本文介绍了Python 错误:需要以下参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 Python 脚本在通过命令行执行时运行良好.我想要做的是将此脚本导入另一个 python 文件并从那里运行它.
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
推荐答案
当使用不是来自 sys.argv
的参数调用 argparse
时,你必须使用
When calling argparse
with arguments not from sys.argv
you've got to call it with
parser.parse_args(args)
而不仅仅是
parser.parse_args()
这篇关于Python 错误:需要以下参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!