2016-12-22 52 views
-1

初學Python的學生在這裏(運行2.7)試圖理解函數和argparse ...有時在一起。我有一個主函數調用一個argparse函數,該函數有一個argparse命令行參數(-i/- input),它調用一個path_check函數,該函數驗證在輸入參數中傳遞的路徑。現在我不知道如何將驗證的輸入路徑返回到我的主函數,因爲path_check函數沒有在main中調用。也想知道是否有更好的方法來構建這個(不知道這裏的類是否合適)。如何從argparse函數調用的函數返回一個值爲主

#!/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

你有什麼不明白的?您將其定義爲參數,但在您調用它時不會傳遞任何參數。 – jonrsharpe

回答

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) 

語句,所以你看看你從解析器回來。

0

爲了澄清上述評論,您需要包括參數這裏

source = path_check(argument) 
0

當調用主函數,如果你想傳遞一些變量,你需要插入他們在括號中。

function(Variable1, Variable2,) 

並且不要忘記把它們放在函數本身接受變量。要將變量返回給主函數,只需在函數的末尾執行一次返回VariableName,並將其添加到main中的調用前面,然後再加上=符號。

例如:

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

function1(x) 
    ReturnVariable = x * 2 
    return ReturnVariable 
相關問題