Does Python have a module for scripting command line tasks?

Question:

Does Python of a module adapted for scripting command line tasks?

I am interested in something that can issues commands, parse the output, especially as relates to success, failure or progress and send an email depending on the outcome.

Is there some module especially adapted for this?

Asked By: vfclists

||

Answers:

Try the subprocess module and check some usage examples.

Answered By: dkamins

Snippet using suprocess and shlex modules:

def runcommand(command):
    args = shlex.split(command)
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdoutdata, stderrdata) = p.communicate()
    return (stdoutdata, stderrdata, p.returncode)

(outdata, errdata, returncode) = runcommand('/bin/ls -hl /tmp')

outlines = outdata.splitlines()
errlines = errdata.splitlines()

For sending mail there are good examples in the library documentation.

Note that communicate() will wait until process terminates. For progress just access Popen pid and streams directly combined with poll() or wait().

Answered By: mmoya

subprocess is good and is in the standard library. There are other external modules that can make interfacing with command line tasks a joy.

  • pbs comes in first for most innovative API.
  • shellout comes in a close second.
Answered By: threebean

This looks like it might do what you want: https://github.com/amoffat/pbs

The documentation on the GitHub page has some good examples. Also, I haven’t used this yet but have read from other people online that they really like this and consider this superior to subprocess (for whatever reason)

Cheers.

Answered By: Josh R