当前位置: 动力学知识库 > 问答 > 编程问答 >

Use Python to run interactive python scripts

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: