温馨提示×

python并发执行shell怎么实现

小亿
118
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