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
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()
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:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With