python Popen 获取输出,等待运行完成

博客围绕Python的Popen展开,主要涉及使用Popen获取输出以及完成运行的相关内容,在信息技术领域中,这对于Python编程和进程管理有一定意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import subprocess

def excuteCommand(com):
    ex = subprocess.Popen(com, stdout=subprocess.PIPE, shell=True)
    out, err  = ex.communicate()
    status = ex.wait()
    print("cmd in:", com)
    print("cmd out: ", out.decode())
    return out.decode()
### Python `subprocess.Popen` 错误处理 当使用 `subprocess.Popen` 执行命令时,可能会遇到各种类型的错误。为了有效捕获并处理这些错误,建议采用以下方法: #### 使用 communicate 方法获取标准输出和标准错误 通过调用 `communicate()` 可以阻塞父进程直到子进程完成执行,并返回一个元组 `(stdout_data, stderr_data)` 。这有助于及时发现程序运行期间产生的任何异常情况。 ```python import subprocess try: process = subprocess.Popen( ['nonexistent_command'], # 故意制造错误用于演示目的 stdout=subprocess.PIPE, stderr=subprocess.PIPE ) output, error = process.communicate() except Exception as e: print(f"An exception occurred while trying to execute the command: {e}") else: if process.returncode != 0: print("The command failed with exit code", process.returncode) if error: print("There was an error during execution:") print(error.decode()) elif output: print("Command executed successfully.") print(output.decode()) ``` 此代码片段展示了如何优雅地处理可能出现的不同种类的错误[^1]。 #### 设置适当的超时时间 有时外部命令可能会长时间挂起而不退出,在这种情况下可以给 `Popen` 对象指定一个合理的超时期限来防止无限等待的情况发生。 ```python timeout_seconds = 5 try: result = subprocess.run(['sleep', '10'], timeout=timeout_seconds) except subprocess.TimeoutExpired: print('The command timed out after {} seconds'.format(timeout_seconds)) ``` 这段例子说明了怎样利用 `run` 函数中的 `timeout` 参数来限定最大允许的时间长度[^3]。 #### 捕捉信号中断和其他特殊情况 对于某些特定平台上的特殊状况(比如被杀死或接收到 SIGINT),可以通过监听相应的状态码来进行针对性处理。 ```python if hasattr(process, "returncode") and isinstance(process.returncode, int): if process.returncode < 0: signal_name = next((name for name in dir(signal) if getattr(signal, name) == -process.returncode), None) print(f"The child process was terminated by signal '{signal_name}'") ``` 上述代码段解释了如果子进程中断,则尝试解析对应的 Unix 信号名称[^2]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值