本文介绍了当模块名称中包含' - '破折号或连字符时,如何导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想导入foo-bar.py。这有效:
I want to import foo-bar.py. This works:
foobar = __import__("foo-bar")这不是:
from "foo-bar" import *我的问题:有什么方法可以使用上面的格式,即从foo-bar导入* 导入一个 - 的模块?
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 不是标识符。将文件重命名为 foo_bar.py
you can't. foo-bar is not an identifier. rename the file to foo_bar.py
编辑:如果 import 不是你的目标(如:你不关心 sys.modules 会发生什么,你不需要它导入只需将所有文件的全局变量放入自己的范围,就可以使用 execfile
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' >>>
更多推荐
当模块名称中包含'
发布评论