Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Import And Initialize Argparse After if __name__ == '__main__'?

If I am using argparse and an if __name__ == '__main__' test in a script that I would also like to use as a module, should I import argparse under that test and then initialize it? None of the style guides I have found mention using argparse in scripts and many examples of argparse scripting do not use the 'if name' test or use it differently. Here is what I have been going with so far:

#! /usr/bin/env python

def main(name):
    print('Hello, %s!' % name)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description = 'Say hello')
    parser.add_argument('name', help='your name, enter it')
    args = parser.parse_args()

    main(args.name)

Should I import argparse with my other modules at the top and configure it in the body of the script instead?

like image 425
Daniel Avatar asked Jan 15 '15 05:01

Daniel


People also ask

What is import Argparse in Python?

argparse is the “recommended command-line parsing module in the Python standard library.” It's what you use to get command line arguments into your program.

How do you add arguments in Argparse?

To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required . The name is exactly what it sounds like — the name of the command line field.

How do you create an argument parser in Python?

# construct the argument parser and parse the arguments ap = argparse. ArgumentParser() ap. add_argument("-d", "--dataset", required=True, help="Path to the directory of indexed images") ap. add_argument("-f", "--features-db", required=True, help="Path to the features database") ap.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.


2 Answers

I would put the import at the top, but leave the code that uses it inside the if __name__ block:

import argparse

# other code. . .

def main(name):
    print('Hello, %s!' % name)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Say hello')
    parser.add_argument('name', help='your name, enter it')
    args = parser.parse_args()

    main(args.name)

Putting the imports at the top clarifies what modules your module uses. Importing argpase even when you don't use it will have negligible performance impact.

like image 135
BrenBarn Avatar answered Oct 24 '22 07:10

BrenBarn


It's fine to put the import argparse within the if __name__ == '__main__' block if argparse is only referred to within that block. Obviously the code within that block won't run if your module is imported by another module, so that module would have to provide its own argument for main (possibly using its own instance of ArgumentParser).

like image 20
101 Avatar answered Oct 24 '22 07:10

101