概覽:四大 API 定位對比
| 方法 | 模塊 | 返回值 | 阻塞性 | 適用場景 |
| os.execl* | os | 不返回(替換進程) | 阻塞 | 進程替換、守護進程啟動 |
| os.system | os | 退出碼 | 阻塞 | 無輸出需捕獲的簡單命令 |
| os.popen | os | 文件對象 | 阻塞 | 需讀取命令輸出 |
| subprocess.run | subprocess | CompletedProcess | 阻塞/非阻塞 | 現代標準,全功能替代以上所有 |
| commands.getoutput | commands (Py2) | 字符串 | 阻塞 | Python 2 遺留,Py3 已移除 |
1. os.execl 系列:進程替換
import os
os.execl('/bin/ls', 'ls', '-l') # 當前進程變為 ls,代碼不再返回
- 類 Unix
exec 系統調用,不創建子進程,直接替換當前進程映像
- 適用於「啟動新程序且不再返回」的場景(如容器入口腳本)
- 變體:
execl, execle, execlp, execlpe, execv, execve, execvp, execvpe
2. os.system:簡單執行,只關心退出碼
import os
exit_code = os.system('notify-send "Hello"') # 0 成功,非 0 失敗
- 創建子進程執行命令,不捕獲輸出(直接繼承 stdout/stderr)
- 返回值為進程退出狀態碼(
exit_code >> 8 為真實退出碼)
- 適合:無輸出需處理的簡單調用(發送通知、觸發腳本)
3. os.popen:捕獲輸出的舊式管道
import os
cmd = "ssh server 'df -h'"
with os.popen(cmd) as f:
output = f.read() # 讀取標準輸出
print(output)
- 返回類文件對象,支持
read(), readlines(), close()
- 單向管道(默認只讀 stdout),雙向需
popen2(已棄用)
- Python 3 推薦用 subprocess 替代
4. subprocess:現代標準庫(強烈推薦)
import subprocess
# 簡單調用
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
print(result.returncode)
# 管道鏈
p1 = subprocess.Popen(['cat', 'big.log'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'error'], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
out, _ = p2.communicate()
subprocess.run()(Py3.5+)覆蓋 90%+ 場景
- 支持:超時、輸入輸出重定向、管道、環境變量、工作目錄、編碼、Shell/非 Shell 模式
- 安全:避免 shell=True,傳列表參數防注入
遷移建議
- 新代碼統一使用 subprocess
- 舊代碼
os.popen → subprocess.run(..., capture_output=True, text=True)
commands 模塊 Py3 已刪除,必須遷移