简体   繁体   English

运行时函数目标为multiprocessing.Process

[英]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.

相关问题 multiprocessing.Process-变量作为函数 - multiprocessing.Process - Variable as function 对象方法作为多处理过程目标 - Object method as multiprocessing.Process target 将函数或类实例传递给multiprocessing.Process的“ target”参数是否安全,而没有密集复制的风险? - Is it safe to pass a function or a class instance to the “target” argument of multiprocessing.Process without the risk of dense copying? 从Jupyter Notebook中的multiprocessing.Process调用时,目标函数未分配给类属性 - Target function does not assign to class attribute when called by multiprocessing.Process from within Jupyter notebook 哪里是multiprocessing.Process - Where is multiprocessing.Process 配置多重处理 - Configuring a multiprocessing.Process multiprocessing.Process 目标仅执行 3 次中的 2 次 - multiprocessing.Process target executing only 2 out of 3 times 恢复传递给multiprocessing.Process的函数的返回值的最快方法 - Fastest way to recover the return value of a function passed to multiprocessing.Process 如何从 multiprocessing.Process 获取函数返回值? - How to get function return value from a multiprocessing.Process? 使用 multiprocessing.Process 在 Python 中并行运行 function - Running a function in Python in Parallel using multiprocessing.Process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM