从蟒蛇bash的交互 [英] Interacting with bash from python
问题描述
我一直在玩弄Python的子
模块,我想从蟒蛇的bash做一个互动会议。我希望能够从Python的读取庆典输出/写命令,就像我在一个终端仿真器做的。我猜code例子解释更好:
I've been playing around with Python's subprocess
module and I wanted to do an "interactive session" with bash from python. I want to be able to read bash output/write commands from Python just like I do on a terminal emulator. I guess a code example explains it better:
>>> proc = subprocess.Popen(['/bin/bash'])
>>> proc.communicate()
('user@machine:~/','')
>>> proc.communicate('ls\n')
('file1 file2 file3','')
(很明显,它不这样的。)是这样的可能,怎么样?
(obviously, it doesn't work that way.) Is something like this possible, and how?
非常感谢
推荐答案
尝试用这个例子:
import subprocess
proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('ls -lash')
print stdout
您已经阅读有关标准输入,输出和错误。这看起来像好的演讲:<一href=\"http://www.doughellmann.com/PyMOTW/subprocess/\">http://www.doughellmann.com/PyMOTW/subprocess/
You have to read more about stdin, stdout and stderr. This looks like good lecture: http://www.doughellmann.com/PyMOTW/subprocess/
编辑:
另外一个例子:
>>> process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> process.stdin.write('echo it works!\n')
>>> process.stdout.readline()
'it works!\n'
>>> process.stdin.write('date\n')
>>> process.stdout.readline()
'wto, 13 mar 2012, 17:25:35 CET\n'
>>>
这篇关于从蟒蛇bash的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!