Skip to content

Instantly share code, notes, and snippets.

@brantfaircloth
Created December 7, 2011 16:47
Show Gist options
  • Save brantfaircloth/1443543 to your computer and use it in GitHub Desktop.
Save brantfaircloth/1443543 to your computer and use it in GitHub Desktop.
Some cool argparse stuff
class FullPaths(argparse.Action):
"""Expand user- and relative-paths"""
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values)))
def is_dir(dirname):
"""Checks if a path is an actual directory"""
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname
def get_args():
"""Get CLI arguments and options"""
parser = argparse.ArgumentParser(description="""do something""")
parser.add_argument('alignments', help="The folder of alignments",
action=FullPaths, type=is_dir)
@brentp
Copy link

brentp commented Dec 7, 2011

awesome, I gotta start using that stuff.

@canteroalejandro
Copy link

great.!!

@qiang-han
Copy link

cool~~

@hihellobolke
Copy link

Thank you! Useful!

@qgicup
Copy link

qgicup commented May 5, 2018

thanks!

@soungalo
Copy link

soungalo commented Jun 9, 2018

Thanks!

@harsilspatel
Copy link

The Class FullPaths can be removed and line 12 can be modified as
return os.path.abspath(os.path.realpath(os.path.expanduser(dirname)))

Consider using realpath to remove symbolic links.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment