【发布时间】:2016-07-19 01:02:51
【问题描述】:
我正在使用 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:~#
有人知道这里发生了什么吗?
【问题讨论】:
-
我认为您看到的是 shell 的返回码,而不是
ls的返回码。 -
p.wait()的返回值是不是也有误? -
请记住,不建议使用
shell=True。尤其是对于不受信任的用户输入。
标签: python bash subprocess