phihag
phihag

Reputation: 288130

How to modularize a Python application

I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up with are:

What is the best method?

Upvotes: 6

Views: 5888

Answers (5)

bobince
bobince

Reputation: 536587

Adding to sys.path (usually using site.addsitedir) is quite common and not particularly frowned upon. Certainly you will want your common working shared stuff to be in modules somewhere convenient.

If you are using Python 2.6+ there's already a user-level modules folder you can use without having to add to sys.path or PYTHONPATH. It's ~/.local/lib/python2.6/site-packages on Unix-likes - see PEP 370 for more information.

Upvotes: 8

Daniel Naab
Daniel Naab

Reputation: 23066

If you have multiple environments which have various combinations of dependencies, a good solution is to use virtualenv to create sandboxed Python environments, each with their own set of installed packages. Each environment will function in the same way as a system-wide Python site-packages setup, but no superuser rights are required to create local environments.

Google has plenty of info, but this looks like a pretty good starting point.

Upvotes: 3

Can Berk Güder
Can Berk Güder

Reputation: 113370

I've used the third approach (add the directories to sys.path) for more than one project, and I think it's a valid approach.

Upvotes: 1

dF.
dF.

Reputation: 75805

Another alternative to manually adding the path to sys.path is to use the environment variable PYTHONPATH.

Also, distutils allows you to specify a custom installation directory using

 python setup.py install --home=/my/dir 

However, neither of these may be practical if you need to have multiple versions running simultaneously with the same module names. In that case you're probably best off modifying sys.path.

Upvotes: 1

sth
sth

Reputation: 229754

You can set the PYTHONPATH environment variable to the directory where your library files are located. This adds that path to the library search path and you can use a normal import to import them.

Upvotes: 4

Related Questions