Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One Python script giving "user input" to another python script

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 :)

like image 917
Jumping cat Avatar asked Dec 16 '22 01:12

Jumping cat


1 Answers

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')
like image 150
user2357112 supports Monica Avatar answered Dec 26 '22 07:12

user2357112 supports Monica