本文介绍了python check_output失败,退出状态为1,但Popen适用于同一命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于标识Xcode是否在Mac上运行的命令:cmd = "ps -ax | grep -v grep | grep Xcode"

Command framed to identify if Xcode is running on Mac: cmd = "ps -ax | grep -v grep | grep Xcode"

如果Xcode没有运行,则上述命令在subprocess模块的Popen方法中可以很好地工作,但是在check_output方法中引发CalledProcessError.我试图通过以下代码检查stderr,但未能获得适当的信息以了解原因.

If Xcode is not running, then above command works well with Popen method of subprocess module, but raises a CalledProcessError with check_output method. I tried to inspect the stderr through the following code, but failed to get appropriate information to understand the reason.

from subprocess import check_output, STDOUT, CalledProcessError

psCmd = "ps -ax | grep -v grep | grep Xcode"
o = None
try:
    o = check_output(psCmd, stderr=STDOUT, shell=True)
except CalledProcessError as ex:
    print 'Error:', ex, o

异常消息如下:

Error: Command 'ps -ax | grep -v grep | grep Xcode' returned non-zero exit status 1 None

问题:为什么上面的命令可以在Popen中使用,而在check_output中不能使用?

Question: Why the above command works with Popen, but fails with check_output ?

注意:如果Xcode正在运行,则命令对这两种方法均适用.

Note: Command works well with both approach, if Xcode is running.

推荐答案

check_output()可以正常工作.这是根据Popen()简化的实现:

check_output() works as expected. Here's its simplified implementation in terms of Popen():

def check_output(cmd):
    process = Popen(cmd, stdout=PIPE)
    output = process.communicate()[0]
    if process.returncode != 0:
        raise CalledProcessError(process.returncode, cmd, output=output)
    return output

grep如果未找到任何内容,则返回1,即,如果Xcode没有运行,则应该期望该异常.

grep returns 1 if it hasn't found anything i.e., you should expect the exception if Xcode is not running.

注意:如实现所示,即使发生异常,您也可以获取输出:

Note: as the implementation shows, you can get the output even if the exception occurs:

#!/usr/bin/env python
from subprocess import check_output, STDOUT, CalledProcessError

cmd = "ps -ax | grep -v grep | grep Xcode"
try:
    o = check_output(cmd, stderr=STDOUT, shell=True)
    returncode = 0
except CalledProcessError as ex:
    o = ex.output
    returncode = ex.returncode
    if returncode != 1: # some other error happened
        raise

您可能可以改用pgrep -a Xcode命令(注意:以p开头)或使用psutil模块获取可移植代码:

You could probably use pgrep -a Xcode command instead (note: starts with p) or use psutil module for a portable code:

#!/usr/bin/env python
import psutil # $ pip install psutil

print([p.as_dict() for p in psutil.process_iter() if 'Xcode' in p.name()])

这篇关于python check_output失败,退出状态为1,但Popen适用于同一命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:18