Recently, our boss asked me to write a daemon program to protect the server process. If the server is unfortunately dead, the Guardian can restart the application immediately. Google on the internet a bit, found that Python has a few modules can be created process. In the end I chose to use the Subprocess module because there was a passage in the Python manual:
This module intends to replace several other, older modules and functions, such as:os.system, os.spawn*, os.popen*, popen2.* , commands.*
Subprocess is used to replace some old modules and functions, such as Os.system, os.spawn*, os.popen*, popen2.*, and commands.*. As can be seen, subprocess is the recommended module.
Here is a very simple example of creating a new process, executing App1.exe, passing in the equivalent parameters, and printing out the return value of the process:
The code is as follows:
Import subprocess
ReturnCode = Subprocess.call (' app1.exe-a-b-c-d ')
print ' ReturnCode: ', ReturnCode
#-----Results--------
#Python is powerful
#app1. exe
#-a
#-b
#-c
#-d
returncode:0
App1.exe is a very simple console program that prints only the parameters passed in, and the code is as follows:
The code is as follows:
#include
using namespace Std;
int main (int argc, const char *argv[])
{
cout << "Python is powerful" << Endl;
for (int i = 0; i < argc; i++)
{
cout << Argv[i] << Endl;
}
return 0;
}
Less gossip, the following is a detailed introduction to the Subprocess module. Only one class is defined in the Subprocess module: Popen. You can use Popen to create processes and make complex interactions with processes. Its constructor is as follows:
Subprocess. Popen (args, bufsize=0, Executable=none, Stdin=none, Stdout=none, Stderr=none, Preexec_fn=none, Close_fds=false, shell= False, Cwd=none, Env=none, Universal_newlines=false, Startupinfo=none, creationflags=0)
The parameter args can be a string or sequence type (for example: list, tuple) that specifies the process's executable file and its arguments. If it is a sequence type, the first element is usually the path to the executable file. We can also explicitly use the executeable parameter to specify the path to the executable file. On the Windows operating system, Popen creates a child process by calling CreateProcess (), CreateProcess receives a string parameter, and if args is a sequence type, the system will pass List2cmdline () The function converts a sequence type to a string.
Parameter bufsize: Specifies the buffer. I still do not know the specific meaning of this parameter, look at each Daniel pointing.
The parameter executable is used to specify the executable program. In general, we use the args parameter to set the program to run. If you set the parameter shell to true,executable, the shell will be used by the specified program. Under the Windows platform, the default shell is specified by the COMSPEC environment variable.
The parameters stdin, stdout, stderr respectively represent the standard input, output, and error handles of the program. They can be pipe, file descriptor or file object, or set to none, which means inheriting from the parent process.
The parameter PREEXEC_FN is only valid on UNIX platforms and is used to specify an executable object (callable object) that will be called before the child process runs.
Parameter CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process. We cannot set Close_fds to true while redirecting standard input, output, and error (stdin, stdout, stderr) of child processes.
If the parameter shell is set to True, the program executes through the shell.
The parameter CWD is used to set the current directory of the child process.
The parameter env is a dictionary type that specifies the environment variables for the child process. If env = None, the environment variables of the child process are inherited from the parent process.
Parameter universal_newlines: Under different operating systems, text line breaks are not the same. such as: Under Windows with '/r/n ' for Exchange, and Linux under the '/n '. If this parameter is set to True,python uniform, these newline characters are treated as '/n '.
Parameters Startupinfo and Createionflags are only used under Windows, and they are passed to the underlying CreateProcess () function to set some properties of the child process, such as the appearance of the main window, the priority of the process, and so on.
Subprocess. PIPE
When you create a Popen object, subprocess. Pipe can initialize stdin, stdout, or stderr parameters. Represents a standard stream that communicates with a child process.
Subprocess. STDOUT
When you create a Popen object, the stderr parameter is initialized to indicate that the error is output through the standard output stream.
Methods of Popen:
Popen.poll ()
Used to check whether the child process has ended. Sets and returns the ReturnCode property.
popen.wait ()
Wait for the child process to end. Sets and returns the ReturnCode property.
popen.communicate (Input=none)
Interacts with the child process. Send data to stdin, or read data from stdout and stderr. Optional parameter input Specifies the parameters that are sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to send data to it through the process's stdin, the parameter stdin must be set to pipe when the Popen object is created. Similarly, if you want to get data from stdout and stderr, you must set stdout and stderr to pipe.
popen.send_signal (signal)
Sends a signal to a child process.
Popen.terminate ()
Stop (stop) child process. Under the Windows platform, this method will call Windows API TerminateProcess () to end the child process.
Popen.kill ()
Kills a child process.
Popen.stdin
If the Popen object is created, the parameter stdin is set to Pipe,popen.stdin will return a file object for the policy child process send instruction. Otherwise, none is returned.
Popen.stdout
If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, none is returned.
Popen.stderr
If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, none is returned.
Popen.pid
Gets the process ID of the child process.
Popen.returncode
Gets the return value of the process. Returns none if the process is not finished yet.
Here is a very simple example of how the Supprocess module interacts with a control-desk application.
The code is as follows:
Import subprocess
p = subprocess. Popen ("App2.exe", stdin = subprocess. PIPE,/
stdout = subprocess. PIPE, stderr = subprocess. PIPE, Shell = False)
P.stdin.write (' 3/n ')
P.stdin.write (' 4/n ')
Print P.stdout.read ()
#----Results----
Input x:
Input y:
3 + 4 = 7
App2.exe is also a very simple console program that receives two values from the interface, performs a plus operation, and prints the results to the console. The code is as follows:
The code is as follows:
#include
using namespace Std;
int main (int argc, const char *artv[])
{
int x, y;
cout << "input x:" << Endl;
CIN >> X;
cout << "Input y:" << Endl;
Cin >> y;
cout << x << "+" << y << "=" << x + y << Endl;
return 0;
}
The Supprocess module provides functions that allow us to create processes.
Subprocess.call (*popenargs, **kwargs)
Run the command. The function waits until the child process finishes running and returns the ReturnCode of the process. The first example of this article demonstrates the call function. You can use this function to create a child process if it does not need to interact.
Subprocess.check_call (*popenargs, **kwargs)
As with Subprocess.call (*popenargs, **kwargs), the calledprocesserror exception is triggered only if the child process returns a returncode that is not 0. In the exception object, include the ReturnCode information for the process.
The subprocess module has so much content. In the Python manual, there are examples of how to use subprocess to replace some old modules with old ones. Interested friends can take a look.