[英]Module throws name error when imported from package
I'm trying to import a module that contains a single line: import logging
, into my web2py project. 我正在尝试将包含一行的模块导入: import logging
到我的web2py项目中。 When I try to import the module from within a package called mymodules
, I get a <type 'exceptions.NameError'> name 'logging' is not defined error
, but When I take the module out of the package and import it directly, it works fine. 当我尝试从名为mymodules
的包中导入模块时,出现<type 'exceptions.NameError'> name 'logging' is not defined error
mymodules
<type 'exceptions.NameError'> name 'logging' is not defined error
,但是当我从包中取出模块并直接导入时,它工作正常。
mymodule.py: mymodule.py:
import logging
Importing it from top-level modules directory: 从顶级模块目录导入它:
import mymodule
- works fine import mymodule
运行正常
Importing from a package: 从包导入:
from mymodules import mymodule
- get the name error from mymodules import mymodule
获取名称错误
There's nothing wrong with the package - I have other modules in there that I import with no problem. 程序包没有问题-我在那里导入了其他模块,没有任何问题。 Don't have a clue as to why this is happening. 不知道为什么会这样。
导入mymodule后,您必须引用mymodule.logging
而不是logging
。
First off, you dont need to add the file extension .py
to your import statement. 首先,您不需要将文件扩展名.py
添加到import语句中。 So it should be: 因此应该是:
import mymodule
mymodule.logging.info("Just some info")
Anthony is correct though, if you want to be able to use logging from there, you would have to call it via mymodule.logging
You could also use a wildcard import but you just need to be a little careful of what you then import in mymodule. Anthony是正确的,但是,如果您希望能够从那里使用日志记录,则必须通过mymodule.logging
进行调用。您也可以使用通配符导入,但是您只需要对随后在mymodule中导入的内容稍加注意即可。 。
from mymodule import *
#now you can use logging directly
logging.info("Just some info")
This was happening because of some old .pyc files that were still in the package- they must have been causing the bad logging references. 发生这种情况是因为某些旧的.pyc文件仍在软件包中-它们一定引起了错误的日志记录引用。 Once I cleared them my problem was solved. 一旦清除它们,我的问题就解决了。 :S :S
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.