I have the following problem, and I will use a simple example to illustrate it. I wrote a python script that requires user interaction, in particular, it uses the raw_input () function to enter the user. The code below simply prompts the user to enter two numbers in a row (by pressing enter between them) and return a response (unexpectedly, unexpectedly, it is called sum_two_numbers.py). Ho-hum!
#! /usr/bin/python
Now I want to write a separate python script that executes the above script and 'feeds' are two required numbers. Therefore, I call this script 'feeder.py'. I tried to write this script using the Python subprocess module, in particular using the "Popen" class and the associated "communication" method. The following is an example script that tries to pass the numbers "5" and "4".
#! /usr/bin/python # ---------- # feeder.py # ---------- import subprocess child = subprocess.Popen("./sum_two_numbers.py",stdin=subprocess.PIPE) child.communicate("5") child.communicate("4")
This code does not work and returns execution errors:
$ ./feeder.py Enter the first number:Enter the second number:Traceback (most recent call last): File "./sum_two_numbers.py", line 6, in <module> b = float(raw_input("Enter the second number:")) EOFError: EOF when reading a line Traceback (most recent call last): File "./feeder.py", line 8, in <module> child.communicate("4") File "/usr/lib/python2.7/subprocess.py", line 740, in communicate self.stdin.write(input) ValueError: I/O operation on closed file
I donβt know how to write "feeder.py" so that it does what I want, these errors bother me. I suspect this error is due to the following comment in the documentation:
Popen.communicate (login = no)
Interaction with the process: sending data to stdin. Reading data from stdout and stderr, while end-of-file. Wait for the process to complete.
I'm not sure what to do with this proposal, and how it can help me ...
Can someone help me with the above script work, for example, how to use the subprocess and Popen correctly ... Or just write a "feeder" script - in any (not too obscure) language! I tried Pexpect, Expect, but ran into problems such as not prompting for child code for input, and I just don't know what it does at all.