您的問題在於您正在嘗試控制一個交互式應用程序。
stdout.read()
將繼續讀取,直到它到達流,文件或管道的末尾。不幸的是,如果是交互式程序,管道只有在程序退出時才關閉;如果您發送的命令不是"quit"
以外的其他命令,則永遠不會。
您將不得不恢復爲使用stdout.readline()
逐行讀取子進程的輸出,並且您最好有一種方法來告訴程序何時準備好接受命令,以及何時發出命令到程序完成,你可以提供一個新的。在像cmd.exe
這樣的程序的情況下,即使readline()
也不能滿足,因爲指示可以發送新命令的行不會被換行符終止,因此必須逐字節地分析輸出。下面是運行cmd.exe
一個示例腳本,找提示,然後發出dir
然後一個exit
:
from subprocess import *
import re
class InteractiveCommand:
def __init__(self, process, prompt):
self.process = process
self.prompt = prompt
self.output = ""
self.wait_for_prompt()
def wait_for_prompt(self):
while not self.prompt.search(self.output):
c = self.process.stdout.read(1)
if c == "":
break
self.output += c
# Now we're at a prompt; clear the output buffer and return its contents
tmp = self.output
self.output = ""
return tmp
def command(self, command):
self.process.stdin.write(command + "\n")
return self.wait_for_prompt()
p = Popen(["cmd.exe"], stdin=PIPE, stdout=PIPE)
prompt = re.compile(r"^C:\\.*>", re.M)
cmd = InteractiveCommand(p, prompt)
listing = cmd.command("dir")
cmd.command("exit")
print listing
如果時間不是重要的,並且不需要交互的用戶,也可以是很簡單,只是爲了批量調用:
from subprocess import *
p = Popen(["cmd.exe"], stdin=PIPE, stdout=PIPE)
p.stdin.write("dir\n")
p.stdin.write("exit\n")
print p.stdout.read()
您的代碼似乎是正確的。從控制檯執行時,console_app是否正常工作?它爲command1返回什麼? – luc 2009-07-14 13:04:21
yes console_app在cmd.exe中運行時正常工作它只是根據提供的輸入(有時是字符串)輸出一些數字 – QAZ 2009-07-14 13:13:41