[英]In python, what code should I generate to do "from FILE import *"?
I'm working on the pythonizer , a program to translate perl to python, and I'm looking to translate the statement "require FILENAME;"我正在开发pythonizer ,这是一个将 perl 转换为 python 的程序,我正在寻找翻译语句“需要 FILENAME;” to python.至 python。 In this case I need to generate "from FILENAME import *".在这种情况下,我需要生成“from FILENAME import *”。 I figured out the "from FILENAME" part (here BASENAME
is the FILENAME
without the path or extension):我想出了“来自文件名”部分(这里的BASENAME
是没有路径或扩展名的FILENAME
名):
from importlib.machinery import SourceFileLoader
module = SourceFileLoader(BASENAME, FILENAME).load_module()
and the import *
part is coded as:并且import *
部分编码为:
__import__(name, fromlist=['*'])
but how do I combine them?但是我该如何组合它们呢?
I see _handle_fromlist in importlib._bootstrap
, but calling an internal routine is most likely not the right answer here.我在importlib._bootstrap
中看到_handle_fromlist ,但在这里调用内部例程很可能不是正确的答案。
Here is my second thought about implementing this:这是我关于实现这一点的第二个想法:
[_p, _m] = _prep_import(FILENAME)
sys.path[0:0] = _p
__import__(_m, fromlist=['*'])
sys.path.pop(0)
Where _prep_import()
looks at the FILENAME (which may be an expression), removes any extension, grabs any path info from it into the first result, and leaves the basename as the second result.其中_prep_import()
查看 FILENAME(可能是一个表达式),删除任何扩展名,从中获取任何路径信息到第一个结果中,并将基本名称作为第二个结果。 Note that the FILENAME may contain dashes ( -
), and I believe __import__
is OK with that.请注意, FILENAME 可能包含破折号( -
),我相信__import__
可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.