Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python works in PyCharm but not from terminal

I recently figured out how to import modules for unittesting in python. As a solution to this, I use:

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from Dev.test import someclass

This works fine while running in PyCharm and I get the expected output. However, when I run from terminal I run into an error:

ImportError: No module named Dev.test

I have the init files where they are supposed to be but I'm lost as to why this is working in PyCharm but not from the terminal. I have not changed my path or anything in PyCharm as this code is supposed to be able to run with minimal modifications on other machines. Any idea as to why this is happening and what I might be able to do to fix it?

My folder structure is as follows

-Current
-Dev
 -__init__.py
 -test
  - __init__.py
  -someclass.py
  -Tests
   -__init__.py
   -someunittest.py

I have tried running someunittest from the main folder as well as with a complete path but it only works in PyCharm

like image 427
user3591079 Avatar asked Jul 10 '15 19:07

user3591079


People also ask

How do I use PyCharm for terminal?

Open the Terminal tool window From the main menu, select View | Tool Windows | Terminal or press Alt+F12 .

Why is Python not running in PyCharm?

To fix this go to Settings or press Ctrl+Alt+S go to Project > Project Interpreter and from the Project Interpreter dropdown select Show All then from the list select the python.exe on its current path and press the + symbol on your right.

Why is PyCharm not recognizing import?

Troubleshooting: Try installing/importing a package from the system terminal (outside of PyCharm) using the same interpreter/environment. In case you are using a virtualenv/conda environment as your Project Interpreter in PyCharm, it is enough to activate that environment in the system terminal and then do the test.


1 Answers

sys.path.append(os.getcwd()[:os.getcwd().index('Dev')])

I added this to my imports and it seems to have solved the problem. However, this doesn't seem like it would be the right way to do it; it will do for now.

like image 192
user3591079 Avatar answered Sep 19 '22 21:09

user3591079