Last active
May 24, 2019 18:56
-
-
Save cfh294/9b21b481fc19838b57583e4ab7cad671 to your computer and use it in GitHub Desktop.
Python decorator example for passing command line arguments to a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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