Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python run package without installing

As part of my build system, I am using a modified version of a Python package (cogapp). I don't want to install the package because:

  1. I've modified the package and don't want to worry about collision with unmodified versions which may already be installed.
  2. It's nicer if the users of the build system don't need to install extra packages.

However, I'm having problems with using the package if it's not installed. If it is installed, I can run:

python -m cogapp <additional args>

and everything runs as intended.

The package has a __main__.py script:

import sys
from cogapp import Cog

sys.exit(Cog().main(sys.argv))

I tried running this directly, e.g.:

python -m <path>/__main__ <additional_args>

But I get the error:

...
/__main__.py", line 3, in <module>
    from cogapp import Cog
ImportError: No module named cogapp

This is probably related to the error I get if I run __init__.py:

from .cogapp import *

The error is:

    from .cogapp import *
ValueError: Attempted relative import in non-package

How can I run the package as a package?

EDIT:

I found a fix by removing all the relative imports from cogapp, and removing the -m, i.e. not running as a module. In this instance it's not too bad because it's a small package with only a single directory. However I'm interested in how this should be done in future. There's lots of stuff written around this subject, but no clear answers!

like image 980
Stefan Avatar asked Nov 02 '22 15:11

Stefan


1 Answers

Here's the solution I've come to.

Disclaimer: you are actually installing the package but to a different path than the standard one.

$ mkdir newhome
$ python setup.py install --home=./newhome
$ PYTHONPATH=$PWD/newhome/lib/python <COMMAND_NEEDING_THAT_PACKAGE>
like image 105
George Avatar answered Nov 15 '22 06:11

George