[英]How to asynchronously call a shell script from Python?
我有一個 shell 腳本,它對傳遞的字符串進行一些處理,然后將其寫入文件。 但是我不希望我的函數 foo() 等待它完成操作。 如何調用process(msg)
然后繼續執行{code block 2}
而無需等待process(msg)
完成執行?
def process(msg):
subprocess.call(['sh', './process.sh', msg])
def foo():
# {code block 1}
process(msg)
# {code block 2}
foo()
將被另一個函數調用,幾乎每秒一次或兩次。
你需要的是https://docs.python.org/3/library/os.html#os.fork ie os.fork()
這樣你就可以產生一個子進程,它可以比父進程os.fork()
更長,以后可以通過Linux 上的systemd
。 我對 Windows 一無所知。
只是為了完整性:Python 的 asyncio 提供了一個高級接口來做到這一點: https ://docs.python.org/3.9/library/asyncio-subprocess.html#subprocesses
文檔中的示例:
import asyncio
async def run(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
asyncio.run(run('ls /zzz'))
subprocess.call() 和 subprocess.run() 創建一個進程,等待它完成,並返回一個 CompletedProcess 對象。
subprocess.Popen() 創建一個進程並返回它。 它是在前面的函數的引擎蓋下使用的。 然后,您可以等待該過程完成,向其發送消息,或者您想做的任何其他事情。 參數大部分與call
或run
相同。
https://docs.python.org/3/library/subprocess.html
稍微細化一下,Popen 是使用 os 啟動新進程的 python 實現。 os.fork() 是一個較低的級別,它實際上並沒有做我們在這里想要的,它會產生另一個 python 解釋器的實例,它的內存狀態與當前的相同。 如果你想使用較低級別的系統調用, os.spawn
接近subprocess.run
比os.fork
。
為了驗證 Popen 正在做你想要的,這個測試程序會打印“returncode = None”,然后等待 5 秒,並打印“returncode = 0”
from subprocess import Popen
p = Popen(["sleep", "5"])
print("started the proc") # this will print immediately
p.poll() # this checks if the process is done but does not block
print(f"p returncode = {p.returncode}")
p.wait() # this blocks until the process exits
print(f"p returncode = {p.returncode}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.