简体   繁体   English

如何同时运行多个python文件?

[英]How to run multiple python files at the same time?

How can I run multiple python files at the same time? 如何同时运行多个python文件? There are 3 files: bot_1.py, bot_2.py, bot_3.py. 一共有3个文件:bot_1.py,bot_2.py,bot_3.py。 I would like to run them at the same time. 我想同时运行它们。 I attached the code. 我附上了代码。 What should I write in the worker function to make this script work? 为了使此脚本正常工作,我应该在worker函数中写些什么? I will appreciate any help. 我将不胜感激。

 import multiprocessing import subprocess def worker(file): #your subprocess code subprocess.Popen(['screen', './bot_1.py']) subprocess.Popen(['screen', './bot_2.py']) subprocess.Popen(['screen', './bot_3.py']) if __name__ == '__main__': files = ["bot_1.py","bot_2.py","bot_3.py"] for i in files: p = multiprocessing.Process(target=worker(i)) p.start() 

Assuming that your bot files execute something when you run them at the command line, we can load them and execute them by importing them into our python process (instead of the shell). 假设您的bot文件在命令行运行时执行了某些操作,我们可以通过将其导入到python进程(而不是shell)中来加载并执行它们。 As each python file defines a package we can do this as follows: 当每个python文件定义一个包时,我们可以按照以下步骤进行操作:

import bot_1, bot_2, bot_3

This however will run them one after another, and also prevent you from running the same one twice. 但是,这将使它们一个接一个地运行,并且还会阻止您一次运行两次。 To get them to run at once, we can use multiprocessing as you suggest: 为了使它们立即运行,我们可以按照您的建议使用多重处理:

import multiprocessing

for bot in ('bot_1', 'bot_2', 'bot_3'):
    p = multiprocessing.Process(target=lambda: __import__(bot))
    p.start()

Processes need a function to run, so we use an anonymous lambda to give it one, and then dynamically import the name. 进程需要一个函数来运行,因此我们使用匿名lambda为其赋予一个名字,然后动态导入该名称。

It's not shown here, but as long as you don't import a module into the parent process, the children will be forced to load it, meaning you can run the same one over and over in the separate process if you need to. 它未在此处显示,但是只要您不将模块导入父进程中,子进程就会被迫加载它,这意味着您可以在单独的进程中反复运行同一模块。

From the docs, In multiprocessing, processes are spawned by creating a Process object and then calling its start() method. 从文档开始,在多处理中,通过创建Process对象然后调用其start()方法来生成进程。

So i guess the good way to do it is with the following: 所以我想做到这一点的好方法是:

bots = ['bot1','bot2','bot3']
modules = map(__import__,bots)

import multiprocessing,subprocess

multiprocessing.Process(target=modules)

In bot1,2,3 i used a simple print("bot1"), bot2 and bot3 and the output is as expected: 在bot1,2,3中,我使用了一个简单的print(“ bot1”),bot2和bot3,其输出是预期的:

user@machine:~$ python mainscript.py 
bot1
bot2
bot3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM