yeleek
yeleek

Reputation: 309

Returning Namespace value

Using argparse in a function i want to be able to return the argument back to main for use elsewhere in the script.

When trying to use 'x' within the verify_args() function it works (all be it I have the namespace to contend with). I cannot though successfully return 'x' (or the value of 'x') back to the main().

#!/usr/bin/env python3


import argparse

def verify_args():
    parser = argparse.ArgumentParser(description='Compare files recursively.')
    parser.add_argument('path', metavar='P', help='Location to begin file comparison from.')
    x=parser.parse_args()

def main():
    verify_args()


if __name__ == '__main__':
    main()

I would like to be able to return the argument (wthout the namespace) from verify_args back to main. Any ideas please?

Upvotes: 0

Views: 117

Answers (1)

PySaad
PySaad

Reputation: 1069

You need to return

Refer below -

#!/usr/bin/env python3

import argparse

def verify_args():
    parser = argparse.ArgumentParser(description='Compare files recursively.')
    parser.add_argument('--path', metavar='-p', help='Location to begin file comparison from.')
    return parser.parse_args()

def main():
    args = verify_args()
    file_path = args.path 
    print (file_path)    #prints your path which you passed


if __name__ == '__main__':
    main()

Reference

https://docs.python.org/3/howto/argparse.html

Upvotes: 2

Related Questions