Skip to content

Instantly share code, notes, and snippets.

@drorata
Last active September 28, 2017 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drorata/1fa68b477d94aea5d37e87aa56e09295 to your computer and use it in GitHub Desktop.
Save drorata/1fa68b477d94aea5d37e87aa56e09295 to your computer and use it in GitHub Desktop.
Problem with 2nd-dependent option using click
"""
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