跳轉到內容

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())

關鍵詞:系統命令、shell 命令、程序、反引號、管道。

[編輯 | 編輯原始碼]
華夏公益教科書