Last active
September 28, 2017 12:28
-
-
Save drorata/1fa68b477d94aea5d37e87aa56e09295 to your computer and use it in GitHub Desktop.
Problem with 2nd-dependent option using click
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
""" | |
Following on the answer: https://stackoverflow.com/a/46451650/671013 | |
Fix of version https://gist.github.com/drorata/1fa68b477d94aea5d37e87aa56e09295/6678ad2056edc60ee77a4e986c626f5dcb662a2a | |
""" | |
import click | |
class OptionRequiredIf(click.Option): | |
def full_process_value(self, ctx, value): | |
value = super(OptionRequiredIf, self).full_process_value(ctx, value) | |
if value is None and ctx.params['output'] == 'file': | |
msg = 'Required if --output=file' | |
raise click.MissingParameter(ctx=ctx, param=self, message=msg) | |
return value | |
@click.command() | |
@click.option('--output', | |
type=click.Choice(['stdout', 'file']), default='stdout') | |
@click.option('--filename', type=click.STRING, cls=OptionRequiredIf) | |
def main(output, filename): | |
print("output: " + output) | |
if output == 'file': | |
if filename is None: | |
print("filename must be provided!") | |
else: | |
print("filename: " + str(filename)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment