且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:导入模块而不执行脚本

更新时间:2023-12-04 18:20:59

这个答案只是为了证明可以完成,但是显然需要一个更好的解决方案,以确保你包括你想要包括的类。

This answer is just to demonstrate that it can be done, but would obviously need a better solution to ensure you are including the class(es) you want to include.

>>> code = ast.parse(open("someones_class.py").read())
>>> code.body.pop(1)
<_ast.Assign object at 0x108c82450>
>>> code.body.pop(1)
<_ast.Print object at 0x108c82590>
>>> eval(compile(code, '', 'exec'))
>>> test = A(4)
>>> test
<__main__.A instance at 0x108c7df80>

您可以检查代码正文你想要包含的元素,然后移除剩下的元素。

You could inspect the code body for the elements you want to include and remove the rest.

注意:这是一个巨大的黑客。

NOTE: This is a giant hack.