python中借助subprocess产生和关闭子进程

用python的subprocess这个模块来产生子进程,并连接到子进程的标准输入/输出/错误中去,还可以得到子进程的返回值。

Subprocess.Popen开启子进程的方法(cmds为命令)

关闭子进程的方法(开启子进程后一定要关闭!)

注意:subprocess模块里的kill和terminate方法都可以杀掉子进程;

在杀掉进程后要执行wait方法等待子进程终止;返回self.returncode

不执行wait方法的后果:

调用异步函数,没有关键字await

 

### Python `subprocess` 模块详解 #### 功能概述 `subprocess` 模块用于生成新的进程,连接到它们的输入/输出/错误管道,并获取返回的状态码。相比旧的方法如 `os.system()` 更加灵活强大[^3]。 #### 主要优势 - 可以获得子进程的标准输出标准错误流。 - 提供更好的错误处理机制。 - 支持复杂的子进程操作,比如设置环境变量、改变工作目录等。 - 替代多个老旧模块方法,统一接口设计[^4]。 #### 常见函数介绍 ##### 1. `subprocess.run()` 自 Python 3.5 版本引入,推荐作为主要API使用。此函数执行给定命令并等待完成,然后返回一个包含结果信息的对象 (`CompletedProcess`)。可以通过传递不同参数控制行为: ```python import subprocess result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(f"Return code: {result.returncode}") if result.stdout: print('Have stdout:') print(result.stdout) else: print('No output.') ``` ##### 参数说明: - **args**: 执行的命令及其参数,通常为列表形式; - **capture_output**: 是否捕捉标准输出标准错误,默认 False; - **text**: 若设为 True 则将字节串转换成字符串; - **check**: 当命令失败时抛出异常; - **timeout**: 设置超时时长; ##### 2. `subprocess.call()` 简单地运行指定命令而不关心其输出内容,只关注最终退出状态。适用于不需要进一步处理输出的情况。 ```python ret_code = subprocess.call(["echo", "Hello world"]) print(ret_code) # 输出应为0表示成功 ``` ##### 3. `subprocess.check_call()` 类似于 `call()` 函数但是会在遇到非零退出状态时报错。 ```python try: ret_code = subprocess.check_call(["false"]) # 此处故意触发错误 except subprocess.CalledProcessError as e: print(e) ``` ##### 4. `subprocess.check_output()` 专门用来收集命令产生的输出数据,如果命令失败也会报错。 ```python output = subprocess.check_output(["echo", "hello"], universal_newlines=True) print(output.strip()) ``` #### 实际应用场景举例 假设有一个需求是要批量压缩文件夹内的图片资源,在 Linux 下可以借助 ImageMagick 工具实现这一目标。下面是一段简单的脚本来展示如何利用 `subprocess` 来调用外部程序 mogrify 对图像进行缩放处理: ```bash #!/usr/bin/env python3 import os from pathlib import Path import subprocess def resize_images(directory_path, width=800): """Resize all images within a directory to specified maximum width.""" image_files = list(Path(directory_path).glob('*.{jpg,jpeg,png,gif}')) for img_file in image_files: try: cmd = ['mogrify', '-resize', f'{width}>', str(img_file)] completed_process = subprocess.run(cmd, check=True, timeout=60) except (FileNotFoundError, PermissionError) as err: print(f'Failed to execute command due to error: {err}') except subprocess.TimeoutExpired: print(f'Timeout occurred while processing file "{img_file}"') else: print(f'Successfully resized "{img_file.name}"') if __name__ == '__main__': dir_to_resize = '/path/to/images' if not os.path.isdir(dir_to_resize): raise NotADirectoryError(f'Directory does not exist or is invalid: {dir_to_resize}') resize_images(dir_to_resize) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值