为什么这是这个python程序的输出?

时间:2010-05-26 21:28:30

标签: python import module hook sys

来自#python的人建议它搜索模块“herpaderp”并查找所有列出的搜索结果。如果是这种情况,为什么在引发ImportError之前它不会列出我系统上的每个模块?有人可以了解这里发生的事情吗?

import sys

class TempLoader(object):     
    def __init__(self, path_entry):
        if path_entry == 'test': return
        raise ImportError

    def find_module(self, fullname, path=None):
        print fullname, path
        return None

sys.path.insert(0, 'test')
sys.path_hooks.append(TempLoader)
import herpaderp

输出:

16:00:55 $> python wtf.py
herpaderp None
apport None
subprocess None
traceback None
pickle None
struct None
re None
sre_compile None
sre_parse None
sre_constants None
org None
tempfile None
random None
__future__ None
urllib None
string None
socket None
_ssl None
urlparse None
collections None
keyword None
ssl None
textwrap None
base64 None
fnmatch None
glob None
atexit None
xml None
_xmlplus None
copy None
org None
pyexpat None
problem_report None
gzip None
email None
quopri None
uu None
unittest None
ConfigParser None
shutil None
apt None
apt_pkg None
gettext None
locale None
functools None
httplib None
mimetools None
rfc822 None
urllib2 None
hashlib None
_hashlib None
bisect None
Traceback (most recent call last):
  File "wtf.py", line 14, in <module>
    import herpaderp
ImportError: No module named herpaderp

2 个答案:

答案 0 :(得分:3)

看起来这就是发生的事情:

http://rhodesmill.org/brandon/2010/ubuntu-exception-190-modules/

基本上,apport模块(不是标准lib的一部分)在异常被写入stdout之前,与异常相关联。因此,当程序找不到“herpaderp”时,它会抛出异常并触发apport及其包含的所有模块的导入,并在异常之前将其显示在输出中。

  

解决方案?我已经删除了   “python-apport”包,以及   那个“ubuntuone-client”套件   取决于它。卸载后,   例外是 - 非常好 -   不会导致单个导入新的   模块!现在,最后,我可以继续   和平地写下我的导入钩子。

答案 1 :(得分:0)

对于为什么会发生这种情况,没有一个好的答案,但是我在测试它的两个操作系统之间有所不同。

2.5.1&amp;在Windows上的2.6.4:

E:\work\python>python wtf.py
herpaderp None
Traceback (most recent call last):
  File "wtf.py", line 14, in <module>
    import herpaderp
ImportError: No module named herpaderp

E:\work\python>python --version
Python 2.5.1
Linux上的

2.5.2:

$ python wtf.py
herpaderp None
apport None
subprocess None
... etc etc
_locale None
operator None
shutil None
Traceback (most recent call last):
  File "wtf.py", line 14, in <module>
    import herpaderp
ImportError: No module named herpaderp
$ python --version
Python 2.5.2

很抱歉,这不是一个真正的答案,但有点太长了,无法发表评论!