简体   繁体   English

Python如何处理sys.path.insert(path)和不同地导入package_path.module

[英]How does Python treat sys.path.insert(path) and import package_path.module differently

I'm using pycharm and was unable to navigate to the base class from the child class code following format for the following project structure 我正在使用pycharm,无法从子类代码遵循以下项目结构的格式导航到基类

dir 1 Base class dir 2 Child class when I import the class using this way, pycharm is not able to navigate to the base class but the Python file executes properly dir 1基类dir 2子类,当我使用这种方式导入类时,pycharm无法导航到基类,但是Python文件正确执行

sys.insert.path("../dir1/")
import baseclass

When I import the class using 当我使用导入课程时

import dir1.baseclass

Makes pycharm understand where the base classes and I navigate to it using shortcuts. 使pycharm了解基类的位置,然后使用快捷方式导航到基类。 The Python scripts executes properly with pycharm in this case. 在这种情况下,Python脚本可以使用pycharm正确执行。

I am not able to understand how python automatically can figure out the path of baseclass.py in import dir1.baseclass because I'd never gave the relative or absolute path of dir1. 我无法理解python如何自动找出import dir1.baseclass中baseclass.py的路径,因为我从未提供过dir1的相对或绝对路径。 Does it automatically assume that dir1 is going to be at the same directory level as that of child class. 是否自动假设dir1与子类位于同一目录级别。

And why does pycharm behave differently with these statements for navigation works the same for execution? 为何pycharm与这些语句的行为有所不同,导航对于执行而言是相同的?

Basically, when you called the Python to run an archive, it defined the directory that contain this archive as the working directory . 基本上,当您调用Python运行档案时,它将包含该档案的目录定义为工作目录 After that, the Python's interpreter has tried to resolve the imports, and to achieve that, it first searched these imports inside the working directory. 之后,Python的解释器尝试解析导入,并实现该导入,它首先在工作目录中搜索了这些导入。

However, as you used import dir1.baseclass , you told to Python that the file baseclass was not been in the working directory, but in one of its sub-directories, in this case, inside of ../WorkingDirecory/dir1/ , so, the python navigated to there and imported the class. 但是,当您使用import dir1.baseclass ,您告诉Python该文件基类不在工作目录中,而是在其子目录之一中,在这种情况下,它位于../WorkingDirecory/dir1/内部,因此,Python导航到那里并导入了该类。

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

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