I have Python script that takes a User input during runtime and gives some outputs. Example code:

import random
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)

Output:

$ ./generate_name.py 
Enter no. of persons:  2
Kyle  Scott
Eric  Mat

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.stdin and sys.stdout and you can capture and monitor all changes you make. This way, you can run it inside one process.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top