Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python尝试除外_Python - Fatal编程技术网

python尝试除外

python尝试除外,python,Python,我有以下代码: #! /usr/bin/python import sys, string def findAll(search, fh): count = 0 for line in fh: count += 1 if line.find(search) != -1: print "%3d: %s"%(count, line.rstrip()) return count search = raw_input("

我有以下代码:

#! /usr/bin/python
import sys, string

def findAll(search, fh):
    count = 0
    for line in fh:
        count += 1
        if line.find(search) != -1:
            print "%3d: %s"%(count, line.rstrip())
    return count

search = raw_input("Enter string to be found: ")
filename = raw_input("Enter filename: ")
fh = open(filename, "rU")
findAll(search, fh)
我的教授建议我写这段代码并加入“改进的用法”。
我不知道该怎么做,但她建议这样做

  • 我通过注释掉
    raw_input()
    语句来修改程序,然后添加语句以检查是否使用少于2个参数调用程序,如果是,则添加到
    print'用法:findstring.py string filename
    。代码获取字符串并在文件中定位它们

  • 我使用
    sys.argv
    中的
    filename
    命令行参数打开文件,并准备发生输入/输出错误(IOError)。然后,要使用
    尝试使用except
    块来编码打开文件是否有效的操作。
    如果打开失败,I
    print”错误:无法打开findstring.py
    ,其中
    findstring.py
    也是文本文件的首选项


  • 老实说。。。我忙着写下她的建议,以至于我不知道如何做她推荐的许多事情。有人能帮助改进这个代码吗?我很困惑,我不知道该怎么做。我的教授说代码可以运行,但我不知道如何修改它

    要提高使用率,请尝试使用argparse模块。它使使用命令行选项更容易

    上述链接中的代码示例如下所示:

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print args.accumulate(args.integers)
    
    现在,考虑如何修改此示例以完成作业。您需要使用字符串(搜索词、文件名)而不是整数


    对于try/except块,请记住处理错误的代码位于块的except部分。也就是说,你可以考虑在Bube块中显示一个错误信息。

    如果你把你的叙述分解成几个问题,你会更有可能得到答案。如果你的教授困惑了你,你应该请你的教授澄清。