여기서 대화 형 응용 프로그램을 제어하려고합니다.
stdout.read()
은 스트림, 파일 또는 파이프의 끝에 도달 할 때까지 계속 읽습니다. 불행하게도, 대화 형 프로그램의 경우, 파이프는 닫히고 whe 프로그램은 종료됩니다. 그건 당신이 보낸 명령이 "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
예 cmd.exe에서 실행하면 console_app가 정상적으로 작동합니다. 제공된 입력 (그리고 때로는 문자열)을 기반으로 일부 숫자 만 출력합니다. – QAZ