Reputation: 16455
I have an own module in my project directory and I import it into my code.
main.py:
from my_module import Test
print(Test.test())
my_module.py:
class Test:
@staticmethod
def test():
return '123'
There is no problem running the code in PyCharm. But when I try to "Execute Selection in Console", I get
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pydev\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'my_module'
How do I import own modules in the PyCharm console?
Upvotes: 7
Views: 23230
Reputation: 945
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['C:\\Users\\ahmet\\source\\repos\\python-core'])
PyCharm adds the root directory for you.
To import a file, you need to prefix the sub-directory name if any as follows
from subdirectory.myfile from ClassA
Upvotes: 2
Reputation: 445
What worked for me was the following:
Upvotes: 2
Reputation: 856
You can also instruct PyCharm to add source roots to PYTHONPATH
in the Python Console:
For some reason, this option is not activated by default.
Upvotes: 15
Reputation: 4010
I don't use PyCharm but the problem is caused by environment variables like PATH
that aren't necessarily available from within a program/IDE.
How to fix it properly/permanently has been discussed numerous times; e.g. here and here. Often, running the program from terminal fixes the issue because the program thereby "inherits" the environment variables. Another way is to use this quick fix:
import sys
sys.path.append("/full/path/to/folder/containing/your_module.py")
# Now, this should work:
import your_module
Upvotes: 3