Python 2.7获取命令stdout / stderr

时间:2017-01-17 21:54:53

标签: python python-2.7

我在Python 2.7中使用子进程模块。我的代码看起来像

cmd = 'unrar l -p%s %s' % (pwd, filename)
proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(output, err) = proc.communicate() 

此代码在Windows 7/10上运行正常,但在Ubuntu 16.04上不起作用。我调试并看到变量err为空,在Windows上包含错误消息。变量输出包含命令的帮助消息。看起来命令是在没有任何选项的情况下运行的。

如果这不是运行命令并获取其stdout / stderr输出的正确方法,那么正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

感谢Jean-FrançoisFabre提供的提示,我删除了Using roughly your approach ... https://tse2.mm.bing.net/th?id=OIP.Me19820ab68b4bcc7ec82756b2b5ecffbo1&pid=Api https://tse3.mm.bing.net/th?id=OIP.Mcbb568859281f5bc7a7f64d8c58d4895H1&pid=Api https://tse3.mm.bing.net/th?id=OIP.Mb6ca65eda578c80e71f4c3b3193c5b67H1&pid=Api https://tse2.mm.bing.net/th?id=OIP.M65fe5bf16283dc466e93650fbaef1205o1&pid=Api https://tse3.mm.bing.net/th?id=OIP.M5d9fb4d528228cb5c8b9748bff10365bo1&pid=Api Using a regular expression ... https://tse2.mm.bing.net/th?id=OIP.Me19820ab68b4bcc7ec82756b2b5ecffbo1&pid=Api https://tse3.mm.bing.net/th?id=OIP.Mcbb568859281f5bc7a7f64d8c58d4895H1&pid=Api https://tse3.mm.bing.net/th?id=OIP.Mb6ca65eda578c80e71f4c3b3193c5b67H1&pid=Api https://tse2.mm.bing.net/th?id=OIP.M65fe5bf16283dc466e93650fbaef1205o1&pid=Api https://tse3.mm.bing.net/th?id=OIP.M5d9fb4d528228cb5c8b9748bff10365bo1&pid=Api 参数,程序运行正常。我想我需要阅读shell=True上的文档来弄清楚为什么在Windows上我需要subprocess.Popen()而在Ubuntu上我没有,但是现在我很高兴。