繁体   English   中英

Python 多处理正在运行我的所有代码 5 次

[英]Python multiprocessing is running all my code 5 times

我制作了一个 discord 机器人,它使用多处理(这是我第一次使用多处理)以提高效率。 没有它,机器人已经可以正常工作了,我只是很无聊,想改进它。 该机器人适用于学校的 discord 服务器,该服务器使用他们的 api 获得当天的午餐(想知道他们为什么有一个)。

出于某种原因,我的多处理迫使我的代码运行 5 次,并且不知何故导致我的 discord 机器人发送的消息比它应该发送的消息多 5 倍。 老实说,我不知道这是怎么回事。 我在与我的机器人有关的任何事情之前运行 function,不知何故,它使 5 个机器人以相同的令牌同时运行。 5个机器人全部上线大约需要30秒,他们一个一个做。 另一件小事是,每次调用 func 时,多处理都会无缘无故地打印 5 次“none”。

感谢您花时间准备我的主题!

from asyncio.tasks import create_task
import discord
from discord.ext.commands import Bot
import datetime, asyncio
from discord.message import Message
import schedule
import random
import requests
import json
import datetime
import multiprocessing
from multiprocessing import Pool



def get_lunch(day):  # Sorting thru a json that is scraped, not gonna put it here b/c i don't want to dox myself, and it works perfectly
    all_todos = load_pre_reqs()
    gotten_lunch = (str(all_todos.split("menu_items")[2 + day].split(r'"name"')[1].split(",")[0]))
    formated_lunch = (gotten_lunch[3:int(len(gotten_lunch)) -1 ])
    return(formated_lunch)

# if anyone is trying to run this code u can use something like instead of above
# def get_lunch(day):
#     lunches = ["a", "b", "c", "d", "e"]
#     return lunches[day]
def lunch():
    if __name__ == '__main__':
        p = Pool(5)
        week = p.map(get_lunch, range(5))
        return week

# I run this^ on it's own and works well, but causes the rest of the code to repeat 5x

print(lunch())

bot = Bot(command_prefix='!')
client = discord.Client()
loop = asyncio.get_event_loop() # here for future
TOKEN = 'insert token here'

@client.event
async def on_ready():
    print(f"connected as {client.user}")


@client.event
async def on_message(message):
    if message.author == client.user:
        return
    else:
        await message.channel.send("hi") #just here to make sure bot is running


client.run(TOKEN)

multiprocessing模块中的文档对此非常清楚。 当您使用多处理运行一个模块时,它会启动一个全新的进程,一个全新的解释器,它必须导入您的主模块和它需要的所有模块。 如果您没有一次性代码在if __name__=='__main__':块中,就像文档建议的那样,那么它将在每个启动的进程中重新运行。

这就是为什么你应该养成将应用程序的主要代码放在def main():中的习惯:

if __name__ == '__main__':
    main()

多处理启动的导入不会以这种方式设置__name__

暂无
暂无

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

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