


Python calls an external subprocess to implement asynchronous standard input and output through pipes
We usually encounter such needs: a complex functional module is implemented through C++ or other lower-level languages, and a Web-based Demo needs to be built to query data. Due to the power and simplicity of the Python language, it is very suitable for building demos. The Flask framework and jinja2 module functions provide python with convenient web development capabilities. At the same time, python can easily interact with codes in other languages. Therefore, we choose python as the tool for developing Demo. Assume that the module we need to call (providing underlying services) reads data in a loop through standard input, and after processing, writes the results to the marked output. This scenario is very common in the Linux environment and relies on Linux's powerful redirection capabilities. Unfortunately, however, the underlying module has a heavy initialization process, so we cannot re-spawn the child process that calls the underlying module for every query request. The solution is to spawn the child process only once, and then interact with the child process through a pipe for each request.
Python’s subprocess module can easily generate subprocesses, similar to the Linux system calls fork and exec. The Popen object of the subprocess module may call external executable programs in a non-blocking manner, so we use the Poen object to achieve our needs. If we want to write data to the standard input stdin of the subprocess, then we need to specify the parameter stdin as subprocess.PIPE when creating the Popen object; similarly, if we need to read data from the standard output of the subprocess, then in When creating a Popen object, you need to specify the parameter stdout as subprocess.PIPE. Let’s look at a simple example first:
from subprocess import Popen, PIPE p = Popen('less', stdin=PIPE, stdout=PIPE) p.communicate('Line number %d.\n' % x)
The communicate function returns a tuple (stdoutdata, stderrdata), which contains the standard output of the child process and the output data indicating errors. However, since the communicate function of the Popen object blocks the parent process and also closes the pipe, each Popen object can only call the communicate function once. If there are multiple requests, the Popen object must be regenerated (reinitializing the child process), which cannot be satisfied. our needs.
Therefore, we can only achieve our needs by writing and reading data to the stdin and stdout objects of the Popen object. Unfortunately, however, the subprocess module by default only runs and reads standard output once when the subprocess terminates. Both subprocess and os.popen* only allow input and output one time, and the output to be read only when the process terminates.
After some research, I found that the standard output of the subprocess can be output through the fcntl function of the fcntl module Change to a non-blocking method to achieve our purpose. This problem that has been bothering me for a long time has finally been solved perfectly. The code is as follows:
#!/usr/bin/python # -*- coding: utf-8 -*- # author: weisu.yxd@taobao.com from subprocess import Popen, PIPE import fcntl, os import time class Server(object): def __init__(self, args, server_env = None): if server_env: self.process = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, env=server_env) else: self.process = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL) fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) def send(self, data, tail = '\n'): self.process.stdin.write(data + tail) self.process.stdin.flush() def recv(self, t=.1, e=1, tr=5, stderr=0): time.sleep(t) if tr < 1: tr = 1 x = time.time()+t r = '' pr = self.process.stdout if stderr: pr = self.process.stdout while time.time() < x or r: r = pr.read() if r is None: if e: raise Exception(message) else: break elif r: return r.rstrip() else: time.sleep(max((x-time.time())/tr, 0)) return r.rstrip() if __name__ == "__main__": ServerArgs = ['/home/weisu.yxd/QP/trunk/bin/normalizer', '/home/weisu.yxd/QP/trunk/conf/stopfile.txt'] server = Server(ServerArgs) test_data = '在云端', '云梯', '摩萨德', 'Alisa', 'iDB', '阿里大数据' for x in test_data: server.send(x) print x, server.recv()
In addition, when calling some external programs, you may need to specify the corresponding environment variables as follows:
my_env = os.environ my_env["LD_LIBRARY_PATH"] = "/path/to/lib" server = server.Server(cmd, my_env)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
