目录
一、如何用 asyncio 运行一个 shell 命令并获取其结果:
一、如何用 asyncio 运行一个 shell 命令并获取其结果:
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:
# 小贴士:获取windows的命令行编码:窗口中输入命令‘chcp’,返回的活动代码页数字cp+数字即是编码,或者使用locale.getdefaultlocale()来获取编码。
print(f'[stdout]\n{stdout.decode("cp936")}')
if stderr:
print(f'[stderr]\n{stderr.decode("cp936")}')
asyncio.run(run('ping www.baidu.com'))
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:
# 小贴士:获取windows的命令行编码:窗口中输入命令‘chcp’,返回的活动代码页数字cp+数字即是编码,或者使用locale.getdefaultlocale()来获取编码。
print(f'[stdout]\n{stdout.decode("cp936")}')
if stderr:
print(f'[stderr]\n{stderr.decode("cp936")}')
async def main():
await asyncio.gather(
run('dir'),
run('ping www.baidu.com'))
asyncio.run(main())
二、创建子进程
asyncio.create_subprocess_exec()创建子进程
asyncio.create_subprocess_shell()运行 cmd shell 命令。
三、常量
asyncio.subprocess.PIPE
可以被传递给 stdin, stdout 或 stderr 形参。
如果 PIPE 被传递给 stdin 参数,则 Process.stdin 属性将会指向一个 StreamWriter
实例。
如果 PIPE 被传递给 stdout 或 stderr 参数,则 Process.stdout 和 Process.stderr 属性将会指向 StreamReader
实例。
asyncio.subprocess.STDOUT
可以用作 stderr 参数的特殊值,表示标准错误应当被重定向到标准输出。
asyncio.subprocess.DEVNULL¶
可以用作 stdin, stdout 或 stderr 参数来处理创建函数的特殊值。 它表示将为相应的子进程流使用特殊文件 os.devnull。