Python 子流程返回代码不同于;echo$?”;
我使用subprocess在Python中调用bash命令,得到的返回代码与shell显示的不同Python 子流程返回代码不同于;echo$?”;,python,bash,subprocess,Python,Bash,Subprocess,我使用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.retu
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:~#
有人知道这里发生了什么吗?您将其用作
子流程.Popen(cmd,shell=True)
,并将cmd
用作字符串
这意味着子流程将在引擎盖下调用带有参数的/bin/sh
。因此,您将返回您的shell的退出代码
如果您确实需要退出命令的代码,请将其拆分为列表并使用shell=False
subprocess.Popen(['cmd',arg1',shell=False)
根据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添加到子流程调用中,它就消失了。我只是想在幕后默默地检查输出上的代码
如果有人能解释为什么在Python中向子进程调用添加“&>/dev/null”会导致其异常行为,我很乐意选择它作为答案 根据,Python脚本中使用的shell是sh
。这个shell是POSIX标准,与Bash相反,Bash具有一些非标准特性,例如速记重定向&>/dev/null
由于您的subprocess.Popen
打开一个sh
,它在自己的后台运行ls
,因此使用sh
的返回值代替ls
,在本例中为0
如果您想在Python中使用Bash行为,我相信您可能必须重新配置(可能重新编译)Python本身。只使用sh
语法更简单,它是ls/dev/dsk 2>/dev/null
我认为您看到的是shell的返回代码,而不是ls
的返回代码。p.wait()
的返回值也不正确吗?请记住,不建议使用shell=True
。特别是对于不受信任的用户输入。但是,如果需要&>/dev/null
,则无法避免使用shell。此外,shell的退出代码应该是最后一个运行的命令的退出代码。我们使用bash作为shell,但是python使用sh
,它对&>
的解释与bash不同。