16

I'm trying to re-organize my Python project by moving scripts from the package directory into a top level script directory. After these changes, this is what my project hierarchy looks like:

MyProject/
    setup.py

    scripts/
        my_package.py

    my_package/
        __init__.py
        module_foo.py

Notice how the script and the package have the same name.

The script my_package.py looks something like this:

# MyProject/scripts/my_package.py
import os
try:
    import my_package
    print os.path.abspath(my_package.__file__)
except ImportError as e:
    print e

When we run the above script the interpreter imports the current module rather than the package of the same name (note: the package my_package has already been installed into site-packages as an egg and our virtual environment is properly activated.)

How can I import the package my_package from the script my_package.py given they have the same name?

Other Technical Info:

  • Python 2.7.3
  • Ubuntu Server 12.04 LTS
  • VirtualEnv 1.11.6
6
  • 1
    Change script name - it is the simplest solution. Commented Jun 29, 2014 at 15:25
  • Did you try add os.path.append("..") before calling import my_package Commented Jun 29, 2014 at 15:27
  • @furas is renaming the script really my only choice? Based on what I've read about the "absolute import" feature, the import syntax I used should work. Commented Jun 29, 2014 at 15:36
  • @user8708 I tried sys.path.append('..') and had no luck. Commented Jun 29, 2014 at 15:36
  • 1
    @AlfaZulu your my_package should be inside scripts to override path Commented Jun 29, 2014 at 15:42

2 Answers 2

1

For me it works with

sys.path.insert(0, '..')

since the import does something like for path in sys.path:.

Sign up to request clarification or add additional context in comments.

Comments

1

You probably want to rename my_package.py, using the canonical name for the core script for a module: __main__.py, and put it back in your module directory. Then also arrange for the my_package executable to be automatically generated by defining an entry_point for it in your setup.py file. Python Apps the Right Way: entry points and scripts, by Chris Warrick covers this in some depth.

See also What is main.py? - Stack Overflow to see some of the other ways of calling my_package that this also sets up automatically, like python -m my_package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.