Created
October 31, 2014 14:52
-
-
Save andrelaszlo/2e0e9c8d7dc14a759323 to your computer and use it in GitHub Desktop.
Incomplete example function that lets a user fill out the parameters for an ArgumentParser interactively
This file contains hidden or 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
def run_interactive(parser): | |
"""Inspect the argument parser and let the user decide on values for | |
all parameters interactively. | |
""" | |
args = [] | |
print "You are running this script in interactive mode. " + \ | |
"Press C-d to abort. Run with --help to see more options." | |
try: | |
for action in parser._actions: | |
store = action.option_strings[-1] | |
if action.type == int: | |
prompt = "{} [{}]\n".format(action.help, action.default) | |
val = raw_input(prompt) | |
if val: | |
args += [store, val] | |
elif type(action.default) == bool: | |
if action.default: | |
default = "y" | |
choices = "[Y/n]" | |
else: | |
default = "n" | |
choices = "[y/N]" | |
prompt = "{} {}\n".format(action.help, choices) | |
val = raw_input(prompt).lower() | |
if val and val != default: | |
args.append(store) | |
except EOFError: | |
print "\nAborting...\n" | |
sys.exit(1) | |
cmd = ' '.join([__file__] + args) | |
print "Command is:" | |
print cmd | |
print "Do you want to run this command? [y/n]" | |
while True: | |
run = sys.stdin.readline().strip().lower() | |
if run == "y": | |
print "running ", cmd | |
args = parser.parse_args(passed_args) | |
return args | |
elif run == "n": | |
sys.exit(1) | |
else: | |
print "y(es) or n(o) please" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment