Popen類的實例有下列方法:shell
檢查子進程是否已經結束,設置並返回返回碼值。less
等待子進程結束,設置並返回返回碼值。
WARNING: 當使用 stdout=PIPE 或 stderr=PIPE 而且子進程生成了足夠多的輸出信息到管道,以致於管道阻塞,將會形成死鎖。
使用 communicate()能夠避免這種狀況。ide
和子進程進行交互: 發送數據到stdin, 從stdout和 stderr讀取數據,直到遇到 end-of-file。等待子進程結束。
可選的 input 參數是一個傳送給子進程的字符串,或 None。
communicate() 返回一個元組(stdoutdata, stderrdata).
NOTE: 若是想發送數據到子進程的 stdin, 須要設置 stdin=PIPE並建立Popen對象。
類似的,要想得到返回結果元組中的非空值,須要設置 stdout=PIPE或 stderr=PIPE.
實際上,讀取的數據是緩衝在內存中,所以,若是數據太大或無限時不要使用這個上方法。函數
發送一個信號 signal到子進程。
NOTE: 在Windows中, SIGTERM是terminate()的別名。ui
中止子程序,在Posix操做系統中,這個方法發送的是SIGTERM到子程序。this
殺死子進程,在Posix操做系統中,這個上函數發送SIGKILL給子進程。
下面的屬性也是一樣有效的:
WARNING: 使用communicate()而不是 .stdin.write, .stdout.read 或 stderr.read,能夠避免因管道阻塞而形成的死鎖。
1. Popen.stdin
若是參數值爲 PIPE, 那麼這個屬性值是一個文件對象,用來提供子進程的輸入。
不然,它的值 爲 None.
2. Popen.stdout
若是參數值爲 PIPE, 那麼這個屬性值是一個文件對象,它提供了子進程的輸出。
不然,值爲 None
3. Popen.stderr
If the stderr argument was PIPE, this attribute is a file object that provides error output from the child process.
Otherwise, it is None.
4. Popen.pid
子進程的進程ID
Note that if you set the shell argument to True, this is the process ID of the spawned shell.
5. Popen.returncode
子進程的返回碼,由poll()和wait()設置(並間接由 communicate()設置)。
非零值表示子進程尚未被結束。
負值 -N 表示子進程被信號N結束。spa
The STARTUPINFO class and following constants are only available on Windows.
1. class subprocess.STARTUPINFO
Partial support of the Windows STARTUPINFO structure is used for Popen creation.
2. dwFlags
A bit field that determines whether certain STARTUPINFO attributes are used when the process creates a window.
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
3. hStdInput
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard input handle for the process. If
STARTF_USESTDHANDLES is not specified, the default for standard input is the keyboard buffer.
4. hStdOutput
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard output handle for the process. Otherwise,
this attribute is ignored and the default for standard output is the console window’s buffer.
5. hStdError
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard error handle for the process. Otherwise,
this attribute is ignored and the default for standard error is the console window’s buffer.
6. wShowWindow
If dwFlags specifies STARTF_USESHOWWINDOW, this attribute can be any of the values that can be specified in the
nCmdShow parameter for the ShowWindow function, except for SW_SHOWDEFAULT. Otherwise, this attribute is ignored.
7. SW_HIDE is provided for this attribute. It is used when Popen is called with shell=True.操作系統
The subprocess module exposes the following constants.
subprocess.STD_INPUT_HANDLE
The standard input device. Initially, this is the console input buffer, CONIN$.
subprocess.STD_OUTPUT_HANDLE
The standard output device. Initially, this is the active console screen buffer, CONOUT$.
subprocess.STD_ERROR_HANDLE
The standard error device. Initially, this is the active console screen buffer, CONOUT$.
subprocess.SW_HIDE
Hides the window. Another window will be activated.
subprocess.STARTF_USESTDHANDLES
Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain
additional information.
subprocess.STARTF_USESHOWWINDOW
Specifies that the STARTUPINFO.wShowWindow attribute contains additional information.
subprocess.CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
This flag is always set when Popen is created with shell=True.
subprocess.CREATE_NEW_PROCESS_GROUP
A Popen creationflags parameter to specify that a new process group will be created.
This flag is necessary for using os.kill() on the subprocess
This flag is ignored if CREATE_NEW_CONSOLE is specified.rest
In this section, 「a becomes b」 means that b can be used as a replacement for a.
Note All 「a」 functions in this section fail (more or less) silently if the executed program cannot be found;
the 「b」 replacements raise OSError instead.
In addition, the replacements using check_output() will fail with a CalledProcessError if the requested operation
produces a non-zero return code. The output is still available as the output attribute of the raised exception.
In the following examples, we assume that the relevant functions have already been imported from the subprocess
module.code
output=`mycmd myarg`
# becomes
output = check_output(["mycmd", "myarg"])
output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.
Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:
output=`dmesg | grep hda`
# becomes
output=check_output("dmesg | grep hda", shell=True)
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
Notes:
Calling the program through the shell is usually not required.
A more realistic example would look like this:
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError as e:
print >>sys.stderr, "Execution failed:", e
P_NOWAIT example:
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
P_WAIT example:
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
Vector example:
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
Environment example:
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}
pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
pipe = os.popen("cmd", 'w', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
child_stdout,
child_stderr) = os.popen3("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
child_stdout,
child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments
will be passed directly to the program without shell intervention. This usage can be replaced as follows:
(child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
bufsize)
==>
p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
Return code handling translates as follows:
pipe = os.popen("cmd", 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
print "There were some errors"
==>
process = Popen("cmd", 'w', shell=True, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
print "There were some errors"
(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
On Unix, popen2 also accepts a sequence as the command to execute, in which case arguments will be passed directly to
the program without shell intervention. This usage can be replaced as follows:
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that:
Popen raises an exception if the execution fails.
the capturestderr argument is replaced with the stderr argument.
stdin=PIPE and stdout=PIPE must be specified.
popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen.
On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):Arguments are delimited by white space, which is either a space or a tab.A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.Backslashes are interpreted literally, unless they immediately precede a double quotation mark.If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.