gpt4 book ai didi

python - 从另一个脚本控制Python脚本

转载 作者:行者123 更新时间:2023-11-30 22:57:29 25 4
gpt4 key购买 nike

我正在尝试学习如何编写脚本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是这样的:(按照马克的建议)

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

最佳答案

您可以使用 subprocess 模块或 os.popen

os.popen(command[, mode[, bufsize]])

打开与命令之间的管道。返回值是连接到管道的打开文件对象,可以根据模式是“r”(默认)还是“w”来读取或写入该文件对象。

对于子流程,我建议

subprocess.call(['python.exe', command])

或者 subprocess.Popen --> 类似于 os.popen(例如)

使用popen,您可以读取连接的对象/文件并检查是否存在“立即停止”。

os.system 并未被弃用,您也可以使用(但您不会从中获得对象),您只需检查执行结束时是否返回即可。

从 subprocess.call 中,您可以在新终端中运行它,或者如果您只想多次调用 test.py --> ,您可以将脚本放入 def main() 中并运行 main 尽可能多您想要直到生成“立即停止”为止。

希望这能解决您的疑问:-)否则请再次发表评论。

看看上面写的内容,您还可以直接从操作系统调用将输出重定向到文件 --> os.system(test.py *args >>/tmp/mickey.txt) 然后您可以检查每个将文件绕圆。

如上所述,popen 是一个您可以访问的目标文件。

关于python - 从另一个脚本控制Python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com