使用python运行带有Popen的shell脚本在python命令行和实际程序中的行为有所不同 [英] Use python to run shell script with Popen behaves differently in python command line and actual program

查看:160
本文介绍了使用python运行带有Popen的shell脚本在python命令行和实际程序中的行为有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个想从python程序中调用的shell脚本,但是对于以下代码(已导入Popen)根本不起作用:

I have a shell script that I want to call from a python program, but doesn't work at all with following code(Popen already imported):

bf_dir = '/home/wireless'
bf_path = os.path.join(bf_dir, 'airdispatch.sh')
sh = Popen("sudo " + bf_path, shell=True)
print sh.communicate()

理想情况下,脚本将生成输出文件,但是通过执行上述代码,这些文件不会出现,并且打印"结果为[None, None].我的猜测是"Popen"根本无法执行,或者可能是我在这里犯了一个错误.因此,我在python命令行中运行了以上代码,但事实证明一切正常.那怎么可能呢?请帮助,谢谢.

Ideally, the script will generate output files, but by executing above code, those files don't appear, and the "print" result is [None, None]. My guess is that the "Popen" somehow doesn't get executed at all, or might be that I made a mistake here. So I run above code in python command line, but it turns out that everything works fine. How can that be possible? Please help, thanks.

推荐答案

之所以没有从命令中获得任何输出,是因为您没有告诉子进程打开用于​​通信的管道...

The reason you are not getting any output from the command is because you have not told the subprocess to open pipes for communication...

from subprocess import Popen, PIPE

sh = Popen("sudo %s" % bf_path, shell=True, stdout=PIPE, stderr=PIPE)

现在,通讯将返回stdout和stderr的输出.另外,如果需要输入密码,sudo可能会给您带来麻烦.

Now communicate will return the output of both stdout and stderr. Also, its possible that the sudo might cause you problems if it requires a password input.

这篇关于使用python运行带有Popen的shell脚本在python命令行和实际程序中的行为有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆