Skip to content

Instantly share code, notes, and snippets.

@brantfaircloth
Created September 30, 2011 00:27
Show Gist options
  • Save brantfaircloth/1252339 to your computer and use it in GitHub Desktop.
Save brantfaircloth/1252339 to your computer and use it in GitHub Desktop.
Convert paths to full paths (argparse)
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 get_args():
parser = argparse.ArgumentParser(description='Something smart here')
parser.add_argument('my_conf', help='The configuration file for the db', action = FullPaths)
return parser.parse_args()
@brantfaircloth
Copy link
Author

I annoyingly created this gist as Anonymous.

@thehesiod
Copy link

Implementation for appends:

class FullPathsAppend(argparse._AppendAction):
    def __call__(self, parser, namespace, values, option_string=None):
        items = copy.copy(argparse._ensure_value(namespace, self.dest, []))
        items = [os.path.abspath(os.path.expanduser(item)) for item in items]
        items.append(values)
        setattr(namespace, self.dest, items)

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