问题描述
我想导入 foo-bar.py.这有效:
foobar = __import__("foo-bar")
这不会:
from "foo-bar" import *
我的问题:有什么方法可以使用上述格式,即 from "foo-bar" import *
来导入具有 -
的模块它吗?
你不能.foo-bar
不是标识符.将文件重命名为 foo_bar.py
如果 import
不是您的目标(例如:您不关心 sys.modules
会发生什么,您不需要它自己导入),只需将文件的所有全局变量放入您自己的范围内,您就可以使用 execfile
# foo-bar.py 的内容baz = 'quux'
>>>execfile('foo-bar.py')>>>巴兹'quux'>>>
I want to import foo-bar.py. This works:
foobar = __import__("foo-bar")
This does not:
from "foo-bar" import *
My question: Is there any way that I can use the above format i.e., from "foo-bar" import *
to import a module that has a -
in it?
you can't. foo-bar
is not an identifier. rename the file to foo_bar.py
Edit: If import
is not your goal (as in: you don't care what happens with sys.modules
, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile
# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>>
这篇关于当模块名称中有“-"破折号或连字符时如何导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!