python subprocess popen获取进程状态_如何从subprocess.Popen获取退出代码?

在Python中使用subprocess.Popen启动进程后,通过p.returncode获取进程状态总是返回None。这是因为进程尚未完成。为了解决这个问题,可以使用Popen.poll()或者Popen.wait()来等待进程结束并获取退出代码。本文通过示例代码展示了如何正确获取进程的退出状态。
摘要由CSDN通过智能技术生成

使用下面的代码,p.returncode总是None。根据^{} documentation,这意味着进程尚未完成。

为什么我得不到出口代码?import os

import sys

import subprocess

cmd = ['echo','hello']

p = subprocess.Popen(cmd,

stdout=subprocess.PIPE,

stderr=subprocess.STDOUT)

try:

# Filter stdout

for line in iter(p.stdout.readline, ''):

sys.stdout.flush()

# Print status

print(">>> " + line.rstrip())

sys.stdout.flush()

except:

sys.stdout.flush()

print 'RETURN CODE', p.returncode

请注意:我之所以分别阅读每一行,是因为我想实时过滤其他长时间运行的进程的输出,并基于某些字符串停止它们。

我在Python2.7.5(CentOS 7 64位)上。

解决方案

感谢@skyking发布的答案,我现在可以使用Popen.poll()(Popen.wait()死锁的进程)成功捕获这样的退出代码:import os

import sys

import subprocess

import time

cmd = ['echo','hello']

p = subprocess.Popen(cmd,

stdout=subprocess.PIPE,

stderr=subprocess.STDOUT)

try:

# Filter stdout

for line in iter(p.stdout.readline, ''):

sys.stdout.flush()

# Print status

print(">>> " + line.rstrip())

sys.stdout.flush()

except:

sys.stdout.flush()

# Wait until process terminates (without using p.wait())

while p.poll() is None:

# Process hasn't exited yet, let's wait some

time.sleep(0.5)

# Get return code from process

return_code = p.returncode

print 'RETURN CODE', return_code

# Exit with return code from process

sys.exit(return_code)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值