多处理稍后添加参数

时间:2019-07-05 19:47:05

标签: python python-3.x python-3.7

我想确定我的多进程,稍后再确定该多进程的arg。

因此,我可以运行此过程以说些什么,以及何时必须说其他可以轻易更改的内容。

import multiprocessing

def tts(Say):
    print(Say)

say = ""
if __name__ == '__main__':
    core1 = multiprocessing.Process(target=tts, args=(say,))
    say = "Hello"
    core1.start()
    core1.join()

现在它什么也不会打印,我希望它打印Hello。

3 个答案:

答案 0 :(得分:0)

您正在向tts传递一个尚未定义的对象。解释为python时,在调用Say

时它将检查core1 = multiprocessing.Process(target=tts(Say))的值
Say = "Hello"
core1 = multiprocessing.Process(target=tts(Say))
core1.start()

答案 1 :(得分:0)

我找到了一种更新变量的方法。

import multiprocessing
def tts(Say):
    print(Say)

say = ""
def core1(action):
    exec("multiprocessing.Process(target=tts, args=(say,))"+action)

if __name__ == '__main__':
    say = "Hello"
    core1(".start()")

有没有更好的方法来获得这个?

答案 2 :(得分:0)

扩展流程类:

class Proc(mp.Process):
    def __init__(self, ss, *args, **kwargs):
        super(Proc, self).__init__(*args, **kwargs)
        self.ss = ss

    def run(self):
        print(self.ss)

if __name__ == '__main__':
    pp = Proc('aaa')
    pp.ss = 'bbb'
    pp.start()
    pp.join()

这将打印bbb