gpt4 book ai didi

python - 内部编译代码中缺少模块

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:22 24 4
gpt4 key购买 nike

我正在尝试使用compile/exec嵌套python脚本。

#!/usr/bin/env python
#file: a.py
import sys

def in_a():
pass

print '__name__=',__name__
print 'modules[__name__]=', dir(sys.modules[__name__])

直接运行会给我一个包含 in_a 函数的对象列表。

使用编译/代码从另一个脚本运行它不再给我 in_a 。

#!/usr/bin/env python
# file: b.py
import sys

def in_b():
pass

script = open('a.py','r').readlines()
context = dict(
__name__='__main__',
__file__='a.py',
)
code = compile("\n".join(script), 'a.py', 'exec')
exec(code, context)

是否可以获取a.py内部模块的引用?

最佳答案

使用exec时,您不会获得模块。模块通常来自进口机器。您可以通过types模块准备一个模块:

import types
someModule = types.ModuleType("anyModuleNameIsFine")
context = someModule.__dict__
context.update({'ambient': 'globals'})
exec(code, context)

但这似乎有点奇怪。这也不会将它们放入 sys.modules 中,您也可以自己将它们放入其中:

sys.modules['anyOtherName'] = someModule

但是现在我们正危险地接近自定义导入器,在这种情况下,您实际上应该明确地使用自定义导入器:

import imp, sys

class HelloImporter(object):

def get_code(self, fullname):
return "print 'hello world'"

def is_package(self, fullname):
return False

def find_module(self, fn, p):
if fn == 'hello':
return self

# see: http://legacy.python.org/dev/peps/pep-0302/#id27
def load_module(self, fullname):
code = self.get_code(fullname)
ispkg = self.is_package(fullname)
mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
mod.__file__ = "<%s>" % self.__class__.__name__
mod.__loader__ = self
if ispkg:
mod.__path__ = []
mod.__package__ = fullname
else:
mod.__package__ = fullname.rpartition('.')[0]
exec(code, mod.__dict__)
return mod

要使用它,请将其添加到您的sys.meta_path

>>> import sys
>>> sys.meta_path.append(sa_import.HelloImporter())
>>> import hello
hello world

关于python - 内部编译代码中缺少模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23666272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com