doc:appunti:prog:python_program_execution
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| doc:appunti:prog:python_program_execution [2009/10/01 15:35] – niccolo | doc: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([" | + | retcode = subprocess.call([" |
| + | </ | ||
| + | |||
| + | Same as above, but run in a subshell (in this case the command may contain shell redirections): | ||
| + | |||
| + | <code python> | ||
| + | retcode = subprocess.call(" | ||
| </ | </ | ||
| ===== 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([" |
| - | output | + | </ |
| + | |||
| + | Get also the return code, stderr and iterate on the output: | ||
| + | |||
| + | <code python> | ||
| + | subproc = subprocess.Popen([" | ||
| + | output, stderr | ||
| retcode = subproc.returncode | retcode = subproc.returncode | ||
| - | for line in output.splitlines(): | + | for line in output.decode(' |
| - | print line | + | print(line) |
| + | </ | ||
| + | |||
| + | ===== Redirect output to a file ===== | ||
| + | |||
| + | <code python> | ||
| + | file = open("/ | ||
| + | subprocess.call([" | ||
| + | file.close() | ||
| + | </ | ||
| + | |||
| + | ===== Run two commands in a pipe ===== | ||
| + | |||
| + | <code python> | ||
| + | cmd1 = [" | ||
| + | cmd2 = [" | ||
| + | p1 = subprocess.Popen(cmd1, | ||
| + | p2 = subprocess.Popen(cmd2, | ||
| + | p1.stdout.close() | ||
| + | output = p2.communicate()[0] | ||
| + | </ | ||
| + | |||
| + | ===== Write to command standard input ===== | ||
| + | |||
| + | <code python> | ||
| + | cmd_input = [] | ||
| + | cmd_input.append(' | ||
| + | cmd_input.append(' | ||
| + | |||
| + | p = subprocess.Popen(' | ||
| + | p.communicate(os.linesep.join(cmd_input)) | ||
| </ | </ | ||
doc/appunti/prog/python_program_execution.1254404125.txt.gz · Last modified: by niccolo
