I have Python script that takes a User input during runtime and gives some outputs.
l1 = ['Bob', 'Eric', 'Dimitar', 'Kyle']
l2 = ['Scott', 'Mat', 'Con']
n = raw_input('Enter no. of persons: ')
for i in range(int(n)):
print random.choice(l1) + ' ' + random.choice(l2)
Enter no. of persons: 2
Now I want to write another Python script that would run the first python script multiple times with a specific input (the input sequence is stored in a list) and record the outputs in file.
Moreover, I can't make any changes in the first Python Code.
I can use the
subprocess module to run the script and record the output but how do I take care of the interactive User input part?
I see two options: you can either run it as a separate process and indeed use
subprocess, such as
sp = subprocess.Popen(['./generate_name.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) sp.stdin.write("2\n") sp.stdin.close() answer = sp.stdout.read() status = sp.wait()
or you take your script and
exec it. Before you do so, you can redirect
sys.stdout and you can capture and monitor all changes you make. This way, you can run it inside one process.
First, see execute python script multiple times and running script multiple times simultaniously in python 2.7. Alse, see run multiple Python scripts from a single parent script.