我有一个调用 bash 脚本的 python 脚本。bash 脚本编译了几个模块,我想在运行时看到编译结果打印在屏幕上。
无论如何,最重要的是 bash 脚本在运行时需要用户提供相当多的输入。如何让我的 python 脚本为 bash 脚本提供标准输入/标准输出?
目前我正在使用
(_stat, _resl) = commands.getstatusoutput("./myBashScript")
但是通过这种方式,当 bash 正在运行时,用户不会受到任何提示......
干杯
如果您使用subprocess(如您所愿!)并且不指定 stdin/stdout/stderr,它们将正常运行。例如:
# lol.py
import subprocess
p = subprocess.Popen(['cat'])
p.wait()
$ python lol.py
hello
hello
catting
catting
您也可以随意处理stdout:
# lol.py
import subprocess
p = subprocess.Popen(['cat'], stdout=subprocess.PIPE)
p.wait()
print "\n\nOutput was:"
print p.stdout.read()
$ python lol.py
hello
catting
^D
Output was:
hello
catting
试试envoy 库。
import envoy
r = envoy.connect('./myBashScript')
r.send('input text') # send info on std_in
r.expect('output text') # block until text seen
print r.std_out # print whatever is in the std_out pipe
您可以使用 os.system 为此打开一个终端窗口,例如 gnome-terminal,以运行 bash 脚本。