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
AlfaZulu
  • 921
  • 5
  • 13
  • 1
    Change script name - it is the simplest solution. – furas Jun 29 '14 at 15:25
  • Did you try add `os.path.append("..")` before calling `import my_package` – Valijon Jun 29 '14 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. – AlfaZulu Jun 29 '14 at 15:36
  • @user8708 I tried *sys*.path.append('..') and had no luck. – AlfaZulu Jun 29 '14 at 15:36
  • 1
    @AlfaZulu your `my_package` should be inside `scripts` to override path – Valijon Jun 29 '14 at 15:42
  • your hierarchy doesn't really make sense. It's the `setup` script that should do the imports and pass relevant data from `my_package` module to `my_package` script. If `my_package` is your main script, why put it in a sub-directory in the first place? That's counterintuitive. – Dunno Jun 29 '14 at 16:12

2 Answers2

1

For me it works with

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

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

User
  • 14,131
  • 2
  • 40
  • 59
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.

Community
  • 1
  • 1
nealmcb
  • 12,479
  • 7
  • 66
  • 91