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

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

问题描述

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

foobar = __import__("foo-bar")

这不会:

from "foo-bar" import *

我的问题:有什么方法可以使用上述格式,即 from "foo-bar" import * 来导入具有 - 的模块它吗?

解决方案

你不能.foo-bar 不是标识符.将文件重命名为 foo_bar.py

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

# foo-bar.py 的内容baz = 'quux'

<预><代码>>>>execfile('foo-bar.py')>>>巴兹'quux'>>>

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?

解决方案

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'
>>> 

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

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