Python/External commands
< Python
执行外部命令的传统方式是执行os.system():
import os
os.system("dir")
os.system("echo Hello")
exitCode = os.system("echotypo")
从Python 2.4开始可以使用subprocess模块:
subprocess.call(["echo", "Hello"])
exitCode = subprocess.call(["dir", "nonexistent"])
执行外部命令并读取其输出的传统方式是通过 popen2 模块:
import popen2
readStream, writeStream, errorStream = popen2.popen3("dir")
# allLines = readStream.readlines()
for line in readStream:
print(line.rstrip())
readStream.close()
writeStream.close()
errorStream.close()
从Python 2.4开始可以使用subprocess模块:
import subprocess
process = subprocess.Popen(["echo","Hello"], stdout=subprocess.PIPE)
for line in process.stdout:
print(line.rstrip())
Keywords: system commands, shell commands, processes, backtick, pipe.
外部链接
编辑- 17.1. subprocess — Subprocess management, python.org, since Python 2.4
- 15.1. os — Miscellaneous operating system interfaces, python.org
- 17.5. popen2 — Subprocesses with accessible I/O streams, python.org, deprecated since Python 2.6