I am having trouble importing python packages only when running python from cmdline/console. However, when using pydev, everything seems to work fine.
I have the following filesystem…
---MarketData
---Parser
---Parser.py
---__init__.py
---IO
---__init__.py
---MarketSocket.py
Currently, Parser and IO are defined as python packages (they have init.py files, although there is no code in the Parser.init.py file.
I am trying to run the following line of code in MarketSocket.py
from Parser import Parser
Which should import the module ‘Parser’ within the package ‘Parser’ however, I get the following error.
ImportError: No Module Named Parser
Any help would be appreciated! This should work according to similar issues on stackOverflow, but for some odd reason it isn’t.
MarketSocket.pyis in the directoryIO. Therefore it is not possible to find the packageParser.The best way to resolve this, are relative imports:
from ..Parser import ParserBut they might not work, if you start the script like:python MarketSocket.py. To use this, you would also have to add an__init__.pyto yourMarketDatadirectory.If it doesn’t work extend the
sys.pathlike this:With this addition, Python searches also the paths you want.
If I were you I would also think about restructuring your project. In my opinion executables should be (most of the time) at the top of your working tree, which is also like Python works.