简体   繁体   English

如何运行我的python代码的多个实例?

[英]how to run multiple instances of my python code?

I am trying to run my python-telegram-bot code multiple times with different settings/options.我正在尝试使用不同的设置/选项多次运行我的 python-telegram-bot 代码。 what is the best way to do this?做这个的最好方式是什么?

this code that i am working on is sort of an infusion of django to python-telegram-bot to use it's phenomenal ORM.我正在处理的这段代码是将 django 注入到 python-telegram-bot 以使用它的非凡 ORM。 I am trying to run multiple instances of my bot code with different tokens.我正在尝试使用不同的令牌运行我的机器人代码的多个实例。 I have read about subprocess and threading and still confused about what should I do?我已经阅读了关于subprocessthreading ,但仍然对我应该做什么感到困惑? should I even write a seprate python script and run it with the desired options/settings as arguments(with subprocess.run or os.system )?我甚至写了seprate python脚本,并与所需的选项/设置作为参数(与运行subprocess.runos.system )?

This is going to be used in a webservice and is expected to run telegram bot instances as users need.这将用于网络服务,并有望根据用户需要运行电报机器人实例。 so maybe 100 instances?所以也许有 100 个实例? it is desired to use the least cpu and memory.希望使用最少的 CPU 和内存。

ps: if there is a better title for this question suggest in comments please. ps:如果这个问题有更好的标题,请在评论中提出。

Okay, if you're looking for maximum compute performance, you want to use subprocesses, because the Global Interpreter Lock prevents compute-intensive code from running simultaneously.好的,如果您正在寻找最大的计算性能,您希望使用子进程,因为全局解释器锁可以防止计算密集型代码同时运行。 (Threading and Async are good for IO-intensive scenarios.) (线程和异步适用于 IO 密集型场景。)

I suggest using the multiprocessing module for this-- it allows you to invoke subprocesses using native Python constructs instead of invoking fork / exec or worrying about which binary to execute.我建议为此使用 multiprocessing 模块 - 它允许您使用本机 Python 构造调用子进程,而不是调用 fork / exec 或担心要执行哪个二进制文件。

Cribbing heavily from the Python docs:从 Python 文档中大量抄袭:

from multiprocessing import Process

def bot(token):
    print(token)

if __name__ == '__main__':
    p1 = Process(target=bot, args=('token1',))
    p2 = Process(target=bot, args=('token2',))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

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

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