Ubuntu – run command-line commands within a python script

command linepythonscripts

Sorry I'm kind of a noob at this:

Basically I've downloaded this package that deals with text files that is run from the terminal, but the command I need takes in two arguments. I also need to do this many times (5000+).

I need to get these arguments with a python script, and can loop it many times using python. So could I get the arguments within the python script, run the command-line line, and loop it? How?

Thanks!

Best Answer

Here's a fish...

import popen2, sys

def loopy_subprocess(arga, argb, iterations, command = 'echo'):
    for i in range(int(iterations)):
        p = popen2.Popen4((command, arga, argb))
        p.wait()
        print(p.fromchild.readlines())

if __name__ == '__main__':
    try:
        arga = sys.argv[1]
        argb = sys.argv[2]
        iterations = sys.argv[3]
    except:
        print("You didn't supply enough arguments\n"+\
              "Usage: python script.py arga argb iterations\n"+\
              "Warning - unsafe.  No input validation and doesn't account for spaces in arguments\n"+\
              "Optionally supply the command to be run as a final argument\n")
        quit()
    try:
        command = sys.argv[4]
        loopy_subprocess(arga, argb, iterations, command)
    except:
        loopy_subprocess(arga, argb, iterations)
Related Question