wiki:ScriptsBestPractice

Scripts Best Practice

I suggest using the following recipe to facilitate the inclusion of python scripts inside PythonEggs:

import sys

def main(args=None):
    if not args:
        args = sys.argv[1:]
    
    # Your code here
    ...

if __name__ == '__main__':
    main()

The advantage of this approach is that the script will support 3 interfaces:

  1. Normal execution on the command line.
  2. Importing from python and execution with myscript.main(args). This will work if the script is in an egg.
  3. Definition of an egg entry point within setuptools.setup() as follows:
      setup(
        entry_points = {
            'console_scripts': [
                'myscript = ndg.some_package.scripts:main',
            ],
        }
      )
    

Note main() must be callable with either no arguments, indicating the script gets arguments from sys.argv, or with a single argument: a list of strings.