Search code examples
pythonpopen

Python: run bash commands sequentially


I am running an executable on a bunch of *.in files in a directory. My script dumps all commands at once. I want to run Popen sequentially after the earlier process has terminated. Here is my script:

import glob, os, subprocess
import sys, re, math

exec_path='/Users/me/path/to/exec'
for name in glob.glob("*.in"):
    print name
    output = name+'.out'
    args = [exec_path, '-o', output, name]
    subprocess.Popen(args)

Thanks for your time.


Solution

  • Sounds like you need to wait for your process to end before moving on with the loop.

    Your example could be rewritten like this;

    import glob
    import subprocess
    
    exec_path='/Users/me/path/to/exec'
    for name in glob.glob("*.in"):
        print name
        output = name + '.out'
        args = [exec_path, '-o', output, name]
        subprocess.Popen(args).wait()  # <- I've added .wait()