import subprocess
# Simple command
subprocess.call('ls -l', shell=True)
$ python replace_os_system.py
total 16
-rw-r--r-- 1 root8085 root8085 0 Jul 1 13:27 __init__.py
-rw-r--r-- 1 root8085 root8085 1316 Jul 1 13:27 replace_os_system.py
-rw-r--r-- 1 root8085 root8085 1167 Jul 1 13:27 replace_os_system.py~
# run cmd
import subprocess
l = subprocess.call(['cmd'])
额外例如: 进行系统调用三种不同的方法: #! /usr/bin/env python
import subprocess
# Use a sequence of args
return_code = subprocess.call(["echo", "hello sequence"])
# Set shell=true so we can use a simple string for the command
return_code = subprocess.call("echo hello string", shell=True)
# subprocess.call() is equivalent to using subprocess.Popen() and wait()
proc = subprocess.Popen("echo hello popen", shell=True)
return_code = proc.wait() # wait for process to finish so we can get the return code
控制标准错误和ST dout: #! /usr/bin/env python
import subprocess
# Put stderr and stdout into pipes
proc = subprocess.Popen("echo hello stdout; echo hello stderr >&2", \
shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
# Read from pipes
for line in proc.stdout:
print("stdout: " + line.rstrip())
for line in proc.stderr:
print("stderr: " + line.rstrip())