Python:导入模块而不执行脚本 [英] Python: import module without executing script
问题描述
我查看了类似的问题,但确实如此没有真正回答我的问题。假设我有以下代码(过于简化以仅突出显示我的问题)。
I looked at a similar question but it does not really answer the question that I have. Say I have the following code (overly simplified to highlight only my question).
class A:
def __init__(self,x):
self.val = x
a = A(4)
print a.val
此代码位于文件 someones_class.py
中。我现在想在我的程序中导入并使用类 A
,而无需修改 someones_class.py
。如果我从someones_class导入A ,python仍会执行文件中的脚本行。
This code resides in a file someones_class.py
. I now want to import and use class A
in my program without modifying someones_class.py
. If I do from someones_class import A
, python would still execute the script lines in the file.
问题:是有没有办法只导入类 A
而不执行最后两行?
Question: Is there a way to just import class A
without the last two lines getting executed?
我知道 if __name__ =='__ main __'
但是我没有选择修改 someones_class.py
文件,因为只有在获得我的程序开始执行。
I know about if __name__ == '__main__'
thing but I do not have the option of modifying someones_class.py
file as it is obtained only after my program starts executing.
推荐答案
这个答案只是为了证明可以完成,但是显然需要一个更好的解决方案,以确保你包括你想要包括的类。
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.
这篇关于Python:导入模块而不执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!