Scripts in python package

I am developing a python application that I decided to turn into a package that will be installed later by easy_install or pip . I used a search to find some good sources about the directory structure for python packages. See this answer or this post .

I created the following structure (I skipped a few files in the list to make strcture more understandable)

  Project /
 | - bin /
 | - my_package /
 |  | - test /
 |  |  | - __init__.py
 |  |  | - test_server.py
 |  | - __init__.py
 |  | - server.py
 |  | - util.py
 | - doc /
 |  | - index.rst
 | - README.txt
 | - LICENSE.txt
 | - setup.py           

After that, I created the server-run script executable

  #! / usr / bin / env python
 from my_package import server

 server.main ()

which I put in the bin directory. If I install my package using python setup.py install or through pip/easy_install , everything works fine, I can run server-run and my server will start processing incoming requests.

But my question is, how can I verify that server-run running in a development environment ( without first installing my_package )? I also want to use this script to run the latest server code for dev purposes.

Development takes place in the Project directory, so I get ImportError if I run ./bin/server-run

  user@host : ~ / dev / Project / $ ./bin/server-run
 Traceback (most recent call last):
   File "./bin/server-run", line 2, in 
     import my_package
 ImportError: No module named my_package

Is it possible to change the bin/server-run script so that it works if I run it from another folder somewhere in the file system (not necessarily from Project dir)? Also note that I want to use (if possible) the same script to start the server in a production environment.

+7
source share
3 answers

You need relative imports. Try

 from .. import mypackage 

or

 from ..mypackage import server 

Documentation here

http://docs.python.org/tutorial/modules.html#intra-package-references

They work with Python 2.5 or later.

To do this only in the development version, try:

 try: from my_package import server except ImportError: from ..my_package import server 
+3
source

You can use virtualenv to test Python code during development, as if it were released

+4
source

The easiest way is to set up the correct Python path, so Python knows how to look for my_package in the current directory.

On Linux (using Bash):

 export PYTHONPATH=. bin/server-run 

On Windows:

 set PYTHONPATH=. python bin/server-run 
+2
source

All Articles