在Python中,可以使用subprocess
模块来并行运行shell命令并等待结果。以下是一个代码示例:
import subprocess
def run_command(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
return stdout.decode("utf-8"), stderr.decode("utf-8")
# 并行运行两个命令,并等待结果
command1 = "ls"
command2 = "pwd"
process1 = subprocess.Popen(command1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process2 = subprocess.Popen(command2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout1, stderr1 = process1.communicate()
stdout2, stderr2 = process2.communicate()
print("Command 1 output:", stdout1.decode("utf-8"))
print("Command 1 error:", stderr1.decode("utf-8"))
print("Command 2 output:", stdout2.decode("utf-8"))
print("Command 2 error:", stderr2.decode("utf-8"))
这个示例中,run_command
函数可以用来运行单个命令并返回输出结果和错误信息。使用subprocess.Popen
函数可以启动一个新的进程来运行shell命令。通过communicate
方法可以等待进程结束并获取输出结果和错误信息。
在示例中,并行运行了两个命令ls
和pwd
,并使用多个进程分别处理每个命令的执行。最后打印出两个命令的输出结果和错误信息。
请注意,在使用subprocess.Popen
启动进程时,shell
参数设置为True
,这允许使用shell语法。但请注意谨慎使用shell参数,以避免安全风险。
上一篇:并行运行SAS宏