Python错误:以下参数是必需的 [英] Python error: the following arguments are required

查看:103
本文介绍了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错误:以下参数是必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆