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.

Answer from BrenBarn on Stack Overflow
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
Source code: Lib/argparse.py Tutorial: This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial. The arg...
🌐
Reddit
reddit.com › r/learnpython › where to put argparse?
r/learnpython on Reddit: Where to put argparse?
July 17, 2015 -

I have some across three ways I've seen argparse placed in applications. They go roughly like this...

First way:

def main(some_arguments):
    do_something(some_arguments)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='This.')
    yada yada
    main(some_arguments) 

Second way:

def main():
    parser = argparse.ArgumentParser(description='This.')    
    yada yada

if __name__ == '__main__':
    main()

And a third way:

def parse_args():
    parser = argparse.ArgumentParser(description='This.')
    yada yada
    return something

def main():
    args = parse_args()

if __name__ == '__main__':
    main()

Is there a preferred way to do it? Are they contingent on some factors that are not immediately apparent to me? Or are they all equivalent and just a matter of taste?

Top answer
1 of 5
7

Personally, I think the first way makes the most sense, or a combination of the first and third.

Something like:

def main(some_args):
    do_stuff...

def parse_arguments():
    argument_parse_code
    return arguments

if __name__ == '__main__':
    arguments = parse_arguments()
    main(*arguments)

My thinking: By defining main with args, you can then import that script elsewhere and call the main function with arguments from the calling script.

By definite the argument parsing in a separate script, you can test more easily, and write unit tests to verify functionality.

2 of 5
3

I think it's a matter of taste, style and designing your code "well".

While not giving a direct response, here's what I like to do - this works for simple utilities, but doesn't change that much for more complicated stuff:

  • usually you have a function/object that does all the work, or at least serves as an entry point to your app logic

  • having that in mind, let main() do two things: call a configure() function that returns parsed args; call do_stuff(arg1, arg2, arg3) using parsed args

  • do_stuff() doesn't need to depend on some arbitrary args object - rather, it receives explicit arguments

Profits:

  • main() servers as a dispatcher, which makes it simple; you might have different logic depending on an argument, let main() dispatch it (there are cool options for complex stuff)

  • configure() is where all your commandline options live

  • do_stuff() is easy to test, easy to import into other projects which might not even have commandline arguments, perhaps you pull them from a DB or a config file?

🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
author, Tshepang Mbambo,. This tutorial is intended to be a gentle introduction to argparse, the recommended command-line parsing module in the Python standard library. Concepts: Let’s show the sor...
🌐
GitHub
gist.github.com › linuxluigi › 0613c2c699d16cb5e171b063c266c3ad
Python __main__.py parser example · GitHub
Python __main__.py parser example · Raw · __main__.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
DEV Community
dev.to › xowap › the-ultimate-python-main-18kn
The Ultimate Python main() - DEV Community
May 12, 2021 - Fortunately there is an easy solution to this: create a C-style main() function. #!/usr/bin/env python3 from argparse import ArgumentParser def main(): parser = ArgumentParser() parser.add_argument("-w", "--what", default="hello, world") args = parser.parse_args() print(args.what) if __name__ == "__main__": main()
🌐
Real Python
realpython.com › command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse – Real Python
December 14, 2024 - You’ll name each Python module according to its specific content or functionality. You can add a __main__.py module to any Python package if you want to make that package directly executable.
Find elsewhere
🌐
University College London
github-pages.ucl.ac.uk › rsd-engineeringcourse › ch04packaging › 02Argparse.html
Argparse
To add the capability to accept inputs from the command line we are going to use argparse. Rememer, what's under the if __name__ == "__main__": block is what's get executed when you run the file! ... %%writefile greeter.py #!/usr/bin/env python from argparse import ArgumentParser def greet(personal, family, title="", polite=False): greeting = "How do you do, " if polite else "Hey, " if title: greeting += f"{title} " greeting += f"{personal} {family}." return greeting if __name__ == "__main__": parser = ArgumentParser(description="Generate appropriate greetings") parser.add_argument('--title', '-t') parser.add_argument('--polite','-p', action="store_true") parser.add_argument('personal') parser.add_argument('family') arguments= parser.parse_args() message = greet(arguments.personal, arguments.family, arguments.title, arguments.polite) print(message)
🌐
Mouse Vs Python
blog.pythonlibrary.org › home › how to create a command-line application with argparse
How to Create a Command-line Application with argparse - Mouse Vs Python
May 19, 2022 - Before you learn how to use argparse, it’s good to know that there is another way to pass arguments to a Python script. You can pass any arguments to a Python script and access those arguments by using the sys module. To see how that works, create a file named sys_args.py and enter the following code into it: # sys_args.py import sys def main(): print('You passed the following arguments:') print(sys.argv) if __name__ == '__main__': main()
🌐
Reddit
reddit.com › r/learnpython › how to use argparse properly in the main function?
r/learnpython on Reddit: How to use Argparse properly in the main function?
March 11, 2024 - In other programming languages I would probably prefer dispatch tables but Python supports only one-line lambdas, so it limits the programmer. actions = { 'action_a': lambda: ...... , 'action_b': lambda: ...... , 'action_c': lambda: ...... , } More replies More replies ... I generally do the arg-parsing directly in main, but otherwise do what you've done.
🌐
Martin Thoma
martin-thoma.com › how-to-parse-command-line-arguments-in-python
How to parse command line arguments in Python · Martin Thoma
% arg) else: return arg def get_parser(): """Get parser object for script xy.py.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser( description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter ) parser.add_argument( "-f", "--file", dest="filename", type=lambda x: is_valid_file(parser, x), help="write report to FILE", metavar="FILE", ) parser.add_argument( "-n", dest="n", default=10, type=int, help="how many lines get printed" ) parser.add_argument( "-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout", ) return parser if __name__ == "__main__": args = get_parser().parse_args() Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.
Top answer
1 of 16
481

Here's the way I do it with argparse (with multiple args):

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

args will be a dictionary containing the arguments:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code here

In your case simply add only one argument.


Editor's note: The docs say this:

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

Use positional arguments instead, e.g. as shown in @mightypile's answer.

2 of 16
319

My understanding of the question is two-fold. First, the simplest possible argparse example. Of course, to be dead-simple, it's got to be a toy example, i.e. all overhead with little power, but it might get you started.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()

if args.a == 'magic.name':
    print('You nailed it!')

But this positional argument is now required. If you leave it out when invoking this program, you'll get an error about missing arguments. This leads me to the second part of the question. You seem to want a single optional argument without a named label (the --option labels). My suggestion would be to modify the code above as follows:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a", nargs='?')
args = parser.parse_args()

if args.a is None:
    print('I can tell that no argument was given and I can deal with that here.')
elif args.a == 'magic.name':
    print('You nailed it!')
else:
    print(args.a)

There may well be a more elegant solution, but this works and is minimalist.

Note: If you want a different default value instead of None, use the default parameter to .add_argument.

🌐
PythonTest
pythontest.com › testing-argparse-apps
Testing argparse Applications | PythonTest
November 16, 2023 - Here’s a few good things to do with all CLI applications. Have a main() function called by a if __name__ == "__main__" block that either contains all of your logic, or calls other functions.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › argparse.py
cpython/Lib/argparse.py at main · python/cpython
self._theme = get_theme(force_color=True).argparse · self._decolor = decolor · else: self._theme = get_theme(force_no_color=True).argparse · self._decolor = _identity · · # =============================== # Section and indentation methods ·
Author   python
🌐
Python.org
discuss.python.org › python help
Argparse python - Python Help - Discussions on Python.org
August 13, 2024 - Hi Everyone, I need help fixing of this code: import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument(‘name’, help=‘Enter your name’) parser.add_argument(‘age’, type=int, help=‘Enter your age’) args = parser.parse_args() if type(args.name) == int: print('Argument can't be a number') print(f'Hello, {args.name}!') if args.age: print(f'You are {args.age} old.') if name == ‘main’: main() Code have to check and end work if: Name is the second agument, ...
🌐
DEV Community
dev.to › taikedz › ive-parked-my-side-projects-3o62
Argument parsing and subparsers in Python - DEV Community
October 27, 2022 - #!/usr/bin/env python3 import argparse # Some fictional machine API - split the logic into modules import power import engine def parse_app_args(args=None): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="cmd") # Farming out the subparser definitionss to their respective modules # So each module can define its parsing options itself power.setup_args(subparsers) engine.setup_args(subparsers) return parser.parse_args(args) def main(): parsed_args = parse_app_args() # We make a point of moving subcommand implementations to their own files, # to decluttrer this main file command_map = { "power": power.run, "engine": engine.run, } # Because the parser will only accept values for the named subparser, # we can consider the check has already been done for us :-) command_map[parsed_args.cmd](parsed_args) if __name__ == "__main__": main()
🌐
Patrick Emonts
patrickemonts.com › post › argparse
Argparse -- or how to tell your program what you actually want | Patrick Emonts
August 27, 2024 - As tradition demands, we start by importing the package import argparse. Since commandline arguments are only used when the program is called directly as an executable, we can move this import to the execution guard if __name__ == "__main__:" (see full code below).
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-argparse-to-write-command-line-programs-in-python
How To Use argparse to Write Command-Line Programs in Python | DigitalOcean
March 11, 2021 - First, you import the argparse module to make it available for use in your program. Next, you create a dictionary data structure tank_to_fish that maps tank names (like tank_a and tank_b) to string descriptions of fish held in those tanks. You instantiate an instance of the ArgumentParser class and bind it to the parser variable. You can think of parser as the main ...
🌐
Cherry Servers
cherryservers.com › home › blog › cloud computing › how to use argparse in python to build command-line interfaces
How to Use argparse in Python | Cherry Servers
February 10, 2026 - However, you should have a Python ... the Python standard library rather than as a separate package in older versions. Run the following command to install argparse. ... To start creating CLIs using argparse, we need to follow the below steps. Import argparse using the below statement to start using it. ... Next, you have to create an ArgumentParser object. ArgumentParser objects are used for two main ...
🌐
Medium
kameshdubey.medium.com › argparse-module-python-a539f0da4d99
Python Argparse Module Tutorial | by Kamesh Dubey | Medium
September 6, 2023 - import argparse if __name__ == "__main__": # This line initializes the parser object from ArgumentParser class parser = argparse.ArgumentParser() # Two types of argument that argparser supports # 1. Positional and # 2.