代码之家  ›  专栏  ›  技术社区  ›  rety

在同一控制台中连续执行程序多次

  •  -1
  • rety  · 技术社区  · 6 年前

    我想每次都用不同的参数在一个循环中执行一个程序多次,但是每次都避免打开新的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

    1 回复  |  直到 6 年前
        1
  •  0
  •   Addison Lynch    6 年前

    在这种情况下,你应该设置参数 shell=True 是的。下面是一个例子:

    说你想跑 foo 10次从 bar 以下内容:

    食品

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

    酒吧.py

    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