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

### 使用Python的subprocess模块运行子进程中的.py文件 通过 `subprocess` 模块,可以方便地启动并运行另一个 Python 脚本。以下是一个详细说明和示例代码。 #### 1. 基本用法 要运行另一个 `.py` 文件,可以使用 `subprocess.run()` 函数[^2]。此函数允许传递命令及其参数,并且可以通过设置选项来控制子进程的行为。例如,可以通过指定 `shell=True` 来启用 shell 特性,或通过 `check=True` 确保命令成功执行[^3]。 ```python import subprocess # 定义目标脚本路径 script_path = 'path/to/your/script.py' # 使用subprocess.run()运行脚本 result = subprocess.run(['python', script_path], capture_output=True, text=True) # 输出结果 print("标准输出:", result.stdout) print("标准错误:", result.stderr) ``` #### 2. 获取子进程的输出 如果需要捕获子进程的标准输出和标准错误,可以使用 `capture_output=True` 和 `text=True` 参数。这将使 `stdout` 和 `stderr` 属性返回字符串而不是字节流。 ```python try: output = subprocess.check_output(['python', script_path], stderr=subprocess.STDOUT, text=True) print("脚本输出:", output) except subprocess.CalledProcessError as e: print(f"脚本执行失败,退出码为 {e.returncode}") print("错误信息:", e.output) ``` #### 3. 创建管道 在某些情况下,可能需要将一个命令的输出作为另一个命令的输入。这可以通过创建管道实现。例如,可以将 `ps` 的输出传递给 `grep`[^4]。 ```python ps = subprocess.Popen(('ps', 'aux'), stdout=subprocess.PIPE) grep = subprocess.Popen(('grep', 'python'), stdin=ps.stdout, stdout=subprocess.PIPE) ps.stdout.close() output = grep.communicate()[0] print(output.decode()) ``` #### 4. 并行运行多个子进程 如果需要同时运行多个 `.py` 文件,可以使用多个 `subprocess.Popen()` 实例[^5]。每个实例代表一个独立的子进程。 ```python import subprocess # 定义多个脚本路径 scripts = ['script1.py', 'script2.py', 'script3.py'] # 启动多个子进程 processes = [] for script in scripts: process = subprocess.Popen(['python', script]) processes.append(process) # 等待所有子进程完成 for process in processes: process.wait() ``` ### 注意事项 - **路径问题**:确保提供的脚本路径是正确的,最好使用绝对路径。 - **错误处理**:建议使用 `try-except` 块捕获 `subprocess.CalledProcessError` 异常以处理可能的错误。 - **资源管理**:当使用管道时,务必关闭不再需要的文件描述符(如 `ps.stdout.close()`),以避免资源泄漏[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

文子阳

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

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

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

打赏作者

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

抵扣说明:

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

余额充值