Skip to content

Instantly share code, notes, and snippets.

@rsyring
Created April 5, 2017 14:31
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 rsyring/cd5a9cc3e7c825bc0569c94fd045be67 to your computer and use it in GitHub Desktop.
Save rsyring/cd5a9cc3e7c825bc0569c94fd045be67 to your computer and use it in GitHub Desktop.
random string script using Click library
#!/usr/bin/env python
from __future__ import print_function
import random
import click
@click.command()
@click.argument('length', type=click.INT)
@click.option('--chartype', type=click.Choice(['alphanumeric', 'alpha', 'numeric', 'all']),
default='all')
@click.option('--case', type=click.Choice(['both', 'upper', 'lower']), default='both')
@click.option('--unique', is_flag=True)
def random_cli(length, chartype, case, unique):
"""Return random string of chars"""
print(randchars(length, chartype=chartype, alphacase=case, unique=unique))
def randchars(n=12, chartype='alphanumeric', alphacase='both', unique=False):
if alphacase == 'both':
alphalist = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
elif alphacase == 'upper':
alphalist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
elif alphacase == 'lower':
alphalist = 'abcdefghijklmnopqrstuvwxyz'
else:
raise ValueError('alphacase "%s" not recognized' % alphacase)
if chartype == 'alphanumeric':
charlist = alphalist + '0123456789'
elif chartype == 'alpha':
charlist = alphalist
elif chartype == 'numeric':
charlist = '0123456789'
elif chartype == 'all':
charlist = alphalist + '0123456789' + """`~!@#$%^&*()_-+={}|[]\:";'<>?,./"""
else:
raise ValueError('chartype "%s" not recognized' % chartype)
retval = []
for _ in range(n):
chosen = random.choice(charlist)
if unique:
charlist = charlist.replace(chosen, '')
retval.append(chosen)
return ''.join(retval)
if __name__ == '__main__':
random_cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment