Python check_output error with exit status 1 but Popen works for the same command

The command is framed to determine if Xcode works on a Mac: cmd = "ps -ax | grep -v grep | grep Xcode"

If Xcode does not work, then the command above works well with Popenthe module method subprocess, but calls method CalledProcessErrorc check_output. I tried to check stderrfor the following code, but could not get the relevant 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

The exception message is as follows:

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

Question: Why does the above command work with Popen, but with a check_output error?

Note. The team works well with both approaches if Xcode is running.

+4
source share
4 answers

check_output() , . 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 .

: , , :

#!/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 :

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

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

Python: " , CalledProcessError.". , Xcode ; grep Xcode , grep Xcode, . , check_output() .

, Python.

+2

grep grep Xcode , returncode , check_output CalledProcessError, print

, , : -

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

psCmd = "ps -aef | grep -v grep | grep Xcode"
o = None
o = check_output(psCmd+";exit 0", stderr=STDOUT, shell=True)

check_output , 0 .

+1

check_output - , . , grep Xcode .

, Python, .

output = check_output(['ps', '-ax'], shell=False)
if 'Xcode' in output:
    print('Xcode appears to be running')

( ) , , - ps. ps, .

0

All Articles