4

Suppose I have a python package called mypackage, which has a series of scripts. Once mypackage is in the site-packages dir, the user can refer to various Python files within mypackage as mypackage.submodule1, mypackage.submodule2 from Python, as usual. However, some of these are scripts that are meant to be called from the command line. In submodule1 for example, I have:

== mypackage/submodule1.py ==

if __name__ == '__main__':
  main()

def main():
  # parse command line options here, do stuff

How can I properly distribute/package mypackage so that the user can cleanly use these submodules as command line scripts once "mypackage" is in their path? I would have thought you can do:

python mypackage.submodule1.py arg1 arg2 ...

but this syntax is invalid. In other words, how can the user refer to submodules of my package as scripts rather than importing them from Py, without requiring the actual "mypackage" dir to be in their PYTHONPATH? (Only the toplevel directory, e.g. site-packages, which contains "mypackage" should be in their PYTHONPATH.)

Thanks.

2 Answers2

4

See http://docs.python.org/distutils/setupscript.html#installing-scripts

The general idea is to distribute a setup.py file, such that when a user runs python setup.py install, the script gets placed on the path. Nearly all of the package distribution methods support this. If you follow the above documentation, users can easy_install, pip install etc. as their system allows.

For an example in the wild, see https://github.com/django/django/blob/master/setup.py. There is a lot of configuration at the top of the file, but the important bit is at the bottom, where you can see

setup(
    ...
    scripts = ['django/bin/django-admin.py'],
    ...
)

This sets up a django-admin.py command for users that install the django package. Once they install, they can run django-admin.py arg1 arg2 ... from their command line.

Clueless
  • 3,984
  • 1
  • 20
  • 27
  • On osx this seems to put scripts in `/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin`, which is not in the PATH. – qed Oct 31 '14 at 15:06
0

I believe the typical way of doing this is to place the modules you want to run as scripts in a location such as /usr/local/bin that is in the PATH of the user. Include a shebang line so that you can call the script without specifying the interpreter and you should be fine.

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
  • But when the users install the package, it gets in their site-packages. So it'll be /some/path/site-packages/mypackage/submodule1.py. How can I get the scripts to appear in /usr/local/bin? Do the users have to copy it themselves as part of installation? That seems clunky –  Dec 23 '11 at 22:00