-1

I want to excute a program multiple times in a loop with diffrenet argument eveytime, but avoid opening new coonsole window everytime.
I tried os.system(), Popen but no success.

example for what I tried:

from subprocess import Popen, PIPE

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

also tried using & ; pause

rety
  • 59
  • 1
  • 6

1 Answers1

0

I this case you should set the parameter shell=True. Here's an example:

Say you want to run foo 10 times from bar:

foo.py

import sys

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

bar.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'))

After running python bar.py, we have the file:

result.txt

1
2
3
4
5
6
7
8
9
10

stdout

debug

debug

debug

...

debug
Addison Lynch
  • 685
  • 5
  • 12
  • but shell=true won't show me console at all, right? I prefer to see it to know how the progress going – rety Jul 04 '18 at 08:03
  • With `shell=True`, "the shell defaults to `/bin/sh`". Also, I've updated my answer with this requirement. This will print a dump of the output of each iteration once it is completed. For a live view of the output of the scripts, see the examples [here](https://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running). – Addison Lynch Jul 04 '18 at 08:22