Linux 拨号vps windows公众号手机端

python并发执行shell怎么实现

lewis 8年前 (2017-10-12) 阅读数 5 #程序编程
文章标签 pythonshell

在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(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(execute_shell_command, args=(command,))
    processes.append(process)
    process.start()

# 等待所有进程执行完毕
for process in processes:
    process.join()

以上两种方法都是通过循环创建多个线程或进程,每个线程或进程执行一个shell命令,并使用join()方法等待所有线程或进程执行完毕。注意,使用多线程或多进程执行shell命令时,需要注意线程或进程间可能存在的竞争条件和资源共享问题。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门