November 26th, 2012, 08:03 AM
Subprocess - then read - then write to same shell?
Please can someone explain how to do this:
I want to make some commands in a shell - read the output and based on the output make another input in the same shell
I have looked at readlines, stdin.write etc but I am lost as to what the solution will be. It seems that as soon as I 'read' the output the process is then closed preventing me from giving any further inputs. If I open a new shell then its no good - because the 2nd commands must come after the 1st (if it meets a condition).
p = subprocess.Popen('some_program', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
out, err = p.communicate()
if "abcdefg" in out:
p.communicate(input = ' -c -d 1234')
out, err = p.communicate()
if "xyz" in out:
print "I have been able to open a shell, read the output and give another command to the same shell"
November 26th, 2012, 10:14 AM
Others and I solve this problem by searching the subprocess output for a known prompt. At that point we know the shell is ready for new input.
[/code] are essential for python code and Makefiles!
November 26th, 2012, 10:57 AM
But how do you do that? Once you have read the output it appears to then close it - so that you can't write anything else. What command do you use to search and what are you searching in?
Originally Posted by b49P23TIvg
November 26th, 2012, 11:20 AM
November 27th, 2012, 07:06 AM
Much appreciated for your quick and informative replies!
I have looked through but I'm still doubtful that subprocess can solve my problem - it seems once you search or read the output that the pipe is then closed.
I have however discovered the addon module 'pexpect'.
For example the following works:
Create two python files as below - the first must be called login.py (only because we call that specific file from the test.py main file - which is what we run). Test both cases by first entering correct password (password) and secondly entering an incorrect password ( =! password)
I will experiment on my main set up to see if this will do its job in the project im working on.
passw = raw_input('Enter PASS: ')
if passw == 'password':
raw_input('You are logged in')
/////// test.py /////////
child = pexpect.spawn('python login.py')
index = child.expect ('PASS')
password = raw_input('Please enter your password: ')
index = child.expect (['logged in', 'Incorrect'])
if index ==0:
print "Test output ===> you are logged in"
if index ==1:
print "Test output ===> your password was incorrect"
raw_input('\nPress any key to quit')
November 27th, 2012, 02:52 PM
Yes, the above works well when applied to my main project. This has helped me to reach a milestone today!
thanks for comments