Python error: the following arguments are required

Aliaksei Laurynovich picture Aliaksei Laurynovich · Jul 4, 2018 · Viewed 38.7k times · Source

I have the Python script that works well when executing it via command line. What I'm trying to do is to import this script to another python file and run it from there.

The problem is that the initial script requires arguments. They are defined as follows:

#file one.py
def main(*args):
   import argparse

   parser = argparse.ArgumentParser(description='MyApp')
   parser.add_argument('-o','--output',dest='output', help='Output file image', default='output.png')
   parser.add_argument('files', metavar='IMAGE', nargs='+', help='Input image file(s)')

   a = parser.parse_args()

I imported this script to another file and passed arguments:

#file two.py
import one
one.main('-o file.png', 'image1.png', 'image2.png')

But although I defined input images as arguments, I still got the following error:

usage: two.py [-h] [-o OUTPUT] 
          IMAGE [IMAGE ...]
two.py: error: the following arguments are required: IMAGE

Answer

Hans picture Hans · Jul 4, 2018

When calling argparse with arguments not from sys.argv you've got to call it with

parser.parse_args(args)

instead of just

parser.parse_args()