Python错误:需要以下参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51172076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python error: the following arguments are required
提问by Aliaksei Laurynovich
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.
我有通过命令行执行它时运行良好的 Python 脚本。我想要做的是将此脚本导入另一个 python 文件并从那里运行它。
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
回答by Hans
When calling argparse
with arguments not from sys.argv
you've got to call it with
当argparse
用不是来自的参数调用时,sys.argv
你必须用
parser.parse_args(args)
instead of just
而不仅仅是
parser.parse_args()