导入时模块执行两次! [英] Module executed twice when imported!

查看:65
本文介绍了导入时模块执行两次!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它似乎是Python的一个不变量(只要Python具有不变量)

模块在Python会话中最多执行一次。我有一个

相当古怪的例子打破了这个不变量:任何人都可以启发

我发生了什么事情?


--- test.py ---

import imptest

execfile(''subtest.py'',dict(__ name__ =''subtest.py''))

--- imptest.py ---

打印''Imptest进口''

--- subtest.py ---

导入imptest

---


$ python test.py

Imptest导入

Imptest进口

$


嗯。如果字典中省略了值__name__,或者它的

值至少不匹配''subtest。''则该消息仅打印

一次(例如,传递dict(__ name __ =''subtest'')会产生一个

导入消息)。


这两种情况都发生在python 2.4和2.3。我不明白。

It seems to be an invariant of Python (insofar as Python has invariants)
that a module is executed at most once in a Python session. I have a
rather bizzare example that breaks this invariant: can anyone enlighten
me as to what is going on?

--- test.py ---
import imptest
execfile(''subtest.py'', dict(__name__ = ''subtest.py''))
--- imptest.py ---
print ''Imptest imported''
--- subtest.py ---
import imptest
---

$ python test.py
Imptest imported
Imptest imported
$

Hmm. If the value __name__ is omitted from the dictionary, or if its
value doesn''t match at least ''subtest.'' then the message is printed only
once (for example, passing dict(__name__=''subtest'') produces one
"imported" message).

This happens with both python 2.4 and 2.3. I don''t get it.

推荐答案

python test.py

Imptest进口

Imptest进口
python test.py
Imptest imported
Imptest imported





嗯。如果字典中省略了值__name__,或者它的

值至少不匹配''subtest。''则该消息仅打印

一次(例如,传递dict(__ name __ =''subtest'')会产生一个

导入消息)。


这两种情况都发生在python 2.4和2.3。我得不到它。


Hmm. If the value __name__ is omitted from the dictionary, or if its
value doesn''t match at least ''subtest.'' then the message is printed only
once (for example, passing dict(__name__=''subtest'') produces one
"imported" message).

This happens with both python 2.4 and 2.3. I don''t get it.


Michael Abbott写道:
Michael Abbott wrote:
它似乎是Python的一个不变量(因为Python有不变量)
一个模块在Python会话中最多执行一次。我有一个相当古怪的例子打破了这个不变量:任何人都可以告诉我发生了什么事吗?

--- test.py ---
import imptest
execfile(''subtest.py'',dict(__ name__ =''subtest.py''))
--- imptest.py ---
print'' Imptest导入''
--- subtest.py ---
导入imptest
---

It seems to be an invariant of Python (insofar as Python has invariants)
that a module is executed at most once in a Python session. I have a
rather bizzare example that breaks this invariant: can anyone enlighten
me as to what is going on?

--- test.py ---
import imptest
execfile(''subtest.py'', dict(__name__ = ''subtest.py''))
--- imptest.py ---
print ''Imptest imported''
--- subtest.py ---
import imptest
---


这篇关于导入时模块执行两次!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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