在相同的条件下连续多次执行一个程序

2024-09-30 14:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想每次都用diffenet参数在循环中多次执行程序,但避免每次都打开新的coonsole窗口。
我试过os.system()Popen,但没有成功

我尝试的例子:

from subprocess import Popen, PIPE

for i in range(10):
    process = Popen("myProgram.exe i", shell=False,stdin=PIPE,stdout=PIPE,stderr=PIPE)

还尝试使用&;pause


Tags: infromimportfor参数osrangesystem
1条回答
网友
1楼 · 发布于 2024-09-30 14:23:02

在这种情况下,您应该设置参数shell=True。举个例子:

假设要从bar运行foo10次:

foo.py

import sys

with open("result.txt", "a") as f:
    print("debug")
    f.write(sys.argv[1])

条形图

import subprocess

for i in range(10):
    CMD = "python foo.py %s" % i
    p = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE))
    print(p.stdout.read().decode('utf-8'))

运行python bar.py之后,我们得到了以下文件:

结果.txt

1
2
3
4
5
6
7
8
9
10

标准输出

debug

debug

debug

...

debug

相关问题 更多 >