在Python中,可以使用多線程或者多進程來實現并發執行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()
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命令時,需要注意線程或進程間可能存在的競爭條件和資源共享問題。