【发布时间】:2016-04-14 20:11:41
【问题描述】:
我正在尝试学习如何编写脚本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 脚本来控制另一个正在运行的脚本。 (例如,可以访问它打印的内容等等)。
- 最后,是否有可能在新的终端中运行
test.py(即不在control.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
【问题讨论】:
-
os.system已弃用;你应该使用subprocess模块 -
要在新终端中运行 test.py,您需要启动该进程,例如
subprocess.call(["xterm", "-e", "python", "test.py", "someargument"]) -
你可能对pexpect感兴趣。
-
@zondo 好样的!你能在这里展示一个例子吗?使用 pexpect
标签: python