Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用字符串变量指定用于新线程| Python3的函数_Python_Python 3.x_Multithreading_Function - Fatal编程技术网

使用字符串变量指定用于新线程| Python3的函数

使用字符串变量指定用于新线程| Python3的函数,python,python-3.x,multithreading,function,Python,Python 3.x,Multithreading,Function,我有一个程序,它启动一个新线程来运行另一个任意进程。我的问题是用于线程的函数名存储在变量中。我的代码: import _thread def ArbitraryFunction(): #do function userIn = "ArbitraryFunction" try: _thread.start_new_thread( userIn, ("Thread-1") ) except: print("Failed to start thread.") 每次运行此

我有一个程序,它启动一个新线程来运行另一个任意进程。我的问题是用于线程的函数名存储在变量中。我的代码:

import _thread

def ArbitraryFunction():
    #do function

userIn = "ArbitraryFunction"

try:
    _thread.start_new_thread( userIn, ("Thread-1") )
except:
    print("Failed to start thread.")
每次运行此代码时,我都会收到一个错误,表明我没有指定函数。不管函数名是如何指定的,它只是包含在一个变量中


我做错了什么,我需要做什么来修复它?任何帮助都将不胜感激

这是一件非常糟糕的事情,因为执行未经分析的代码是一个巨大的安全缺陷

可以使用eval:

def myFunction():
    return 5

eval('myFunction')()
这允许您从名称空间(函数)获取对象,然后执行它。我再说一遍,这是一个非常糟糕的做法

更好的方法是在字典中映射函数,然后根据名称查找函数。因为函数是Python中的第一类对象,所以可以在大多数数据结构中使用它们

# Create a dict of function names and functions
functions = {'myFunction': myFunction, 'squareroot': sqrt}

# Execute one of the functions
return functions['myFunction']()

这是一件非常糟糕的事情,因为执行未经检查的代码是一个巨大的安全缺陷

可以使用eval:

def myFunction():
    return 5

eval('myFunction')()
这允许您从名称空间(函数)获取对象,然后执行它。我再说一遍,这是一个非常糟糕的做法

更好的方法是在字典中映射函数,然后根据名称查找函数。因为函数是Python中的第一类对象,所以可以在大多数数据结构中使用它们

# Create a dict of function names and functions
functions = {'myFunction': myFunction, 'squareroot': sqrt}

# Execute one of the functions
return functions['myFunction']()
import\u线程
导入系统
def ArbitraryFunction():
#做功能
userIn=“任意函数”
尝试:
_thread.start\u new\u线程(getattr(sys.modules[\uuuuu name\uuuuu],userIn),(“thread-1”,)
例外情况除外,如e:
打印(“由于:\n{}而无法启动线程。格式(e))
注意

\u thread.start\u new\u thread()
的第二个参数必须是元组。要使用单个条目定义元组,请使用尾随逗号
(“Thread-1”)

import\u Thread
导入系统
def ArbitraryFunction():
#做功能
userIn=“任意函数”
尝试:
_thread.start\u new\u线程(getattr(sys.modules[\uuuuu name\uuuuu],userIn),(“thread-1”,)
例外情况除外,如e:
打印(“由于:\n{}而无法启动线程。格式(e))
注意


\u thread.start\u new\u thread()
的第二个参数必须是元组。要使用单个条目定义元组,请使用尾随逗号
(“Thread-1”)

此示例令人困惑——您有一个名为
userIn
的字符串变量,但随后将另一个名为
function
(不存在)的变量传递给线程。抱歉,键入错误。将修复。此示例令人困惑--您在中有一个名为
userIn的字符串变量,但随后您将另一个名为
function
(不存在)的变量传递给线程。抱歉,键入error。会解决的。我理解安全风险。这是一个个人项目,如果我想开源,我会修复它。然而,所选择的功能是作为插件实现的,因此创建字典是不切实际的。我理解安全风险。这是一个个人项目,如果我想开源,我会修复它。但是,所选的功能是作为插件实现的,因此创建字典是不切实际的。是否可以仅保留sys.modules[\uuuuu name\uuuu]
?是的。此外,您还可以在can
sys.modules[\uu\u name\uu]
上了解更多关于它们的信息?是的。此外,您还可以在