subprocess 是 Python 3 推薦的子程序管理模組,取代舊有 os.system、os.popen、commands 等,提供豐富的進程控制、管道串聯與即時 I/O 能力。
import subprocess
subprocess.call(["ls", "-l"]) # 返回退出碼
subprocess.call("exit 1", shell=True) # shell 指令,返回 1
# 簡單捕獲標準輸出
output = subprocess.check_output(["echo", "Hello World!"], shell=True)
print(output.decode()) # b'Hello World!\n'
# 讀取檔案內容(Windows type 指令)
content = subprocess.check_output(["type", "app2.cpp"], shell=True)
with open('tmp.log', 'w') as f:
subprocess.Popen(['ipconfig', '/all'], stdout=f)
proc = subprocess.Popen(['ipconfig', '/all'], stdout=subprocess.PIPE, shell=True)
stdout, stderr = proc.communicate()
print(stdout.decode())
child1 = subprocess.Popen(["dir", "/w"], stdout=subprocess.PIPE, shell=True)
child2 = subprocess.Popen(["find", "txt"], stdin=child1.stdout, stdout=subprocess.PIPE, shell=True)
out, _ = child2.communicate()
print(out.decode())
p = subprocess.Popen(["cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True)
p.stdin.write("dir\n")
p.stdin.flush()
print(p.stdout.readline())
p.stdin.write("exit\n")
p.stdin.flush()
subprocess.run()(Python 3.5+)簡化常見情況。shell=True 除非需要 shell 特性(通配符、管道、環境變數展開),防止注入風險。Popen + 執行緒/非阻塞 I/O 避免死鎖。text=True(或 universal_newlines=True)自動處理編碼與換行。