[Tutor] Read from large text file, parse, find string, print string + line number to second text file.

Steven D'Aprano steve at pearwood.info
Sat Feb 2 02:00:09 CET 2013


On 02/02/13 08:24, Scurvy Scott wrote:
> One last question on this topic..
>
> I'd like to call the files and the string form the command line like
>
> Python whatever.py STRINGTOSEARCH NEWFILE FILETOOPEN
>
> My understanding is that it would be accomplished as such
>
> import sys
>
> myString = sys.argv[1]
> filetoopen = sys.argv[2]
> newfile = sys.argv[3]
>
>
> ETC ETC CODE HERE
>
> Is this correct/pythonic? Is there a more recommended way? Am I retarded?



Best practice is to check if your program is being run as a script before doing anything. That way you can still import the module for testing or similar:


def main(mystring, infile, outfile):
    # do stuff here


if __name__ == '__main__':
    # Running as a script.
    import sys
    mystring = sys.argv[1]
    infile = sys.argv[2]
    outfile = sys.argv[3]
    main(mystring, infile, outfile)



Best practice for scripts (not just Python scripts, but *any* script) is to provide help when asked. Insert this after the "import sys" line, before you start processing:

    if '-h' in sys.argv or '--help' in sys.argv:
        print(help_text)
        sys.exit()



If your argument processing is more complicated that above, you should use one of the three argument parsing modules that Python provides:

http://docs.python.org/2/library/getopt.html
http://docs.python.org/2/library/optparse.html (deprecated -- do not use this for new code)
http://docs.python.org/2/library/argparse.html


getopt is (in my opinion) the simplest to get started, but the weakest.

There are also third-party argument parsers that you could use. Here's one which I have never used but am intrigued by:

http://docopt.org/



-- 
Steven


More information about the Tutor mailing list