User Tools

Site Tools


doc:appunti:prog:python_program_execution

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
doc:appunti:prog:python_program_execution [2009/10/01 15:35] niccolodoc:appunti:prog:python_program_execution [2022/07/01 10:56] (current) – [Get the output of a program] niccolo
Line 14: Line 14:
  
 <code python> <code python>
-retcode = subprocess.call(["ls", "-l"])+retcode = subprocess.call(["mycmd", "myarg"]
 +</code> 
 + 
 +Same as above, but run in a subshell (in this case the command may contain shell redirections): 
 + 
 +<code python> 
 +retcode = subprocess.call("mycmd myarg", shell=True)
 </code> </code>
  
 ===== Get the output of a program ===== ===== Get the output of a program =====
 +
 +Assign the output to a variable:
  
 <code python> <code python>
-subproc = subprocess.Popen(cmd, stdin=None, stdout=subprocess.PIPE) +output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0].decode('utf-8'
-output  = subproc.communicate()[0]+</code> 
 + 
 +Get also the return code, stderr and iterate on the output: 
 + 
 +<code python> 
 +subproc = subprocess.Popen(["mycmd", "myarg"], stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
 +output, stderr = subproc.communicate()
 retcode = subproc.returncode retcode = subproc.returncode
-for line in output.splitlines(): +for line in output.decode('utf-8').splitlines(): 
-    print line+    print(line
 +</code> 
 + 
 +===== Redirect output to a file ===== 
 + 
 +<code python> 
 +file = open("/tmp/cmd_output", "w"
 +subprocess.call(["mycmd", "myarg"], stdout=file) 
 +file.close() 
 +</code> 
 + 
 +===== Run two commands in a pipe ===== 
 + 
 +<code python> 
 +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] 
 +</code> 
 + 
 +===== Write to command standard input ===== 
 + 
 +<code python> 
 +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))
 </code> </code>
  
doc/appunti/prog/python_program_execution.1254404125.txt.gz · Last modified: 2009/10/01 15:35 by niccolo