this is my first question, I hope I'm doing this right. let's say I have these this file:
"simple.py":
a=raw_input("your name?")
print "Hello",a
but with a different script, I want to execute "simple.py" many time and giving the input automatically, that would work like:
"everyone.py"
run simple.py input=Alice
run simple.py input=Bob
...
to get "Hello Alice" "Hello Bob" ...
I know it's possible to make "everyone.py" run "simple.py" by using os.system, but is there any practical way to do something like this? And what if the first script asks for input several times?
It's important that I CANNOT EDIT SIMPLE.PY, only the other file
Thanks in advance :)
For a case as simple as simple.py
, you should be able to use subprocess.Popen
:
import subprocess
child = subprocess.Popen(['python', 'simple.py'], stdin=subprocess.PIPE)
child.communicate('Alice')
For more complex cases, the Pexpect module may be useful. It helps automate interaction with normally-interactive programs by providing more convenient, robust interfaces to send input, wait for prompts, and read output. It should work in cases where Popen
doesn't work or is more annoying.
import pexpect
child = pexpect.spawn('python simple.py')
child.expect("your name?")
child.sendline('Alice')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With