Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making python run a file in command line, input something, wait and then input something again

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

like image 793
exklamationmark Avatar asked Nov 15 '11 22:11

exklamationmark


2 Answers

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='
like image 69
Facundo Casco Avatar answered Sep 25 '22 23:09

Facundo Casco


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.

like image 30
slowdog Avatar answered Sep 25 '22 23:09

slowdog