CLI Python Script Template

Python has a unique way of executing and there a number of ways to wrap and twist the main entry point, catch errors, and provide for command line arguments. If a script is to be used at the command line, there are a few niceties that can be employed to make the user’s life easier.

Here are some good practices:

  1. On linux systems, using #!/usr/bin/env python invokes the environment’s python run-time rather than some usr/bin
    as some systems may be different.
  2. Provide a clear description at the head of the script, in python this is handled special as the __doc__ variable and can be utilized for help notations.
  3. When importing, utilize the from module import function
    . In most cases, there is little to gain loading entire modules and explicitly declaring functions helps organize the imports.
  4. When providing a main entry point, utilize the if __name__ == “__main__”:
    declaration and create a seperate main function. This helps to clearly define the program entry and avoid executing code when imported from other modules. If needed, an addtional try, except block in this location can help intercept errors arising from Python itself.
  5. Exit cleanly with sys.exit(main())
  6. Utilize argparse or argh modules to help organize arguments. Argparse comes standard and can be used in lieu of argh if additional modules are not desired.

Example Template

Comments are closed.



  • slide
  • slide
  • slide
  • slide
Casino Canada Online