Reputation: 175
I have a little test.sh script that I run from the command line ./test.sh
and it will ask me for input to 2 questions that I enter, then it loops till I ctrl-c
out of it.
I want to write a little python script that can run my test.sh
, and enter the inputs to the script questions from variables, var1 and var2 that I set in python.
I also want to have another variable, var3, that loops for x long and runs my test.sh, and ends it then relaunches it every x minutes based on the value of var3
I wrote this code but it doesn't seem to pass the commands into my test.sh
after it launches:
import os
os.system('./test.sh arg1')
time.sleep(10)
sh('input answer 1')
time.sleep(5)
sh('input answer 2')
Currently my code has been updated based on this thread to look like this:
#!/usr/bin/env python
import pexpect
import sys
import os
child = pexpect.spawn ('./test.sh -arg1')
child.expect ('some expected output from the .sh file')
child.expect ('more expected output from the .sh file')
child.expect ('(?i)Enter Username:')
child.sendline ('myusername')
child.expect ('(?i)Enter Password:')
child.sendline ('mypassword')
# sys.stdout.write (child.after)
# sys.stdout.flush()
time.sleep(30)
child.sendcontrol('c')
child.close()
print 'Goodbye'
--fixed-- Now the problem is my timeout or sleep is getting inturrupted, possibly by my .sh script's output. When I run this script with either timeout or time.sleep uncommented, it either has no affect and goes straight down the line to my child.close() and ends the program, or it hangs up the child.sendline ('mypassword') for some reason and I get stuck at my .sh script's password prompt... maybe it's not really stuck there because I can't interact with it. --fixed--
Once I get the script pausing for 30 seconds (or x) then all I will have left to do is make the whole thing loop x times. Finnaly I'll need to add error checking because the .SH responds with different strings of text that can indicate I need to run the script again right away.
Thanks for everyone's help so much!
Upvotes: 1
Views: 577
Reputation: 414079
Using pexpect
:
import pexpect # $ pip install pexpect
while var3: # start ./test.sh again
output = pexpect.run('./test.sh arg1',
timeout=x, # terminate child process after x seconds
events={r'(?i)question 1': var1, # provide answers
r'(?i)question 2': var2})
Note: subprocess
-based solution might be more complex due to buffering issues and it might require additionally pty
, select
modules, example.
Upvotes: 2
Reputation: 3695
import subprocess
p = subprocess.Popen('./test.sh arg1', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
time.sleep(10)
p.stdin.write('input answer 1') #Probably adding \n is necessary
time.sleep(5)
p.stdin.write('input answer 2') #Probably adding \n is necessary
print p.stdout.readline() # To print one-line output of the shell script
Upvotes: 1