Skip to content

Instantly share code, notes, and snippets.

@sumanthkumarc
Created May 4, 2021 04:48
Show Gist options
  • Save sumanthkumarc/62223aa0aa6ad23d2bf1026e2944debf to your computer and use it in GitHub Desktop.
Save sumanthkumarc/62223aa0aa6ad23d2bf1026e2944debf to your computer and use it in GitHub Desktop.
custom arg parser
import CustomArgumentParser
from io import StringIO
import sys
parser = CustomArgumentParser(description='Process my command')
parser.add_argument('foo', type=str, help='Magic of foo')
parser.add_argument(
'--bar',
action='store',
required=False,
type=str,
default='baz',
help='Bar optional param',
)
# hack to capture stdout for argparse help/error and send it to
# client.
sys.stdout = result = StringIO()
error_text = ''
try:
cmd_params = parser.parse_args(command.split())
except:
# Restore the stdout stream for future code.
sys.stdout = sys.__stdout__
error_text = result.getvalue()
# Use the below format to return message for proper formatting.
return {
"statusCode": "200",
"body": json.dumps({
"text": error_text
}),
"headers": {
"Content-Type": "application/json;charset=utf-8",
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment