asyncio_run_command.py
· 721 B · Python
Raw
import asyncio
async def run_command(*args):
# 建立子行程
process = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
# 等待子行程完成
stdout, stderr = await process.communicate()
# 輸出結果
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
# 執行指令
# asyncio.run(run_command('ls', '-l'))
# asyncio.run(run_command('ping', 'www.google.com'))
# 執行指令
async def main():
await asyncio.gather(
run_command('ping', '-c', '4', 'www.google.com'),
run_command('ls', '-l')
)
asyncio.run(main())
| 1 | import asyncio |
| 2 | |
| 3 | async 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 | # 執行指令 |
| 24 | async def main(): |
| 25 | await asyncio.gather( |
| 26 | run_command('ping', '-c', '4', 'www.google.com'), |
| 27 | run_command('ls', '-l') |
| 28 | ) |
| 29 | |
| 30 | asyncio.run(main()) |
| 31 |