2012-10-02 68 views
1

我在写一个调用命令行(例如python本身)的Python代码,该命令将打开它自己的shell。 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

它可以不是一个“插入”命令。 subprocess不与交互式shell进行交互。

您需要使用stdin=PIPE第一子的写'i 2\n'该管道。

考虑使用pexpect但如果你想与互动节目互动。它可能会让你的生活变得更容易。

+1

或['winpexpect'(https://bitbucket.org/geertj/winpexpect/wiki/Home)在Windows – jfs

0

看看subprocess.Popen.communicate()。如果只是接收一些线路并将命令发送到另一个进程,那应该是您要查找的内容。

一些示例:

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

我已经修改了我的代码,并有一个错误。 %1不是有效的win32应用程序。我正在运行一个Linux命令。 – Ashton

+0

不要在谜语中说话。告诉我们您的确切命令,您使用过的,然后按照原样复制错误。我的例子也来自Linux。 – Michael

+0

Pout,perr = Popen(['./ cmdl'],stdin = PIPE,stdout = PIPE,stderr = PIPE).communicate('i 2 \ n')这是正确的吗?对不起,我在Python中很新。 – Ashton

相关问题