2012-10-02 110 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

相關問題