Python : 在不同进程之间传递值

Python : passing values between different processes

我调试了一段时间的代码,发现 bash_shell(message,shell) 无法将 shell 字典传回主进程。字典仍然是空白的,但当我阅读(实际上是打印)bash_shell() 中的 shell 时,它确实具有价值。这意味着可能是因为我传递了变量的值而不是别名?但是我在其他网站上看到其他帖子,人们就是这样做的,而且效果很好。

我尝试 threading.Thread() 而不是 multiprocessing.Process()。线程可以用全局变量传回值(没试过传参方式)

import multiprocessing,subprocess
# doing import stuff and blah blah blah
shell = dict()
shell['sh_out'] = ''
shell['py_out'] = ''
# code.... (in this part I also defined channel, guild, _globals, _locals,bot, etc...)
def bash_shell(msg,shell):
    global channel,guild,_globals,_locals
    try:
        proc = subprocess.Popen(msg.split(" "), stdout=subprocess.PIPE,text=True)
    except Exception as e:
        shell['sh_out'] = str(e) + '\n$'
        return
    (out, err) = proc.communicate()
    if err:
        shell['sh_out'] = '```\n' + str(out) + "\n```\nError: `" + str(err) + "`\n```\n$```"
    else:
        shell['sh_out'] = '```\n'+ str(out) + "\n$```"
    if len(rt) > 1988:
        f = open("samples/shoutput.txt","w")
        f.write(rt)
        f.close()
    return
#code.......
# @bot.event
def on_message(message):
    #again code......
    # if message.channel.name == 'bash':
        # p = multiprocessing.Process(target=bash_shell,args=[message,shell])
        p = multiprocessing.Process(target=bash_shell,args=['ls -al',shell])
        p.start()
        p.join(5)
        if p.is_alive():
            p.kill()
            shell['sh_out'] = "Enough fork bomb. Please don't try to hang the bot."
            p.join()
        if len(shell['sh_out']) > 1998:
            # await message.channel.send(file=discord.File(open("samples/shoutput.txt","r"),"output.txt"))
            shell['sh_out'] = ''
            return
        print(shell)
        # await message.channel.send(shell['sh_out'])
        shell['sh_out'] = ""
        return

on_message('a')

(注意:如果你想知道我在做什么,它只是一个在 discord.py 中编码的机器人。代码已被修改,以便更容易理解并更容易触发异常。)

那我做错了什么?还是有更好的方法来解决这个问题?为什么它不能更改字典 shell 但其他人可以这样做?

你有两种可能:

1 ) 在进程之间共享内存 space

2 ) 使用多处理库提供的管理器对象

但是对于进程之间的通信,您可以使用这篇优秀文章中提到的队列:

https://www.geeksforgeeks.org/multiprocessing-python-set-2/amp/