User Tools

Site Tools


Sidebar

No ai soldati italiani all'estero

Indice

Eventi

Energia

Rigacci.Org usa energia elettrica da fonti rinnovabili, grazie al gruppo di acquisto Merci Dolci.

Merci Dolci - Energia Rinnovabile

Software libero!

Petizione contro i brevetti software

Faunalia: Soluzioni GIS professionali

Debian

www.gnu.org www.kernel.org

doc:appunti:prog:python_program_execution

Program execution from Python

The right module to use is subprocess. Older modules and functions that should be avoided are:

  • os.system
  • os.spawn*
  • os.popen*
  • popen2.*
  • commands.*

Run a command

Run command with arguments. Wait for command to complete, then return the returncode attribute.

retcode = subprocess.call(["mycmd", "myarg"])

Same as above, but run in a subshell (in this case the command may contain shell redirections):

retcode = subprocess.call("mycmd myarg", shell=True)

Get the output of a program

Assign the output to a variable:

output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0]

Get also the return code, stderr and iterate on the output:

subproc = subprocess.Popen(["mycmd", "myarg"], stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, stderr = subproc.communicate()
retcode = subproc.returncode
for line in output.splitlines():
    print line

Redirect output to a file

file = open("/tmp/cmd_output", "w")
subprocess.call(["mycmd", "myarg"], stdout=file)
file.close()

Run two commands in a pipe

cmd1 = ["oggdec", "-Q", "-o", "-", src]
cmd2 = ["lame", "--preset", "cd", "-", dst]
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
output = p2.communicate()[0]

Write to command standard input

cmd_input = []
cmd_input.append('line input one')
cmd_input.append('line input two')
 
p = subprocess.Popen('command', stdin=subprocess.PIPE)
p.communicate(os.linesep.join(cmd_input))
doc/appunti/prog/python_program_execution.txt · Last modified: 2017/07/16 06:44 by niccolo