如何从argparse函数调用的函数向main返回值

时间:2016-12-22 22:06:56

标签: python python-2.7 function argparse

新手Python学生在这里(运行2.7)试图理解函数和argparse ......有时候在一起。

我有一个调用argparse函数的main函数,该函数有一个调用path_check函数的argparse命令行参数(-i / - input),该函数验证输入参数中传递的路径。现在我不知道如何将经过验证的输入路径返回给我的main函数,因为在main中没有调用path_check函数。还想知道是否有更好的方法来构建它(不确定一个类是否合适)。

#!/bin/user/python

import os,sys
import argparse  

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input",help="source directory",
        required=True,type=path_check)
    args = parser.parse_args()

def path_check(arg):
    if not os.path.exists(arg):
        print("Directory does not exist. Please provide a valid path")
    else:
        return arg

def main():
    '''
    This main script analyzes the source folder and redirects
    files to the appropriate parsing module
    '''
    parse_args()
    source = path_check() # This is the problem area

if __name__ == "__main__": main()

收到的错误是

TypeError: path_check() takes exactly 1 argument (0 given)

编辑: 以下是更正后的代码,如果它对任何人都有帮助。我需要在argparse参数中添加一个描述,这样我就可以调用参数的值,然后我就可以返回了。

 #!/bin/user/python

import os,sys
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input",help="source directory",
        dest="input",required=True,type=path_check)

    args = parser.parse_args()
    return args.input

def path_check(arg):
    if not os.path.exists(arg):
        print("Directory does not exist. Please provide a valid path")
    else:
        return arg

def main():
    '''
    This main script analyzes the source folder and redirects
    files to the appropriate parsing module
    '''
    source = parse_args()

if __name__ == "__main__": main()

3 个答案:

答案 0 :(得分:2)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input",help="source directory",
        required=True,type=path_check)
    args = parser.parse_args()
    return args     # <====

def main():
    '''
    This main script analyzes the source folder and redirects
    files to the appropriate parsing module
    '''
    args = parse_args()      # <===
    source = path_check(args.input) # <===

parse_args函数必须将args变量返回main。然后main必须将其input属性传递给path_check

args.input将是您在命令行中提供的字符串。

args是一个简单的argparse.Namespace对象,其属性对应于您在parser中定义的每个参数。其中一些属性的值可能为None,具体取决于默认值的处理方式。

在调试过程中,最好包含一个

print(args)

语句,因此您可以看到从解析器中获得的内容。

答案 1 :(得分:0)

为澄清上述说明,您需要在此处加入参数

source = path_check(argument)

答案 2 :(得分:0)

在main中调用函数时,如果要传递某个变量,则需要将它们插入括号中。

function(Variable1, Variable2,)

并且不要忘记将它们放在函数本身上以接受变量。要将变量返回到main函数,只需在函数末尾执行一个返回VariableName,并将其添加到main中的调用前面,然后是=符号。

示例:

main()
   x = 1
   ReturnVariable = function1(x)

function1(x)
   ReturnVariable = x * 2
   return ReturnVariable