{
  "schemaVersion": "0.11.0",
  "canonical": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/",
  "atlas": "https://www.pystone.net/?node=python-modulenotfounderror-import-debug#knowledge-atlas",
  "markdown": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug.md",
  "context": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug.context.json",
  "knowledgeVersion": "224c990773de.5fa8af6e39fa",
  "build": {
    "siteCommit": "224c990773de166d23a886306577dd90379529ce",
    "notesCommit": "5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a",
    "builtAt": "1970-01-01T00:00:00.000Z",
    "version": "224c990773de.5fa8af6e39fa"
  },
  "id": "note:python-modulenotfounderror-import-debug",
  "slug": "python-modulenotfounderror-import-debug",
  "title": "Python ModuleNotFoundError与ImportError排查",
  "type": "note",
  "visibility": "public",
  "idStability": "rename-stable",
  "author": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "publisher": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "aliases": [],
  "summary": "Python ModuleNotFoundError与ImportError排查",
  "contentRole": "unspecified",
  "isMoc": false,
  "mocRecognition": "none",
  "generated": false,
  "attribution": "unspecified",
  "domain": "10-计算机、信息技术与工程",
  "tags": [],
  "mocs": [],
  "contentHash": "5346b3730b02d9cfbc1a4c46b162854c85f84ef279ff838fdffd6366e3e92c90",
  "assets": [
    {
      "reference": "assets/1621330950043.png",
      "url": "/media/a13631e2187aef2a4b70.png",
      "mediaType": "image/png",
      "contentHash": "a13631e2187aef2a4b70887179edd5ccda483fe8420a2f0d92989f77eef49c19",
      "byteLength": 88715,
      "width": 1351,
      "height": 707
    },
    {
      "reference": "assets/1621331019416.png",
      "url": "/media/e3a6d8657ccb22a2fc3d.png",
      "mediaType": "image/png",
      "contentHash": "e3a6d8657ccb22a2fc3d65dc65dc719d8a6c2cc579d9ba59ee5726f6758232b8",
      "byteLength": 16391,
      "width": 663,
      "height": 196
    }
  ],
  "headings": [
    {
      "depth": 1,
      "text": "Python ModuleNotFoundError与ImportError排查",
      "anchor": "python-modulenotfounderror与importerror排查",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#python-modulenotfounderror%E4%B8%8Eimporterror%E6%8E%92%E6%9F%A5"
    },
    {
      "depth": 2,
      "text": "【Python】How to Fix ModuleNotFoundError and Im",
      "anchor": "pythonhow-to-fix-modulenotfounderror-and-im",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#pythonhow-to-fix-modulenotfounderror-and-im"
    },
    {
      "depth": 2,
      "text": "Terminology",
      "anchor": "terminology",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#terminology"
    },
    {
      "depth": 2,
      "text": "How does module import work behind the scenes?",
      "anchor": "how-does-module-import-work-behind-the-scenes",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#how-does-module-import-work-behind-the-scenes"
    },
    {
      "depth": 3,
      "text": "Step 1: sys.modules lookup",
      "anchor": "step-1-sysmodules-lookup",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#step-1-sysmodules-lookup"
    },
    {
      "depth": 3,
      "text": "Step 2: Python Standard Library lookup",
      "anchor": "step-2-python-standard-library-lookup",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#step-2-python-standard-library-lookup"
    },
    {
      "depth": 3,
      "text": "Step 3: sys.path lookup",
      "anchor": "step-3-syspath-lookup",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#step-3-syspath-lookup"
    },
    {
      "depth": 2,
      "text": "Absolute vs Relative imports",
      "anchor": "absolute-vs-relative-imports",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#absolute-vs-relative-imports"
    },
    {
      "depth": 3,
      "text": "absolute imports",
      "anchor": "absolute-imports",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#absolute-imports"
    },
    {
      "depth": 3,
      "text": "relative imports",
      "anchor": "relative-imports",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#relative-imports"
    },
    {
      "depth": 2,
      "text": "Resolution",
      "anchor": "resolution",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#resolution"
    },
    {
      "depth": 3,
      "text": "Use IDE",
      "anchor": "use-ide",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#use-ide"
    },
    {
      "depth": 3,
      "text": "Other cases",
      "anchor": "other-cases",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#other-cases"
    },
    {
      "depth": 4,
      "text": "方法一：命令行",
      "anchor": "方法一命令行",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#%E6%96%B9%E6%B3%95%E4%B8%80%E5%91%BD%E4%BB%A4%E8%A1%8C"
    },
    {
      "depth": 4,
      "text": "方法二：python scripts",
      "anchor": "方法二python-scripts",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#%E6%96%B9%E6%B3%95%E4%BA%8Cpython-scripts"
    },
    {
      "depth": 2,
      "text": "Ref",
      "anchor": "ref",
      "citation": "https://www.pystone.net/notes/python-modulenotfounderror-import-debug/#ref"
    }
  ],
  "claims": [],
  "outgoing": [],
  "incoming": [
    {
      "id": "note:software-engineering-and-quality",
      "title": "软件工程与质量保障",
      "url": "https://www.pystone.net/notes/software-engineering-and-quality/",
      "atlas": "https://www.pystone.net/?node=software-engineering-and-quality#knowledge-atlas",
      "label": "软件工程与质量保障",
      "origin": "explicit",
      "humanReviewed": true,
      "context": "CI-CD与质量保障/CI-CD工具链中的“Python ModuleNotFoundError与ImportError排查”导航项",
      "citation": "https://www.pystone.net/notes/software-engineering-and-quality/#ci-cd%E4%B8%8E%E8%B4%A8%E9%87%8F%E4%BF%9D%E9%9A%9Cci-cd%E5%B7%A5%E5%85%B7%E9%93%BE"
    }
  ],
  "contentMarkdown": "# Python ModuleNotFoundError与ImportError排查\n\n> 创建时间：2021/5/18 17:17\n\n## 【Python】How to Fix ModuleNotFoundError and Im\n  * 【Python】How to Fix ModuleNotFoundError and ImportError\n    * Terminology\n    * How does module import work behind the scenes?\n      * Step 1: sys.modules lookup\n      * Step 2: Python Standard Library lookup\n      * Step 3: sys.path lookup\n    * Absolute vs Relative imports\n      * absolute imports\n      * relative imports\n    * Resolution\n      * Use IDE\n      * Other cases\n        * 方法一：命令行\n        * 方法二：python scripts\n    * Ref\n\n## Terminology\n\n**python module** \\- a single file with a .py extension.\n**python package** \\- a folder that contains at least one python module.\n\n>   * For python2, a package requires a **init**.py file\n>\n>   * A python package can contain any number of nested **sub-packages**\n>\n>\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n> Project myproject contains two packages, mypackage and anotherpackage each of which contains a number of python modules, while the latter also contains a sub-package called mysubpackage which in turn contains an additional python module.\n\n## How does module import work behind the scenes?\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\nPython will execute the above statement in two steps:\n\n  * Locate, load and initialise (if required) the requested module\n\n  * Define necessary names in the local namespace and corresponding scope\n\nNow Python interpreter is going to follow the next steps in an attempt to **resolve a** .\n\n### Step 1: sys.modules lookup\n\nInitially, Python will try to search for the module’s name in **sys.modules** , which is a dictionary that maps module names to modules which have already been loaded. If the name is resolved successfully (which means that another module has already loaded) it will be then be made available to the local namespace otherwise, jump into step 2.\n\n![Alt text](assets/1621330950043.png)\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n### Step 2: Python Standard Library lookup\n\n> Python Standard Library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.\n\nIf the name couldn’t be found in sys.modules then Python is going to search for it in Python Standard Library. Again, if the name is resolved then it will be defined in the local namespace otherwise step 3 needs to be followed.\n\n### Step 3: sys.path lookup\n\nNow if the module’s name was not found either in sys.modules nor in standard library, Python will finally attempt to resolve it under **sys.path**.\n\n![Alt text](assets/1621331019416.png)\n\n## Absolute vs Relative imports\n\nWe discourage the use of relative imports as they are not as readable as absolute imports\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n### absolute imports\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n### relative imports\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n## Resolution\n\n核心原则：\n\n  * use absolute imports\n\n  * append your project’s root directory to PYTHONPATH\n\n本质是：\n\n  * 给sys.path中添加路径，使得import时能够找到相应的module。\n\n  * 给sys.modules中添加item\n\n### Use IDE\n\nMost modern Python **IDEs** will do the trick automatically but if this is not the case, I am pretty sure there will be such option where you’ll be able to define the PYTHONPATH for your Python application\n\n### Other cases\n\n以下两种方法效果相同。\n\n#### 方法一：命令行\n\nIf you are running your Python application in any other environment such as **Docker** , **Vagrant** or **inside your virutal environment** you can run the below command in your bash:\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n上述命令会将相应的path添加到 **sys.path** 当中。\n\n#### 方法二：python scripts\n\nAdd this code in your python scripts:\n\n```csharp\nstring str1 = String.Empty;\nstring str2 = String.Empty;\n\nstr2 = String.Intern(sb.ToString());\n\nif((object)str1==(object)str2)\n    Console.WriteLine(&quot;The strings are equal.&quot;);\nelse\n    Console.WriteLine(&quot;The strings are not equal.&quot;);\n\n```\n\n## Ref\n\n<https://towardsdatascience.com/how-to-fix-modulenotfounderror-and-importerror-248ce5b69b1c>\n"
}
