Adrian P. Adrian P. - 2 months ago 20x
Python Question

How to use python argparse with args other than sys.argv?

I've been all over the documentation and it seems like there's no way to do it, but:

Is there a way to use argparse with any list of strings, instead of only with sys.argv?

Here's my problem: I have a program which looks something like this:

# This file is
import argparse

def main(argv):
parser = argparse.ArgumentParser()
# Do some argument parsing

if __name__ == '__main__':

This works fine when this program is called straight from the command line. However, I have another python script which runs batch versions of this script with different commandline arguments, which I'm using like this:

import program1

arguments = ['arg1', 'arg2', 'arg3']

I still want to be able to parse the arguments, but argparse automatically defaults to using sys.argv instead of the arguments that I give it. Is there a way to pass in the argument list instead of using sys.argv?


You can pass a list of strings to parse_args:

parser.parse_args(['--foo', 'FOO'])