简体   繁体   中英

Pycharm ModuleNotFoundError: No module named // python import from child directory fails

I have been around many similar questions and articles and tried many different ways but still fail at finding where the problem is.

I created a new project in pycharm and set it as root. Then created a script at the root level that holds some variables i want to import in the scripts of sub-directories.

Here's the result of the unix tree command:

root_project  
├── subfolder  
│   └── sub_script.py  
└── variables_i_need.py  

the content of variables_i_need.py is simply name = "john"

the content of sub_script.py is

from variables_i_need import name

if __name__ == "__main__":
    print(name)

Now, when i run the sub_script.py using the在此处输入图像描述 play button of the sub_script, it works and the run console prints:

/usr/bin/python3.8 /home/root_project/subfolder/sub_script.py
john

Process finished with exit code 0

But when I try to run it from the command line it breaks:

python3 sub_script.py

~/Desktop/root_project/subfolder » python3 sub_script.py                                                                                      gabri@gabriele-computer
Traceback (most recent call last):
  File "sub_script.py", line 1, in <module>
    from variables_i_need import name
ModuleNotFoundError: No module named 'variables_i_need'

If you look into PyCharm configuration, there are two options:

  1. Add content roots to PYTHONPATH
  2. Add source roots to PYTHONPATH

They are flagged by default.

In your case, the first one allows you to run the script correctly because it adds root_project path in the PYTHONPATH environment variable.

So, if you want to run the script also in command line you should set the same variable.
You can proceed like this:

  1. Open command line

  2. If you are on Linux you can use

    export PYTHONPATH=<absolute_path_of_root_project>

  3. If you are on Windows you can use

    SET PYTHONPATH=<absolute_path_of_root_project>

  4. Run script

    ~/Desktop/root_project/subfolder » python3 sub_script.py

Please remember that the export/set command is not permanent, it is valid for the current command line session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM