[英]runtime function target to multiprocessing.Process
Is there a way to decide which function to run by the new process in run-time. 有没有办法确定新进程在运行时要运行哪个功能。 (created by multiprocessing.Process
) (由multiprocessing.Process
创建)
Suppose I have 2 function 假设我有2个功能
def f():
print("In f")
def g():
print("In g")
func_name = str(input("enter function to be run = "))
multiprocessing.Process(target = func_name, args = ()).start()
Now when I run the program 现在,当我运行程序时
enter function to be run = f
This gives me error 这给我错误
TypeError: 'str' object is not callable
This seems obvious because the name of the function should match, but in this case the name is in the variable func_name
as a string. 这似乎很明显,因为函数的名称应该匹配,但是在这种情况下,该名称作为字符串存在于变量func_name
中。
Use a dictionary: 使用字典:
functions = {'f': f, 'g': g}
multiprocess.Process(target=functions.get(func_name), args=()).start()
It would be better to make sure that func_name
is actually in functions
. 最好确保func_name
实际上在functions
。 You could also have a default function that could be given as a second argument to .get()
您还可以拥有一个默认函数,该函数可以作为.get()
的第二个参数提供
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.