Python error: the following arguments are required
Asked Answered
H

2

10

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
Heall answered 4/7, 2018 at 11:0 Comment(2)
Beside the point, but '-o file.png' should either be separated with an equals sign: '-o=file.png', or two separate strings: '-o', 'file.png', or not have a space: '-ofile.png' (which is hard to read IMHO).Evansville
you need to add -- prefix before the files parameter.Cybil
A
14

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()
Arleyne answered 4/7, 2018 at 11:9 Comment(0)
M
3

If your MAIN isn't a def / function you can simulate the args being passed in:

if __name__=='__main__':

    # Set up command-line arguments
    parser = ArgumentParser(description="Simple employee shift roster generator.")
    parser.add_argument("constraints_file", type=FileType('r'),
                        help="Configuration file containing staff constraints.")
    parser.add_argument("first_day", type=str,
                        help="Date of first day of roster (dd/mm/yy)")
    parser.add_argument("last_day", type=str,
                        help="Date of last day of roster (dd/mm/yy)") 

    #Simulate the args to be expected...   <--- SEE HERE!!!
    argv = ["",".\constraints.txt", "1/5/13", "1/6/13"]

    # Parse arguments
    args = parser.parse_args(argv[1:])
Musquash answered 9/12, 2020 at 4:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.