python之子进程

目录

一、如何用 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

可以被传递给 stdinstdout 或 stderr 形参。

如果 PIPE 被传递给 stdin 参数,则 Process.stdin 属性将会指向一个 StreamWriter 实例。

如果 PIPE 被传递给 stdout 或 stderr 参数,则 Process.stdout 和 Process.stderr 属性将会指向 StreamReader 实例。

asyncio.subprocess.STDOUT

可以用作 stderr 参数的特殊值,表示标准错误应当被重定向到标准输出。

asyncio.subprocess.DEVNULL

可以用作 stdinstdout 或 stderr 参数来处理创建函数的特殊值。 它表示将为相应的子进程流使用特殊文件 os.devnull

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值