开发者

Problem Using Python's subprocess.communicate() on Windows

开发者 https://www.devze.com 2022-12-09 12:53 出处:网络
I have an application that I am trying to control via Python and the subprocess module.Essentially what I do is start the application using Popen (which opens a command prompt within which the program

I have an application that I am trying to control via Python and the subprocess module. Essentially what I do is start the application using Popen (which opens a command prompt within which the program executes) and then at some point in time later on in the execution I need to send a string (a command) to the STDIN of that program. That works fine excep开发者_JAVA百科t for the fact that the command doesn't get processed until I manually type a button into the command window of the application that Python has started. Here is part of my code:

cmd = 'quit\n'
app.communicate(cmd.encode('utf-8'))

Any ideas?

EDIT #1

Yes typing a button does mean pressing a key on the keyboard, sorry for the confusion. I've attached more of my code below

app = Popen(['runProg.exe', '-m', '20'], stdin=PIPE, universal_newlines=True)
while not os.path.exists('C:/temp/quit-app.tmp'): time.sleep(1)
app.communicate('quit')
os.remove('C:/temp/quit-app.tmp')

So what should happen is the program should run until the quit-app.tmp file is created; once it's created "quit" should be sent to the application, which is a command for it to shut down cleanly. If a human was running this program, they'd do this just by typing "quit" in the command window. Thanks!


try:

cmd = 'quit\n\r'

EDIT:

Only thing that is working for me is:

app = subprocess.Popen(["cmd.exe","testparam"],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
app.stdin.write('exit\r\n')

Because as documentation says:

Popen.communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号