我正在尝试学习如何编写一个脚本control.py,它在循环中运行另一个脚本test.py一定次数,在每次运行中,读取其输出并在打印某些预定义输出时暂停它(例如文本’现在停止’),并且循环继续其迭代(一旦test.py完成,无论是单独还是强制).所以有一些事情:
for i in range(n):
os.system('test.py someargument')
if output == 'stop now': #stop the current test.py process and continue with next iteration
#output here is supposed to contain what test.py prints
>上面的问题是,它不会检查test.py正在运行的输出,而是等到test.py进程自行完成,对吧?
>基本上尝试学习如何使用python脚本来控制另一个,因为它正在运行. (例如,可以访问它打印的内容等).
>最后,是否可以在新终端(即不在control.py的终端中)运行test.py并仍然实现上述目标?
尝试:
test.py是这样的:
from itertools import permutations
import random as random
perms = [''.join(p) for p in permutations('stop')]
for i in range(1000000):
rand_ind = random.randrange(0,len(perms))
print perms[rand_ind]
而control.py是这样的:(遵循Marc的建议)
import subprocess
command = ["python", "test.py"]
n = 10
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline().strip()
print output
#if output == '' and p.poll() is not None:
# break
if output == 'stop':
print 'sucess'
p.kill()
break
#Do whatever you want
#rc = p.poll() #Exit Code