Ultima attività 10 months ago

這段 Python 程式碼使用 asyncio 來 非同步執行系統指令,透過 asyncio.create_subprocess_exec() 建立子行程,並並行執行多個指令(如 ping 和 ls)。它適用於 非同步處理系統指令、提升效能、避免阻塞主執行緒,適合用於 自動化腳本、伺服器管理或批次處理 任務。

Revisione b4052bfaaa22c77230f0ffc4e4f8585640debb6c

asyncio_run_command.py Raw
1import asyncio
2
3async def run_command(*args):
4 # 建立子行程
5 process = await asyncio.create_subprocess_exec(
6 *args,
7 stdout=asyncio.subprocess.PIPE,
8 stderr=asyncio.subprocess.PIPE)
9
10 # 等待子行程完成
11 stdout, stderr = await process.communicate()
12
13 # 輸出結果
14 if stdout:
15 print(f'[stdout]\n{stdout.decode()}')
16 if stderr:
17 print(f'[stderr]\n{stderr.decode()}')
18
19# 執行指令
20# asyncio.run(run_command('ls', '-l'))
21# asyncio.run(run_command('ping', 'www.google.com'))
22
23# 執行指令
24async def main():
25 await asyncio.gather(
26 run_command('ping', '-c', '4', 'www.google.com'),
27 run_command('ls', '-l')
28 )
29
30asyncio.run(main())
31