子行程¶
原始碼:Lib/asyncio/subprocess.py、Lib/asyncio/base_subprocess.py
This section describes high-level async/await asyncio APIs to create and manage subprocesses.
Here's an example of how asyncio can run a shell command and obtain its result:
import asyncio
async def run(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
asyncio.run(run('ls /zzz'))
會印出:
['ls /zzz' exited with 1]
[stderr]
ls: /zzz: No such file or directory
Because all asyncio subprocess functions are asynchronous and asyncio provides many tools to work with such functions, it is easy to execute and monitor multiple subprocesses in parallel. It is indeed trivial to modify the above example to run several commands simultaneously:
async def main():
await asyncio.gather(
run('ls /zzz'),
run('sleep 1; echo "hello"'))
asyncio.run(main())
另請參閱Examples。
建立子行程¶
- async asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=None, **kwds)¶
建立一個子行程。
The limit argument sets the buffer limit for
StreamReaderwrappers forstdoutandstderr(ifsubprocess.PIPEis passed to stdout and stderr arguments).回傳一個
Process實例。See the documentation of
loop.subprocess_exec()for other parameters.If the process object is garbage collected while the process is still running, the child process will be killed.
在 3.10 版的變更: 移除了 loop 參數。
- async asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)¶
執行 cmd shell 命令。
The limit argument sets the buffer limit for
StreamReaderwrappers forstdoutandstderr(ifsubprocess.PIPEis passed to stdout and stderr arguments).回傳一個
Process實例。See the documentation of
loop.subprocess_shell()for other parameters.If the process object is garbage collected while the process is still running, the child process will be killed.
重要
It is the application's responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid shell injection vulnerabilities. The
shlex.quote()function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands.在 3.10 版的變更: 移除了 loop 參數。
備註
Subprocesses are available for Windows if a ProactorEventLoop is
used. See Subprocess Support on Windows
for details.
也參考
asyncio also has the following low-level APIs to work with subprocesses:
loop.subprocess_exec(), loop.subprocess_shell(),
loop.connect_read_pipe(), loop.connect_write_pipe(),
as well as the Subprocess Transports
and Subprocess Protocols.
常數¶
- asyncio.subprocess.PIPE¶
Can be passed to the stdin, stdout or stderr parameters.
If PIPE is passed to stdin argument, the
Process.stdinattribute will point to aStreamWriterinstance.If PIPE is passed to stdout or stderr arguments, the
Process.stdoutandProcess.stderrattributes will point toStreamReaderinstances.
- asyncio.subprocess.STDOUT¶
Special value that can be used as the stderr argument and indicates that standard error should be redirected into standard output.
- asyncio.subprocess.DEVNULL¶
Special value that can be used as the stdin, stdout or stderr argument to process creation functions. It indicates that the special file
os.devnullwill be used for the corresponding subprocess stream.
與子行程互動¶
Both create_subprocess_exec() and