当模块名称中包含' - '破折号或连字符时,如何导入模块? [英] How to import module when module name has a '-' dash or hyphen in it?

查看:162
本文介绍了当模块名称中包含' - '破折号或连字符时,如何导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于当模块名称中包含' - '破折号或连字符时,如何导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆