Python:如何同时运行多个文件? [英] Python: How to run multiple files at the same time?

查看:80
本文介绍了Python:如何同时运行多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 For 循环,它会在完全相同的时间自动启动不同的 python 文件,但它们似乎总是一个接一个地运行.

I'm trying to create a For-loop which automatically starts different python files at the exact same time, but they always seem to run one after one.

import os
import multiprocessing
import p1, p2, p3

#first idea

path = "C:" + "\\Users\\Max\\\\Desktop\\\python\\tasks\\"
tasks = ['p1.py', 'p2.py', 'p3.py']
len = tasks.__len__()
ind = 0
for i in range(len):
    os.system('python' + ' ' + tasks[ind])
    ind += 1

#second idea

for x in ('p1', 'p2', 'p3'):
    p = multiprocessing.Process(target=lambda: __import__(x))
    p.start()

p1、p2、p3 是我试图同时运行的文件,但它们一个接一个地执行,所以如果代码是:

p1, p2, p3 are the files I'm trying to run at the same time, but they get executed one after one, so if the code is:

time.sleep(10)
print("hello)

我必须等待 30 秒才能完成程序,而不是我想要的 10 秒.

I will have to wait 30 seconds for the program to be done, instead of the 10 seconds I want.

推荐答案

如果要在三个独立的解释器中启动文件,请将它们作为子进程启动:

If you want to start the files in three separate interpreters, start them as subprocesses:

import subprocess
path = r"C:\Users\Max\Desktop\python\tasks"
tasks = ['1.py', '2.py', '3.py']
task_processes = [
    subprocess.Popen(r'python %s\%s' % (path, task), shell=True)
    for task
    in tasks
]
for task in task_processes:
    task.wait()

这篇关于Python:如何同时运行多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆