Thomas Sablik
Thomas Sablik

Reputation: 16455

How to import own module in PyCharm console

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

Answers (4)

Ahmet Emrebas
Ahmet Emrebas

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

JohnnyQ
JohnnyQ

Reputation: 445

What worked for me was the following:

  1. Go to File -> Settings (or Default Settings) -> Build, Execution, Deployment -> Console -> Python Console
  2. Comment out "sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])"
  3. Now I can import modules inside the source roots in the console!

Upvotes: 2

ochedru
ochedru

Reputation: 856

You can also instruct PyCharm to add source roots to PYTHONPATH in the Python Console:

  • go to File -> Settings (or Default Settings) -> Build, Execution, Deployment -> Console -> Python Console
  • check "Add source roots to PYTHONPATH".

For some reason, this option is not activated by default.

Upvotes: 15

jDo
jDo

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

Related Questions