Skip to content

Instantly share code, notes, and snippets.

@cfh294
Last active May 24, 2019 18:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cfh294/9b21b481fc19838b57583e4ab7cad671 to your computer and use it in GitHub Desktop.
Save cfh294/9b21b481fc19838b57583e4ab7cad671 to your computer and use it in GitHub Desktop.
Python decorator example for passing command line arguments to a function
from utils import with_cmd_line_args
@with_cmd_line_args
def main(cmd_line):
""" Write the contents of one file to another """
with open(cmd_line.input_file) as in_file:
with open(cmd_line.output_file, "w") as out_file:
for line in in_file:
out_file.write(line)
if __name__ == "__main__":
main()
import argparse
def with_cmd_line_args(f):
""" Decorator that passes along input file path and output file path
command line arguments to a decorated function """
def wrapper(*args, **kwargs):
parser = argparse.ArgumentParser()
# define all command line arguments, we'll just do two file paths
parser.add_argument("-i", "--input-file", type=str, help="An input file path")
parser.add_argument("-o", "--output-file", type=str, help="An output file path")
# return the wrapped function with the parsed arguments
return f(parser.parse_args(), *args, **kwargs)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment