Python - 打开一个打开另一个shell的命令

时间:2012-10-02 10:42:02

标签: python

我正在编写一个调用命令行的Python代码(例如python本身),该命令将打开自己的shell。 Python如何控制这个shell?

import subprocess
subprocess.call(['./testprg'])

# testprg will open its own shell 
# so the code below will not work
subprocess.call(['i 2'])

testprg是另一个打开shell提示符的程序。输入“i 2”将触发值为2的“插入”命令。

2 个答案:

答案 0 :(得分:2)

它不能。 subprocess不与交互式shell进行交互。

您需要在第一个子流程中使用stdin=PIPE对该管道进行写'i 2\n'

如果您想与交互式程序进行交互,请考虑使用pexpect。它可能会让你的生活更轻松。

答案 1 :(得分:0)

看看subprocess.Popen.communicate()。如果它只是接收一些行并将命令发送到另一个进程,它应该是您正在寻找的。

一些例子:

pout, perr = Popen([tools['PASSWD'], username], stdin=PIPE, stdout=PIPE,
        stderr=PIPE).communicate("%s\n%s\n" % (password, password))