0

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?

3
  • 1
    If you are using a Unix-style system you might use pipes... Commented Jan 27, 2014 at 11:03
  • Do you Mean something like: subprocess.Popen('./generate_name.py <<< 2', shell= 1) . Yes that would work. Thanks a lot :) Commented Jan 27, 2014 at 11:13
  • 3
    You should probably be using the stdin argument to Popen rather than ever using shell=True (or your less idiomatic version). Commented Jan 27, 2014 at 11:23

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.