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
I was getting the error with "Add source roots to PYTHONPATH" as well. My problem was that I had two folders with the same name, like project/subproject1/thing/src
and project/subproject2/thing/src
and I had both of them marked as source root. When I renamed one of the "thing"
folders to "thing1"
(any unique name), it worked.
Maybe if PyCharm automatically adds selected source roots, it doesn't use the full path and hence mixes up folders with the same name.
Always mark as source root the directory ABOVE the import!
So if the structure is
parent_folder/src/module.py
you must put something like:
from src.module import function_inside_module
and have parent_folder
marked as "source folder" in PyCharm
The solution for this problem without having to Mark Directory as Source Root is to Edit Run Configurations and in Execution select the option "Redirect input from" and choose script you want to run. This works because it is then treated as if the script was run interactively in this directory. However Python will still mark the module name with an error "no module named x":
When the interpreter executes the import statement, it searches for x.py in a list of directories assembled from the following sources:
I was having this problem just now and I was able to solve it in sort of a similar way that @Beatriz Fonseca and @Julie pointed out.
If you go to File
-> Settings
-> Project: YourProjectName
-> Project Structure
, you'll have a directory layout of the project you're currently working in. You'll have to go through your directories and label them as being either the Source
directory for all your Source files, or as a Resource
folder for files that are strictly for importing.
You'll also want to make sure that you place __init__.py
files within your resource directories, or really anywhere that you want to import from, and it'll work perfectly fine.
I hope this answer helps someone, and hopefully JetBrains will fix this annoying bug.
my_module
is a folder not a module and you can't import a folder, try moving my_mod.py
to the same folder as the cool_script.py
and then doimport my_mod as mm
. This is because python only looks in the current directory and sys.path
, and so wont find my_mod.py
unless it's in the same directory
Or you can look here for an answer telling you how to import from other directories.
As to your other questions, I do not know as I do not use PyCharm.
This can be caused when Python interpreter can't find your code. You have to mention explicitly to Python to find your code in this location.
To do so:
sys.path.extend(['your module location'])
to Python console.In your case:
On the start, write the following code:
import sys
sys.path.extend([my module URI location])
Once you have written this statement you can run following command:
from mymodule import functions