Skip to content

Instantly share code, notes, and snippets.

@beardedfoo
Created August 17, 2022 14:40
Show Gist options
  • Save beardedfoo/ace1bfb5c0ff16fd299b36ea67ee4440 to your computer and use it in GitHub Desktop.
Save beardedfoo/ace1bfb5c0ff16fd299b36ea67ee4440 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""A hello world in python using argparse"""
import argparse
import sys
def parse_args():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('name', help='The name of the entity to be greeted')
p.add_argument('--emoji', action='store_true', default=False,
help='Enables a hand wave emoji in the greeting')
p.add_argument('--language',
choices=['english', 'nederlands'],
default='english',
help='Sets the language for the greeting'
)
return p.parse_args()
def main():
args = parse_args()
if args.language == 'english':
greeting = 'Hello'
elif args.language == 'nederlands':
greeting = 'Hoi'
if args.emoji:
print(f'{greeting} {args.name} 👋')
else:
print(f'{greeting} {args.name}')
if __name__ == '__main__':
sys.exit(main())
@beardedfoo
Copy link
Author

$ ./hello.py
usage: hello.py [-h] [--emoji] [--language {english,nederlands}] name
hello.py: error: the following arguments are required: name
cyle@wse-server-1:~$ ./hello.py  --help
usage: hello.py [-h] [--emoji] [--language {english,nederlands}] name

A hello world in python using argparse

positional arguments:
  name                  The name of the entity to be greeted

optional arguments:
  -h, --help            show this help message and exit
  --emoji               Enables a hand wave emoji in the greeting
  --language {english,nederlands}
                        Sets the language for the greeting
                        
$ ./hello.py Person
Hello Person

$ ./hello.py Person --emoji
Hello Person 👋

$ ./hello.py Person --emoji --language nederlands
Hoi Person 👋

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment