溫馨提示×

python外部命令如何使用線程池執行命令

小樊
111
2024-12-12 01:05:40
欄目: 編程語言

在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)

在這個示例中,我們首先導入subprocessconcurrent.futures模塊。然后,我們定義了一個名為run_command的函數,該函數接受一個命令字符串作為參數,并使用subprocess.run()執行該命令。我們捕獲了subprocess.CalledProcessError異常,以便在命令執行失敗時處理錯誤。

接下來,我們定義了一個包含要執行的外部命令的列表。然后,我們創建了一個ThreadPoolExecutor實例,并使用executor.map()方法將run_command函數應用于命令列表。這將在線程池中并行執行命令。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女