Python/External commands

执行外部命令的传统方式是执行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.

外部链接

编辑