Python:subprocess
lastmod 2022-10-11created 2015-04-1711 edits
Use the os.system
With this method, the program's exit code1 is returned as the return value.
Use the os.popen
The os.popen series appeared in python 2.0, and as of 2.6 it is recommended to replace it with subprocess's popen. subprocess appeared in version 2.4.
import os
def execute(cmd):
std_in, std_out, std_err = os.popen3(cmd)
return std_out, std_err
cmd = "ls -l"
std_out, std_err = execute(cmd)
for line in std_out.readlines():
print line
Use the subprocess
import subprocess
def execute(cmd) :
fd = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return fd.stdout, fd.stderr
cmd = "ls -l"
std_out, std_err = execute(cmd)
for line in std_out.readlines():
print line
See also
- Python
- Python:asyncio
- Asyncio:AsyncPythonSubprocess - Implementation of a class that launches a Subprocess using Python's asyncio package.
Favorite site
- 17. Interprocess Communication and Networking » 17.1. subprocess — Subprocess management
- Python - Running external programs
- How to use Python command and os commands
- [Recommended] Using os.popen3 and subprocess.Popen
- Running bash commands in Python: subprocess, pexpect
- subprocess (Python) Running applications from Python
- Saving the output of external programs in Python