」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在Python中實作非同步Shell指令執行?

如何在Python中實作非同步Shell指令執行?

發佈於2024-11-23
瀏覽:258

How to Implement Asynchronous Shell Command Execution in Python?

Python 中的非同步Shell 指令執行

Python 中的非同步Shell 指令執行

為了促進Python 腳本中外部shell 指令的非同步執行,人們可能會考慮使用os . system() 函數。然而,這種方法在命令結束時引入了 & 符號的使用,以避免同步行為。因此,它引起了人們對其作為實現非同步執行的合適方法的適當性的擔憂。

子程序:高級解決方案

取代 os.system(), subprocess 模組以 Popen 類別的形式提供了更合適的解決方案。此類可以非同步無縫執行長時間運行的命令,從而允許 Python 腳本在外部命令執行其任務時繼續其操作。

實作
from subprocess import Popen

# Initiate the long-running 'watch ls' command
p = Popen(['watch', 'ls'])

# Continue executing the Python script while the command runs
# ...

# Terminate the subprocess when necessary
p.terminate()
來說明Popen 的用法,請考慮以下範例:

from subprocess import Popen # 啟動長時間運行的「watch ls」指令 p = Popen(['手錶', 'ls']) # 命令運行時繼續執行Python腳本 # ... # 必要時終止子程序 p.terminate()

其他功能

How to Implement Asynchronous Shell Command Execution in Python?

除了非同步執行之外,Popen 實例還提供其他一些功能。值得注意的是,它允許透過 poll() 方法監視其執行狀態。此外,還可以利用 communications() 方法透過 stdin 交換資料並等待進程終止。

版本聲明 本文轉載於:1729581855如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3