0

I'm trying to understand how this work but I'm really confused.

I created a package "parent" under C:\script\test with empty __init__.py

parent\testfunc.py

def return_2():
    return 2

Then, a couple sub packages with empty __init__.py

parent\sub\subsub\testsubsub.py

from parent import testfunc

def print_2():
    print(testfunc.return_2())

if __name__ == '__main__':
    print_2()
  • If I execute this within PyCharm, it works. I get 2.
  • Open CMD, add C:\script\test to %PATH%, it cannot find the parent module
  • CMD with %PATH% set and -m flag, it says I cannot import by filename

Why do I get different result? Why could it not find the package if it's already added to the %PATH%? Why did it work in PyCharm?

Edit - I am unsure if the provided link was addressing the same issue since the OP was able to import his package while I cannot. Additional searching brought me to this thread which suggested %PYTHONPATH% instead of %PATH% and that seems to do the trick.

Panupat
  • 452
  • 6
  • 21
  • Don't put scripts inside packages, scripts are executed as `__main__` and *are not in a package*. – Martijn Pieters Apr 09 '18 at 07:02
  • In this case, you need to put `C:\script\test` on your Python module search path, explicitly, so to `PYTHONPATH`, not `PATH`. There are no mechanisms that would put `parent` anywhere on the search path just because you created sub-packages. Your script has no package context. – Martijn Pieters Apr 09 '18 at 07:03
  • What is package context? Is it how you set up \__init__.py? I'm looking at numpy as example and I admit I'm totally lost. – Panupat Apr 09 '18 at 07:05
  • You didn't include how you ran with the `-m` flag; for `python -m`, a **module** name is expected, so `parent.sub.subsub.testsubsub`. – Martijn Pieters Apr 09 '18 at 07:05
  • `__init__.py` files in the same directory as a script have no meaning, no. – Martijn Pieters Apr 09 '18 at 07:05

0 Answers0