Pickling函数并包含导入

2024-05-19 18:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的想法是这样的,所以我希望允许用户向web端点发送代码。你知道吗

我想从方法中获取模块/导入。 有可能吗?你知道吗

import pickle
import inspect

def add(x,y):
    return x+y

def stringify_method(func):
    """"""
    return pickle.dumps(func)

print(pickle.loads(stringify_method(add))(1,2))
3

所以它返回3,这是预期的。你知道吗

现在假设我有更复杂的事情:

import sys
import pickle
import inspect
import arcpy
import pandas as pd
import numpy as np

def create_array(array):
    return np.array(array)

def unpickle_method(func):
    """"""
    return pickle.dumps(func)

print(pickle.loads(stringify_method(create_array))([1,2,3,4]))

我得到的方法很好,但模块不遵循。我如何得到我的import numpy as np和熊猫等。。?你知道吗


Tags: 模块方法importaddreturndefasnp
1条回答
网友
1楼 · 发布于 2024-05-19 18:18:29

不太清楚你想做什么,但这有帮助吗?你知道吗

>>> import sys
>>> import numpy as np
>>> import inspect
>>> 
>>> [x[0] for x in inspect.getmembers(sys.modules[__name__], inspect.ismodule)]
['__builtins__', 'inspect', 'np', 'sys']

this gets me 1/2 way there, I need to be able to then grab the import statements from the method: import numpy as np

您可能可以从以下内容重建语句:

>>> [(x, y.__name__) for x,y in inspect.getmembers(sys.modules[__name__], inspect.ismodule)]
[('__builtins__', 'builtins'), ('inspect', 'inspect'), ('np', 'numpy'), ('sys', 'sys')]

(注意('np', 'numpy')元素,它告诉您import numpy as np

相关问题 更多 >