Skip to content

Instantly share code, notes, and snippets.

@rcassani
Created August 26, 2019 18:24
Show Gist options
  • Save rcassani/a9754243421a29080fc6c14e2023a69f to your computer and use it in GitHub Desktop.
Save rcassani/a9754243421a29080fc6c14e2023a69f to your computer and use it in GitHub Desktop.
Pass arguments to Python code
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
# 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