簡體   English   中英

使用字符串變量指定用於新線程的函數 | 蟒蛇3

[英]Using a String Variable to Specify Function Used for a New Thread | Python3

我有一個程序可以啟動一個新線程來運行另一個任意進程。 我的問題是用於線程的函數的名稱存儲在一個變量中。 我的代碼:

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']()
import _thread
import sys


def ArbitraryFunction():
    # do function

userIn = "ArbitraryFunction"

try:
    _thread.start_new_thread(getattr(sys.modules[__name__], userIn), ("Thread-1",))
except Exception as e:
    print("Failed to start thread due to:\n{}".format(e))

筆記

_thread.start_new_thread()第二個參數需要是一個元組。 要定義具有單個條目的元組,請使用尾部逗號("Thread-1",)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM