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