在Python中,你可以使用concurrent.futures
模塊中的ThreadPoolExecutor
類來創建一個線程池,并使用它來執行外部命令。以下是一個示例:
import subprocess
from concurrent.futures import ThreadPoolExecutor
def run_command(command):
try:
# 使用subprocess.run()執行命令并獲取結果
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
print(f"Command executed successfully: {command}")
print(f"Output: {result.stdout}")
except subprocess.CalledProcessError as e:
print(f"Error executing command: {command}")
print(f"Error message: {e.stderr}")
# 定義要執行的外部命令列表
commands = [
"echo 'Hello, World!'",
"ls /",
"pwd",
]
# 創建一個線程池
with ThreadPoolExecutor(max_workers=3) as executor:
# 使用線程池執行命令
executor.map(run_command, commands)
在這個示例中,我們首先導入subprocess
和concurrent.futures
模塊。然后,我們定義了一個名為run_command
的函數,該函數接受一個命令字符串作為參數,并使用subprocess.run()
執行該命令。我們捕獲了subprocess.CalledProcessError
異常,以便在命令執行失敗時處理錯誤。
接下來,我們定義了一個包含要執行的外部命令的列表。然后,我們創建了一個ThreadPoolExecutor
實例,并使用executor.map()
方法將run_command
函數應用于命令列表。這將在線程池中并行執行命令。