您的问题在于您正在尝试控制一个交互式应用程序。
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