optparse and strings

守給你的承諾、 提交于 2019-12-24 00:30:00

问题


Trying to learn how to use outparse. So here is the situation, I think I got my setup correct its just how to set my options is kinda... confusing me. Basically I just want to check my filename to see if there are specific strings.

For example:

    python script.py -f filename.txt -a hello simple

I want it to return something like...

    Reading filename.txt....
    The word, Hello, was found at: Line 10
    The word, simple, was found at: Line 15

Here is what I have so far, I just don't know how to set it up correctly. Sorry for asking silly questions :P. Thanks in advance.

Here is the code thus far:

    from optparse import OptionParser

    def main():

        usage = "useage: %prog [options] arg1 arg2"
        parser = OptionParser(usage)

        parser.add_option_group("-a", "--all", action="store", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")

        (options, args) = parser.parse_args()

        if len(args) != 1:
            parser.error("not enough number of arguments")

            #Not sure how to set the options...


    if __name__ == "__main__":
        main()

回答1:


You should use OptionParser.add_option()... add_option_group() isn't doing what you think it does... this is a complete example in the spirit of what you're after... note that --all relies on comma-separating the values... this makes it easier, instead of using space separation (which would require quoting the option values for --all.

Also note that you should check options.search_and and options.filename explicitly, instead of checking the length of args

from optparse import OptionParser

def main():
    usage = "useage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-a", "--all", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")
    parser.add_option("-f", "--file", type="string", dest="filename", help="Name of file")
    (options, args) = parser.parse_args()

    if (options.search_and is None) or (options.filename is None):
        parser.error("not enough number of arguments")

    words = options.search_and.split(',')
    lines = open(options.filename).readlines()
    for idx, line in enumerate(lines):
        for word in words:
            if word.lower() in line.lower():
                print "The word, %s, was found at: Line %s" % (word, idx + 1)

if __name__ == "__main__":
    main()

Using your same example, invoke the script with... python script.py -f filename.txt -a hello,simple



来源:https://stackoverflow.com/questions/7734462/optparse-and-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!