ProjectDude
ProjectDude

Reputation: 21

Can't import own packages in Python 2.7

I'm having some trouble importing own packages in my programs, and so I made a test folder to try and understand what I'm doing wrong.

It's the simplest of things, But I still can't get it to work.

This is my folder structure:

test
> pack1
  > __init__.py
  > mod1.py
> pack2
  > __init__.py
  > mod2.py

Both init-files are empty.

mod1 looks like this:

def foo():
    print "hello"

and mod2 looks like this

from pack1.mod1 import *

foo()

When running the code in PyCharm, everything works fine! But when trying to execute from cmd I get ImportError: No module named pack1.mod1

Is sys.path.insert(0, "../pack1") my only option, or is there another reason why cmd will not cooperate?

Upvotes: 0

Views: 1214

Answers (4)

knitti
knitti

Reputation: 7033

Regardless of version, python has to know where to look for packages. Manipulating sys.path is a quick and dirty option, which will break sometimes in the future, if your code grows more complex. Try making a package and install it via pip install -e or python setup.py develop

(Look for this at the nice distutils introduction)

Upvotes: 2

Konstantin
Konstantin

Reputation: 25349

If you do not want to modify scripts or directory layout you can use PYTHONPATH environmental variable.

Example

vagrant@h:/tmp/test/pack2$ python mod2.py
Traceback (most recent call last):
  File "mod2.py", line 1, in <module>
    from pack1.mod1 import *
ImportError: No module named pack1.mod1
vagrant@h:/tmp/test/pack2$ export PYTHONPATH="${PYTHONPATH}:/tmp/test"
vagrant@h:/tmp/test/pack2$ python mod2.py
hello
vagrant@h:/tmp/test/pack2$

More about searching modules - https://docs.python.org/2/tutorial/modules.html#the-module-search-path

Upvotes: 0

RvdK
RvdK

Reputation: 19800

You say you execute it via: (Documents)/test/pack2> python mod2.py

Problem is that pack2.mod2.py doesn't know where pack1 is.

Execute it as module: (Documents)/test> python -m pack2.mod2

Upvotes: 0

Noble Mushtak
Noble Mushtak

Reputation: 1784

In regular Python, there are only certain folders that are checked for importing packages and the test folder you have doesn't seem to be one of those files. To change this, edit sys.path in mod2.py and then import pack1.mod1.

mod2.py

import sys
# Add test folder to sys.path
sys.path.append("../")

from pack1.mod1 import *
# Prints "hello"!
foo()

Also, instead of editing sys.path, you could add the pack1 folder into the Lib folder within your Python directory. This will work because this is, by default, one of the folders in sys.path.

Python 2.7
  > Lib
    > pack1
      > __init__.py
      > mod1.py

mod2.py

from pack1.mod1 import *
# Prints "hello"!
foo()

Upvotes: 0

Related Questions