在Python中,可以使用subprocess
模塊來(lái)創(chuàng)建和管理子進(jìn)程,以及執(zhí)行外部命令。subprocess
模塊提供了多種方法來(lái)調(diào)用shell命令,包括同步調(diào)用和異步調(diào)用。
異步調(diào)用shell命令的方法有兩種:
subprocess.Popen
函數(shù)創(chuàng)建子進(jìn)程,并通過(guò)communicate
方法來(lái)獲取命令的輸出。這種方法允許程序在命令執(zhí)行期間繼續(xù)執(zhí)行其他操作。import subprocess
def run_command_async(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return process
command = "ls -l"
process = run_command_async(command)
output, error = process.communicate()
print(output.decode())
asyncio
庫(kù)來(lái)實(shí)現(xiàn)異步調(diào)用。asyncio
提供了高級(jí)的異步編程支持,可以在調(diào)用shell命令時(shí)使用create_subprocess_shell
函數(shù)來(lái)創(chuàng)建子進(jìn)程。import asyncio
async def run_command_async(command):
process = await asyncio.create_subprocess_shell(command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
output, error = await process.communicate()
return output
async def main():
command = "ls -l"
output = await run_command_async(command)
print(output.decode())
asyncio.run(main())
請(qǐng)注意,異步調(diào)用shell命令需要使用asyncio
庫(kù)來(lái)管理異步任務(wù)和事件循環(huán)。