当模块名称中包含' - '破折号或连字符时,如何导入模块?

时间:2021-07-21 16:49:43

I want to import foo-bar.py. This works:

我想导入foo-bar.py。这有效:

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?

我的问题:有什么方法可以使用上面的格式,即从“foo-bar”import *导入一个有 - 中的模块吗?

3 个解决方案

#1


71  

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

你不能。 foo-bar不是标识符。将文件重命名为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

编辑:如果导入不是你的目标(如:你不关心sys.modules会发生什么,你不需要它自己导入),只需将所有文件的全局变量放到你自己的范围内,你可以使用的execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

#2


73  

If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:

如果您无法重命名模块以匹配Python命名约定,请创建一个新模块以充当中介:

 ---- foo_proxy.py ----
 tmp = __import__('foo-bar')
 globals().update(vars(tmp))

 ---- main.py ----
 from foo_proxy import * 

#3


36  

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 *

#1


71  

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

你不能。 foo-bar不是标识符。将文件重命名为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

编辑:如果导入不是你的目标(如:你不关心sys.modules会发生什么,你不需要它自己导入),只需将所有文件的全局变量放到你自己的范围内,你可以使用的execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

#2


73  

If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:

如果您无法重命名模块以匹配Python命名约定,请创建一个新模块以充当中介:

 ---- foo_proxy.py ----
 tmp = __import__('foo-bar')
 globals().update(vars(tmp))

 ---- main.py ----
 from foo_proxy import * 

#3


36  

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 *