问题:当模块名称中带有’-‘破折号或连字符时,如何导入模块?

我想导入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

从Python 3.1开始,您可以使用importlib:

import importlib  
foobar = importlib.import_module("foo-bar")

https://docs.python.org/3/library/importlib.html

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )


回答 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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。