Python Attempted relative import in non-package,ImportError: cannot import name ‘xx’ from ‘__main

Problem introduction

When writing a python script, you want to extract the configuration shared by the two scripts to form a configuration file, and read the configuration file when running the script

Script tool directory structure:

	programoperater
		__init__.py
		autorun_startprogram.py		
		autorun_checkstart.py	
		programsetting.py	

In the script, import the configuration file through the relative path:

from . import programsetting

In the server, use your own installed Python 3.7.3 to report an error:

use the server’s own Python 2.7.5 to report an error:

Problem analysis, that is, python package mechanism

Official explanation: relative imports use a module’s name attribute to determine that module’s position in the package hierarchy__ name__ To achieve

Through “from. Import programsetting g”, programsetting obtains the “programoperator. Program”__ name__ Property. The premise is that the program operator is recognized by the Python interpreter as a package for processing (for example, run.py running in the peer folder of the program operator has statements such as import program operator. Program)

newfolder/
└─ programoperater
│		__init__.py
│		autorun_startprogram.py	
│		autorun_checkstart.py	
│		programsetting.py		
│
└─ run.py

there is a problem that causes me to quote packages:
scripts that I run directly will be regarded as top-level scripts. Top level script__ name__ Is automatically set to__ main__。 So if I run autorun directly from inside the program operator folder_ Checkstart. Py, then its__ name__ It’s set up__ main__, Python will not treat it as a package, and the relative import statement will not work

Note that relative imports are based on the name of the current module. Since the name of the main module is always “main”, modules intended for use as the main module of a Python application must always use absolute imports.

Solutions

change directory structure:

 programoperater
 │ 	 	__init__.py
 │   	autorun_checkstart.py
 │    	autorun_startprograms.py
 │  
 └─settings
         __init__.py
         programsetting.py

modification of package introduction mode:

from settings import programsetting

Through this modification, you can directly run the specified script autorun_ checkstart.py

Interpretation of the Official Website Package Mechanism: https://docs.python.org/zh-cn/3/tutorial/modules.html#packages

Similar Posts: