Search code examples
pythonpython-3.ximportrelative-import

Import module from parent folder but still working in child directory


I'm relatively new to Python and I need to make a script which can call a function from a file in parent folder. In simple terms, the directory now looks like this:

  • parentModule.py
  • childDirectory/
    - childScript.py

parentModule.py contains the following script

def runFunction():
    print('function triggered')
    return 1

childScript.py contains the following script

import sys, os

sys.path.append( os.path.dirname(os.path.realpath(__file__))+'/..')
import parentModule

def runChildMain():
    '''
    run runFunction from parentModule.py
    '''
    parentModule.runFunction()

    # Do stuff in childDirectory, for example, create an empty python file
    open('test', 'a').close()

runChildMain()

I need to be able to run childScript.py on its own because later on the childScript.py will be run as a subprocess. The problem is that when I use sys.path, which I did not mention before, the command to create a file with open() runs in the parent directory, not in the childDirectory. So, this results in the file 'test' created in the parentDirectory, but I need it to be created inside childDirectory.


Solution

  • The correct way of doing this is to run the script with the -m switch

    python -m childDirectory.childScript # from the parent of childDirectory
    

    Then in childScript you do a simple from parentModule import runFunction. Hacking the sys path is bad practice and using chdir should be also avoided (leads to nasty surprises)