初學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()
你有什麼不明白的?您將其定義爲參數,但在您調用它時不會傳遞任何參數。 – jonrsharpe