我正在使用 subprocess 在 Python 中调用 bash 命令,但我得到的返回码与 shell 显示的不同。
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()
当发送“ls/dev/dsk &>/dev/null”时,check_code 返回 0,但“echo $?”在终端中产生“2”:
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:~#
有人知道这里发生了什么吗?
最佳答案
根据 subprocess.Popen
,您的 Python 脚本中使用的 shell 是 sh
。此 shell 是 POSIX 标准,与 Bash 不同,Bash 具有多个非标准功能,例如简写重定向 &>/dev/null
。 sh
,Bourne shell,将此符号解释为“在后台运行我,并将 stdout 重定向到/dev/null”。
由于您的 subprocess.Popen
打开了一个 sh
,它在自己的后台运行 ls
,sh
的返回值使用 code> 代替 ls
,在本例中为 0。
如果您希望 Python 具有 Bash 行为,我相信您可能必须重新配置(可能是重新编译)Python 本身。仅使用 sh
语法更简单,即 ls/dev/dsk 2>/dev/null
。
关于python - 子进程返回代码不同于 "echo $?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36318777/