OS independent path import in Python

895 Views Asked by At

I'm working on the development of a some small Python packages in parallel, and I have organized my repository as follow:

|- root_folder
    |- source_code_folder
        |- package1
        |- package2
        |-...
    |- test_folder
        |- package1_test_folder
            |- package1_test.py

Where root_folder is the repository, source_code_folder contains the packages to be imported and tested in the test.py files contained in test_folder/packageX_test_folder.

I've written the following lines of code to add to the PATH the source_code_folder(not permanently) from whatever test_folder/package1_test_folder/test.py file.

if __name__ == '__main__':
    def __import_pkgs():
        # automatically add to the path the source_code_folder folder if it is not contained yet
        THIS_PATH = os.getcwd().split('\\')
        for i in range(THIS_PATH.index('root_folder'),len(THIS_PATH)-1): THIS_PATH.pop()
        ROOT_PATH = '\\'.join(THIS_PATH)
        PKG_PATH = ROOT_PATH + '\\source_code_folder\\'
        if sys.path.count(PKG_PATH) == 0: sys.path.append(PKG_PATH)
        return None

    __import_pkgs()

In this way, however, this __import_pkgs() function works only for Windows-based environments. Is there any way to made this independant to the OS systems? Anyone have any suggestion to make it more efficient/elegant?

2

There are 2 best solutions below

1
On BEST ANSWER

i recommend using "os.path" like so:

import sys
from os import path

if __name__ == '__main__':
    software_code_full_path = path.abspath(path.join(path.dirname(__file__), '../../source_code_folder'))

    if software_code_full_path not in sys.path:
        sys.path.append(software_code_full_path)
3
On

use os.sep to get the path separator instead of explicitly using forward or backward slash