How to package a Python module

141 views Asked by At

I am a newbie to Python and I have been going through the exercises in LPTHW:
http://learnpythonthehardway.org/book/ex46.html

The explanation of packaging the author gave was very vague, so I did some researching, but I was still left with some questions in the end.

Firstly, what happens if you have a module that imports another module? Do you put the module that is imported into a subdirectory of the directory containing the first module, or in another separate directory in the root?

Secondly, once you have installed the entire package how do you run any scripts that are in the bin folder?

1

There are 1 answers

2
Burhan Khalid On BEST ANSWER

Firstly, what happens if you have a module that imports another module? Do you put the module that is imported into a subdirectory of the directory containing the first module, or in another separate directory in the root?

A module is just a file with Python code - you don't need to put it in a separate directory. The easiest option is to put the file in the same directory that contains the module that will be doing the import.

If you put it in some other directory and that directory is not a package you will not be able to import it at all (unless you manually mess around with PYTHONPATH which you shouldn't).

Secondly, once you have installed the entire package how do you run any scripts that are in the bin folder?

The way to do this is to specify the scripts for your application in the setup.py file using console_scripts. This way, when your package is installed, your scripts will be built correctly and placed in the right directories on the target platform so that you can directly execute them (without being aware of their location on the filesystem).

As an example, you can browse the setup.py file for the django project.

If you are installing a package, you don't need to know where the actual script is located - simply install the package and execute the command directly from your prompt.