How to make Python script use a designated directory as source for imports (from within the script)?

51 views Asked by At

I am currently stuck on a Python issue where I want to import scripts from another directory that is removed from the current one. The import structure is relative in certain scripts, and I do not want to change the import structure of many files. As an additional note, I want to run this file from the Command Prompt/Powershell. My file structure looks like this:

project_folder
   ->scripts_folder # I am here
      -my_script # this is the file I am running
   - other_scripts_folder # I want this to be the directory of imports
      -script1
      -script2
      ...
      - sub_folder
         -script3
         -script4
         ...

Therefore, my problem is: I want to be able to import scripts 1-4 (and others in other_scripts_folder) without changing their relative structure into my_script when running my_script from the console.

I have tried changing my current working directory by appending the path of the folder I want to import from to sys.path and directly changing my working directory as detailed in other posts related to this issue, but despite this, the Python interpreter does not import from that directory, and throws an error (because it could not locate these packages). I have also seen other posts describe how to do this in the command line — is there a way to do this in Python (i.e. not using export PYTHONPATH="${PYTHONPATH}:/your/source/root")?

0

There are 0 answers