问题:当模块名称中带有’-‘破折号或连字符时,如何导入模块?
我想导入foo-bar.py。这有效:
foobar = __import__("foo-bar")
这不是:
from "foo-bar" import *
我的问题:有什么办法可以使用上述格式,即from "foo-bar" import *
导入其中包含的模块-
?
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?
回答 0
你不能。 foo-bar
不是标识符。将文件重命名为foo_bar.py
编辑:如果import
不是您的目标(例如:您不在乎会发生什么sys.modules
,您不需要导入自身),只需将文件的所有全局变量放入自己的作用域即可,您可以使用execfile
# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>>
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'
>>>
回答 1
如果您不能重命名模块以匹配Python命名约定,请创建一个新模块以充当中介:
---- foo_proxy.py ----
tmp = __import__('foo-bar')
globals().update(vars(tmp))
---- main.py ----
from foo_proxy import *
If you can’t rename the module to match Python naming conventions, create a new module to act as an intermediary:
---- foo_proxy.py ----
tmp = __import__('foo-bar')
globals().update(vars(tmp))
---- main.py ----
from foo_proxy import *
回答 2
回答 3
如果您不能重命名原始文件,则还可以使用符号链接:
ln -s foo-bar.py foo_bar.py
然后,您可以:
from foo_bar import *
If you can’t rename the original file, you could also use a symlink:
ln -s foo-bar.py foo_bar.py
Then you can just:
from foo_bar import *
回答 4
就像其他人说的那样,您不能在python命名中使用“-”,有许多解决方法,其中一种这样的解决方法在必须从路径添加多个模块的情况下非常有用。 sys.path
例如,如果您的结构是这样的:
foo-bar
├── barfoo.py
└── __init__.py
import sys
sys.path.append('foo-bar')
import barfoo
Like other said you can’t use the “-” in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path
For example if your structure is like this:
foo-bar
├── barfoo.py
└── __init__.py
import sys
sys.path.append('foo-bar')
import barfoo