2

I have a script that when I run it from pycharm, it runs fine, but when executed from the command line it complains

import util as u

ModuleNotFoundError: No module named 'util'

I followed this advice here: Script running in PyCharm but not from the command line

Interpreter is the same, working directory is the same, but sys paths are different.

The module's folder looks like this

mymodule
    sub_1
        util.py
    sub_2
         ...
    main.py

pycharm shows all folders when printing sys.path elements. when running from the command line, it doesn't show any of them, even when I run it from thr director where main.py is. Do I have to add the directory to PYTHONPATH even when I run the file from that directory? Seems like overkill having every project's directory added. Is there a better way to do this or is that the standard procedure?

martineau
  • 119,623
  • 25
  • 170
  • 301
chrise
  • 4,039
  • 3
  • 39
  • 74
  • 1
    try relative `import .util as u` – digitake Jun 20 '17 at 11:47
  • make `__init__.py` in `sub_1` – RaminNietzsche Jun 20 '17 at 11:53
  • It seems you don't have a package with subpackages, you have directories containing a bunch of ifles. If `mymodule` was a package, the directory containing it shoud be on `sys.path`, every directory below it should have an `__init__.py` and your shoudn't try call a script inside it. A lounch script should be on the same level as the top level directory and basically just import the entry point and call it. – mata Jun 20 '17 at 11:57
  • thanks digitake. the dot worked its magic. if you could add as reply, I can accept – chrise Jun 20 '17 at 12:08

2 Answers2

3

digitake's suggestion to use a relative path worked

import .util as u
chrise
  • 4,039
  • 3
  • 39
  • 74
2

I think more information is needed to make solution recommendations, but here is what I would check for:

  1. does your package of modules have the __init__.py file(s)
  2. when using command line, are you calling python interpreter with the -I parameter? that would strip location context from your script and so not scan the local directory for modules or packages, so if you do, try running without it.
Ilia Gilmijarow
  • 1,000
  • 9
  • 11