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:
- On linux systems, using
#!/usr/bin/env python
invokes the environment’s python run-time rather than someusr/bin
as some systems may be different. - 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.
- 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. - 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. - Exit cleanly with
sys.exit(main())
. - 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#!/usr/bin/env python """ Description of script """ from sys import exit, stderr from argparse import ArgumentParser class CommandlineParser(ArgumentParser): """Enhanced argument parser for command line""" def __init__(self): super(CommandlineParser, self).__init__() self.description = __doc__ def error(self, message): self.print_help() exit(2) def main(): """Main""" parser = CommandlineParser() parser.add_argument('-o', '-optional_flag', help="Some optional argument") parser.add_argument('positional', help="Some positional argument") args = parser.parse_args() if __name__ == "__main__": exit(main()) |