PyCharm error: 'No Module' when trying to import own module (python script)

前端 未结 14 1789
醉话见心
醉话见心 2020-12-07 07:57

I have written a module (a file my_mod.py file residing in the folder my_module). Currently, I am working in the file cool_script.py t

相关标签:
14条回答
  • 2020-12-07 08:17

    The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:

    • "Add content roots to PYTHONPATH"
    • "Add source roots to PYTHONPATH"

    I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.

    0 讨论(0)
  • 2020-12-07 08:19

    If your own module is in the same path, you need mark the path as Sources Root. In the project explorer, right-click on the directory that you want import. Then select Mark Directory As and select Sources Root.

    I hope this helps.

    0 讨论(0)
  • 2020-12-07 08:21

    The key confusing step that must be done is to recreate the run configuration for the source file that you're trying to execute, so that the IDE picks up the new paths.

    The way that actually worked for me was to go to Run/Edit Configurations..., select the configuration for the file that you're trying to run on the left side, uncheck the "Add source roots to PYTHONPATH" box, save, and then go back and check the box and save. THEN it would work.

    0 讨论(0)
  • 2020-12-07 08:21

    Pycharm 2017.1.1

    1. Click on View->ToolBar & View->Tool Buttons
    2. On the left pane Project would be visible, right click on it and press Autoscroll to source and then run your code.

    This worked for me.

    0 讨论(0)
  • 2020-12-07 08:23

    So if you go to

    -> Setting -> Project:My_project -> Project Structure,

    Just the directory in which the source code is available and mark it as "Sources" (You can see it on the same window). The directory with source code should turn blue. Now u can import in modules residing in same directory.

    0 讨论(0)
  • 2020-12-07 08:23

    Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.

    Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.

    Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.

    0 讨论(0)
提交回复
热议问题