[英]Pickling a Function and Include the Imports
My idea is this, so I want to allow users to send code to a web endpoint. 我的想法是这样,所以我想允许用户将代码发送到Web端点。
I would like to grab the modules/imports from the method. 我想从方法中获取模块/导入。 Is that possible?
那可能吗?
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
So it returns 3, which is expected. 因此它返回3,这是预期的。
Now let's say I have something more complicated: 现在让我们说一些更复杂的事情:
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]))
I get the method just fine, but the modules do not follow. 我得到的方法很好,但是模块不遵循。 How do I get my
import numpy as np
and pandas, etc..? 如何获取
import numpy as np
和pandas等?
Not exactly sure what you are trying to do, but is this helpful? 不确定您要做什么,但这有帮助吗?
>>> 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
这使我到达那里的1/2方式,然后我需要能够从方法中获取导入语句:import numpy as np
You could probably reconstruct the statements from this: 您可能可以从中重构语句:
>>> [(x, y.__name__) for x,y in inspect.getmembers(sys.modules[__name__], inspect.ismodule)]
[('__builtins__', 'builtins'), ('inspect', 'inspect'), ('np', 'numpy'), ('sys', 'sys')]
(note the ('np', 'numpy')
element which tells you import numpy as np
) (注意
('np', 'numpy')
元素告诉您import numpy as np
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.