Search code examples
pythonintellij-ideapython-import

Python set working directory like Intellij in terminal


I have a python which has the following folder/file structure.

Project/
-- generic_module
-- directory
---- sub_directory
------ main.py (uses generic_module, & other imports are relative to Project)

Now if I want to run main.py via Intellij IDE, I can just set the "Working Directory" in the run configuration and it works fine. enter image description here

I want to run it via terminal without Intellij IDE. In that case what do I do ?

I tried things like "python directory/sub_directory/main.py" from the Project/ folder, but still I am facing import errors.


Solution

  • IntelliJ IDE behind the hoods changes the pythonpath env variable. So run the python script via terminal one could do it in two ways

    Powershell

    $env:PYTHONPATH+=";<path_of_directories_containing_the_imports>
    

    Other shell such as bash, etc change the env "PYTHONPATH" as shown

    Pythonic way (thanks to Tim Roberts comments)

    sys.path.append(...)
    

    or

    os.abspath(os.dirname(__file__)+"../..")