views:

323

answers:

1

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 except 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!

A: 

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.

bua
Ok I just tried that and I still have the same problem. Thanks though!
Bozzy
Theoretically it's `\r\n` and not `\n\r`, not sure if that makes a difference for your application. To avoid transforming the strings you can set the optional `universal_newlines` parameter to True when calling Popen. Normally on Windows the pipes are opened in binary mode and indeed, if you don't use this option you have to do as bua suggested (plus something else apparently). So independently of your problem, use this option or add `\r\n`.
RedGlyph
Please review last update.
bua