Subprocess return code is different from "echo $?"

I use a subprocess to invoke the bash command in Python, and I get a different return code than the shell shows me.

import subprocess
def check_code(cmd):
    print "received command '%s'" % (cmd)
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p.wait()
    print "p.returncode is '%d'" % (p.returncode)
    exit()
    if p.returncode == 0:
        return True
    else:
        return False
    #End if there was a return code at all
#End get_code()

When sending "ls / dev / dsk &> / dev / null" check_code returns 0, but "echo $?" produces "2" in the terminal:

Welcome to Dana version 0.7
Now there is Dana AND ZOL

received command 'ls /dev/dsk &> /dev/null'
p.returncode is '0'
root@Ubuntu-14:~# ls /dev/dsk &> /dev/null
root@Ubuntu-14:~# echo $?
2
root@Ubuntu-14:~#

Does anyone know what is going on here?

+4
source share
3 answers

subprocess.Popen, , Python script, sh. POSIX, Bash, , &> /dev/null. sh, Bourne, " stdout /dev/null ".

subprocess.Popen sh, ls , ls sh, 0.

Bash Python, , , , (, ) Python. sh, ls /dev/dsk 2> /dev/null.

+3

xi_, , , "& > " "/dev/null". , .

, "& > /dev/null", . , "& > /dev/null" - .

Welcome to Dana version 0.7
Now there is Dana AND ZOL

received command 'cat /etc/fstab'
p.wait() is 0
p.returncode is '0'

received command 'cat /etc/fstabb'
p.wait() is 1
p.returncode is '1'

received command 'cat /etc/fstab &> /dev/null'
p.wait() is 0
p.returncode is '0'

received command 'cat /etc/fstabb &> /dev/null'
p.wait() is 0
p.returncode is '0'
root@Ubuntu-14:~# cat /etc/fstab &> /dev/null
root@Ubuntu-14:~# echo $?
0
root@Ubuntu-14:~# cat /etc/fstabb &> /dev/null
root@Ubuntu-14:~# echo $?
1
root@Ubuntu-14:~#

"& > /dev/null" , STDERR. stderr = PIPE , . .

- , "& > /dev/null" Python , !

0

subprocess.Popen(cmd, shell=True), cmd .

, /bin/sh . , shell.

, shell=False.

subprocess.Popen(['cmd', 'arg1'], shell=False)

-1

All Articles