在 Python 中執行 Bash 命令
Muhammad Waiz Khan
2023年1月30日
Python
Python Bash
本教程將解釋在 Python 中執行 bash 命令的各種方法。Bash 是 Linux 和 Unix 作業系統中使用的 shell 或命令語言直譯器。而 bash 命令是使用者向作業系統發出的執行特定任務的指令,如 cd 命令改變當前目錄,mkd 命令新建目錄,ls 命令列出目錄中的檔案和子目錄等。
在 Python 中使用 subprocess 模組的 run() 方法執行 Bash 命令
subprocess 模組的 run() 方法接受以字串形式傳來的命令,為了獲得輸出或命令的輸出錯誤,我們應該將 stdout 引數和 stderr 引數設定為 PIPE。run 方法返回一個完成的程序,包含 stdout、stderr 和 returncode 作為屬性。
該程式碼示例程式碼演示瞭如何使用 run() 方法在 Python 中執行 bash 命令。
from subprocess import PIPE
comp_process = subprocess.run("ls", stdout=PIPE, stderr=PIPE)
print(comp_process.stdout)
在 Python 中使用 subprocess 模組的 Popen() 方法執行 Bash 命令
subprocess 模組中的 Popen() 方法與 run() 方法功能類似,但使用起來比較麻煩。Popen() 方法與 run() 方法不同,它不返回一個已完成的程序物件作為輸出,而且 Popen() 方法啟動的程序需要單獨處理,使用起來比較棘手。
Popen() 方法返回的不是已完成的程序,而是一個程序物件作為輸出。返回的程序需要使用 process.kill() 或 process.terminate() 方法來殺死。
和 run() 方法一樣,我們需要設定 Popen() 的 stdout 和 stderr 引數來獲取命令的輸出和錯誤。而輸出和錯誤可以通過返回的程序物件使用 process.communicate 方法進行訪問。
下面的程式碼示例演示瞭如何使用 Popen() 方法執行 bash 命令,以及如何在 Python 中獲取 stdout 和 stderr 值,然後殺死程序。
from subprocess import PIPE
process = subprocess.Popen("ls", stdout=PIPE, stderr=PIPE)
output, error = process.communicate()
print(output)
process.kill
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe