5

In python, I wanted to do the following: I have a command-line program that requires user to enter input step by step & wait in between to get the result. Now, I want to automate this process using python.

The process will be something like:

  • run myProgram.exe in commandline
  • enter command 1
  • wait for command 1 to run & finish (takes ~5 minutes)
  • enter command 2 ...

is there a way to simulate this process in python? I knew that we can run a program & pass in command line parameters using os.open() or subprocess. But those are a one-off thing.

Thanks

2 Answers 2

3

You can use subprocess module and Popen.communicate() to send data to the process stdin

EDIT:

You are right, he should use stdin.write to send data, something like this:

#!/usr/bin/env python

import subprocess
import time

print 'Launching new process...'
p = subprocess.Popen(['python', 'so1.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

print 'Sending "something"...'
p.stdin.write('something\n')

print 'Waiting 30s...'
time.sleep(30)

print 'Sending "done"...'
p.stdin.write('done\n')

p.communicate()
print '=o='
Sign up to request clarification or add additional context in comments.

1 Comment

Popen.communicate blocks until the process terminates, so the "enter command 2" part won't be possible.
2

On Unix, or with cygwin python on Windows, the pexpect module can automate interactive programs.

See the examples here. You'll want to pass a longer-than-default timeout argument to expect() for the part that takes five minutes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.