简体   繁体   English

Python子模块导入

[英]Python sub module import

Lets say i have an app with a GUI.假设我有一个带有 GUI 的应用程序。

the folder structure is:文件夹结构是:

\project
   run.py
   gui.py
   \tracker
      tracker.py
      trackerdialog.py
      trackerDB.py

run.py is the main app entry point. run.py 是主要的应用程序入口点。 it imports a bunch of packages including "import tracker.tracker"它导入了一堆包,包括“import tracker.tracker”

while I'm working on tracker.py, tracker.py reads: import trackerDialog, trackerDB当我在 tracker.py 工作时,tracker.py 读取: import trackerDialog, trackerDB

when I run tracker.py, everything works but when I import tracker from run.py.当我运行 tracker.py 时,一切正常,但是当我从 run.py 导入跟踪器时。 run.py errors with "no module named trackerDialog" “没有名为 trackerDialog 的模块”的 run.py 错误

What is the proper way to import this submodule so i can test it isolated as tracker.py but also still have run.py be able to import it?导入此子模块的正确方法是什么,以便我可以将它隔离为 tracker.py 进行测试,但仍然让 run.py 能够导入它?

Base it from the working directory of the main program基于主程序的工作目录

from tracker import trackerdialog, trackerDB

You may also need to write a file named literally __init__.py (it does not need any content) to mark the directory ./tracker as containing Python libs (more here: What is __init__.py for? )您可能还需要编写一个字面上命名为__init__.py的文件(它不需要任何内容)以将目录./tracker标记为包含 Python 库(更多信息:__init__.py 用于什么?


To use the file as both a library in a directory and also directly run it, consider either要将文件用作目录的库直接运行它,请考虑

  • creating a dedicated runner in the root directory在根目录中创建一个专用的运行器
  • try/excepting ImportError尝试/排除ImportError
     try: from tracker import trackerdialog, trackerDB except: import trackerDialog, trackerDB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM