Created
August 26, 2019 18:24
-
-
Save rcassani/a9754243421a29080fc6c14e2023a69f to your computer and use it in GitHub Desktop.
Pass arguments to Python code
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 | |
parser = argparse.ArgumentParser() | |
# Positional argument | |
parser.add_argument('echo', help='Response text') | |
# Optional arguments | |
parser.add_argument('--value', type=int, default=0) | |
parser.add_argument('--flag', action='store_true', help='Flag, true if present') | |
args = parser.parse_args() | |
print(args.echo) | |
print(args.value) | |
if args.flag: | |
print('Flag is here') | |
# Call as: | |
# $ python example_argparse.py abc | |
# Response | |
# abc | |
# Call as: | |
# $ python example_argparse.py abc --value=123 --flag | |
# Response | |
# abc | |
# 123 | |
# Flag is here | |
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
# Simplest way | |
import sys | |
print(str(sys.argv[1])) # | |
# Call in the terminal as: | |
# $ python simple_arguments.py 123 | |
# Reponse: | |
# 123 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment