How to relative import a package create by me using python and strucure it better?

47 Views Asked by At

Hi I'm creating a package/Module (hysysview), I have created some tests so that I can test the packages, therefore I need to import the module, however, I'm getting this error when I import HysysCOM.py in testHysys.py

Importing in testHysys

import sys
import os
from hysysview.HysysCOM import HysysReader
from enum import Enum

Error:

 line 3, in <module>
    from ..hysysview.HysysCOM import HysysReader
ImportError: attempted relative import with no known parent package

Folder tree

 |-hysysview
 | |-HysysCOM.py
 | |-HysysOperations.py
 | |-HysysOperations_backup.py
 | |-HysysVariables.py
 | |-missingOperation.txt
 | |-__init__.py
 | |-__pycache__
 |-requirements.txt
 |-setup.py
 |-test
 | |-sampleApp
 | |-stored
 | |-test7.bat
 | |-test7.txt
 | |-test8.bat
 | |-test9.bat
 | |-testHysys.py
 | |-__init__.py

To run the test I call test16. in the terminal:

test16.bat:

python testHysys.py 16 > test16.txt

WinmergeU test16.txt ./stored/test16_stored.txt

timeout /t 100

testHysys.py:

.
.
.
if __name__ == "__main__":
    
    param = sys.argv[1]
    
    if int(param) == TestIdEnum.TEST_SETTING_VALUES.value: #12
        testSettingValues()
    if int(param) == TestIdEnum.TEST_OPERATIONS_NAMES_COLLECTOR.value: #14
        testgetAllOpetationsNames()
    if int(param) == TestIdEnum.TEST_GET_ANY_PROPERTY.value: #15
        testgetOperationPropertiesValues()
    if int(param) == TestIdEnum.TEST_GENERATE_JSON.value: #16
        testGenerateJson()

Tried to solve this issue using a setup.py file but I'm not very familiar with it!

if someone can give me some advice about how to solve this issue and also structure my packages better will be welcome

Thanks you in advance

2

There are 2 best solutions below

0
rajaa lebchiri On

include it in your init.py file

from .package import *
0
chepner On

Since testHysys.py is being executed as a script, not a module, you need to explicitly set the __package__ variable so that the script knows how to resolve relative imports.

Something like

# In testHysys.py

if __name__ == "__main__" and __package__ is None:
    __package__ = "hysysview"

See PEP 366 for more details.