检查空参数Python

时间:2017-11-26 07:31:20

标签: python sys

我的程序中有两个参数问题,第一个问题是如果没有参数传递给程序我正在尝试打印错误而且我试图改为使用-n代表“没有参数”实际上不必传递任何参数来将文件加载到程序中,我希望它只是像python3 program.py file file2 file3那样运行而不是使用python3 -n file file2 file3等。我已经注释掉了什么如果参数只是程序文件[0]退出

,我试图检查参数
def main():

    script = sys.argv[0]
    action = sys.argv[1]
    noargfile = sys.argv[1:]
    filenames = sys.argv[2:]
    OutContent = filenames or noargfile

    #Load files with arguments -d & --default
    print("Loading Files....", sys.argv[1:])

    for arg in filenames:
        try:
            myfile = open(arg, "r")
            fileContent = myfile.readlines()
            myfile.close()
            OutContent = OutContent + fileContent

            #if len(sys.argv) == script:
                #print("No Argument")
                #sys.exit(0)

            if action == '--default':
                counter = 0 # set a counter to 0 
                for line in OutContent: #for each line in load if the " 200 " is found add 1 to the counter and repeat until done. 
                    if re.findall(r"\s\b200\b\s", line):
                        counter += 1
                print("\nTotal of (Status Code) 200 request:", counter)
            elif action == '-d':
                counter = 0 # set a counter to 0 
                for line in OutContent: #for each line in load if the " 200 " is found add 1 to the counter and repeat until done. 
                    if re.findall(r"\s\b200\b\s", line):
                        counter += 1
                print("\nTotal of (Status Code) 200 request:", counter)
            elif action == '-n':
                menu(arg, OutContent)
        except OSError:
           print("File could not be opened " + filenames)

if __name__ == "__main__":
    main()

我的索引超出范围错误,我不明白为什么

File "program.py", line 161, in main
    action = sys.argv[1]
IndexError: list index out of range

2 个答案:

答案 0 :(得分:0)

将此添加为函数main中的第一行:

if len(sys.argv)==1: sys.exit("error here")

答案 1 :(得分:0)

当已经有非常好的参数解析时,你不应该自己进行参数解析(pypy上可能有100个)

这个小例子使用argparse模块。它需要n个文件并将其存储为变量files

中的字符串列表
import argparse

parser = argparse.ArgumentParser(description='Load some files')
parser.add_argument('-f','--files', dest='files', nargs='+', help='<Required> Set flag', required=True)


args = parser.parse_args()
print args.files

<强>用法:

python myscript -f test1.txt test2.txt test3.txt

以下是有关如何添加更多功能的详细信息,例如help页面或制作required|optional字段。 https://docs.python.org/2/library/argparse.html