몇 가지 관련 답변을 찾았지만 원하는 것은 아닙니다. 여기 문자열의 파이썬 동적 함수
내가 지금 가지고있는 코드입니다 :code_str = """
print "this is my global x = " + x
print "And another line is done"
"""
x = 'mystery'
func_template = lambda p: None
func_template.__code__ = compile(code_str, '<string>', 'exec')
func_template() # this executes fine and also has access to x, which i do need.
# func_template('param') # This raises: TypeError: <module>() takes no arguments (1 given)
일부 배경; code_str는 데이터베이스에서 오는 것, 그리고 내가 이름 중 하나를 호출 할 수 있도록하는 딕셔너리에 많은 기능을 저장 아래와 같이해야합니다
all_funcs = {}
# Assuming db_result returns a list of name, code tuples from the databse
for name, code in db_result:
all_funcs[name] = my_compile(code)
그때 단지에 필요한 함수를 호출 할 내가 이름을 알고있는 경우 인수 내가 원하는 :
result = all_funcs[by_name](arg1, arg2)
편집 : 데이터베이스가 신뢰할 수있는, 그래서 santize 또는 악성 코드에 대해 걱정할 필요가 없습니다.