Python 多处理是 运行 我所有代码的 5 倍

Python multiprocessing is running all my code 5 times

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

出于某种原因,我的多处理迫使我的代码 运行 5 次,不知何故导致我的 discord 机器人发送的消息比它应该发送的消息多 5 倍。老实说,我不知道这是怎么回事。我 运行 在与我的机器人做任何事情之前的功能,并且它以某种方式使 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__那样设置。