溫馨提示×

python并發執行shell怎么實現

小億
186
2023-11-20 16:03:19
欄目: 編程語言

在Python中,可以使用多線程或者多進程來實現并發執行shell命令。

  1. 使用多線程實現并發執行shell命令的方法如下:
import threading
import subprocess

def execute_shell_command(command):
    subprocess.call(command, shell=True)

threads = []

# 創建多個線程,每個線程執行一個shell命令
commands = [
    "echo 'Hello, World!'",
    "ls -l",
    "ping www.google.com"
]

for command in commands:
    thread = threading.Thread(target=execute_shell_command, args=(command,))
    threads.append(thread)
    thread.start()

# 等待所有線程執行完畢
for thread in threads:
    thread.join()
  1. 使用多進程實現并發執行shell命令的方法如下:
import multiprocessing
import subprocess

def execute_shell_command(command):
    subprocess.call(command, shell=True)

processes = []

# 創建多個進程,每個進程執行一個shell命令
commands = [
    "echo 'Hello, World!'",
    "ls -l",
    "ping www.google.com"
]

for command in commands:
    process = multiprocessing.Process(target=execute_shell_command, args=(command,))
    processes.append(process)
    process.start()

# 等待所有進程執行完畢
for process in processes:
    process.join()

以上兩種方法都是通過循環創建多個線程或進程,每個線程或進程執行一個shell命令,并使用join()方法等待所有線程或進程執行完畢。注意,使用多線程或多進程執行shell命令時,需要注意線程或進程間可能存在的競爭條件和資源共享問題。

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