【问题标题】:Python script executed twice with Eclipse PyDev使用 Eclipse PyDev 执行两次 Python 脚本
【发布时间】:2014-06-09 10:49:00
【问题描述】:

我在 Eclipse PyDev 中有一个名为automated_vertica 的项目,其架构如下:

automated_vertica
    src
        root
            __init__.py
            RequestHandler.py

RequestHandler.py 是一个只有一堆方法的模块。

__init__.py 只包含两行:

from root import RequestHandler
print('test')

当我在 PyDev 中运行 __init__.py 时,Eclipse 控制台会读取两次 test。如果我删除from root,它就可以正常工作。

您能否解释一下我缺少什么以及这里发生了什么?

编辑:RequestHandler.py 的内容

'''
Created on Apr 23, 2014

@author: myname
'''
def FileToString(fileName): 
    f = open(fileName, 'r')
    result = f.read() 
    f.close()
    return result

def Flatten(listOfLists):
        return [value for sublist in listOfLists for value in sublist]

【问题讨论】:

  • RequestHanlder.py 中有什么内容?
  • 我已经添加了这个模块的内容
  • 但即使是空模块,也会出现问题。
  • 等一下。是from root import... 还是__init__.py 还是init.py
  • __init__.py(当我在我的问题中输入它时它只是用粗体写的)

标签: python eclipse python-2.7 python-import


【解决方案1】:

由于root 有一个__init__ 文件,它是一个模块。

当您运行from module import.. 时,它会执行该模块__init__ 中的任何代码。

并且由于您的__init__ 包含print,因此会被执行。

由于您直接运行__init__(顺便说一句,您不应该这样做),它正在执行以下操作:

-> from root import RequestHandler
    -> root.__init__:
        -> import RequestHandler
        -> print("Test")
-> print("Test")

__init__ 对于检查是否存在任何模块、后备或检查 python 版本很有用。

例如,这个__init__.py不会让任何低于400的Python版本导入模块:

import sys

if not hasattr(sys, "version_info") or sys.version_info < (400, 0):
    raise RuntimeError("root requires Python 400.0 or later.")

del sys

from root import RequestHandler
print("Test")

让我们希望它更新到时间结束。

【讨论】:

  • 如果我只输入import RequestHandler,它不会执行__init__.py?另外,如果不在__init__.py 中,我应该把我的打印放在哪里?
  • 正确。因为它是在本地导入(因为它在同一目录中)而不是从模块中导入。如果您愿意,您可以将打印件保留在__init__,但我不确定您为什么要这样做。将其放入您正在执行的代码中 - 主 whatever.py 即您的主程序。
猜你喜欢
  • 1970-01-01
  • 2013-05-25
  • 2013-08-11
  • 2012-08-31
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2020-07-14
相关资源
最近更新 更多