Charlie Martin
Charlie Martin

Reputation: 112386

organizing a Python application

I have a Python application, and I have a question about packaging that isn't really a distutils question, but rather a question of how to organize and set up the application so it's easily used from the command line.

Assume the application contains one package, and assume for the moment that I don't necessarily want to make it a distutils package (although I could be dissuaded.)

The program itself as an SNMP subagent to be run by Net-SNMP using pass_persist. This isn't particularly important to the question, it just means the program overall is exec'd, and reads stdin with responses on stdout.

Further assume the agent is structured in the more or less canonical Python fashion

  agent
      __init__.py
      main.py
      <other modules at the same level>

main.py is a simple program something like

#!/usr/bin/env python
import sys
def main(argv):
    <initialize the environment, input output, logging and so on>
    while <not done>:
         <process an input>
    <clean up and terminate>

if __name__ == '__main__':
    main(sys.argv)

There seem to be just a few ways this can be organized to be run:

Put the package somewhere in site-packages and have a top-level program in the PATH like

#!/usr/bin/env python
from agent import main
main(sys.argv)

Put the package directory somewhere and run it by using

/path/to/directory/agent/main.py

(with the bumpo version being to put the agent directory in the path somewhere so you can just run main.py)

or some third, more Pythonic and cool, method that lets me install the code and put something into the path directly that I don't know.

Googling hasn't helped much, I suspect this is one of those "too dumb to answer" questions. I am, unfortunately, too dumb to know that.

Upvotes: 1

Views: 267

Answers (2)

Keith
Keith

Reputation: 43044

The first option you listed is the usual "Pythonic and cool" method of doing this. You can also use Distribute to manage it so it can be developed more conveniently. Then package or install when completed. The Distribute system can be used to manage your development as well as being used as a packaging tool. It also generate launcher scripts for you. You define entry points in your setup.py and it will create the top-level launcher script for you.

When developing you can set Development Mode that sets up the Python environment to look for your package in your workspace. So any changes are immediately visible when run next time. Then, after it s developed you can package it as an egg, or even build an RPM or Windows installer from the same source.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799130

"Put the package directory somewhere" is most of it. The rest is to write a shell script that uses exec on the python interpreter with the main.py script.

#!/bin/sh
exec python /usr/share/myapp/main.py "$@"

Upvotes: 1

Related Questions