[Tutor] Read from large text file, parse, find string, print string + line number to second text file.
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
> filetoopen = sys.argv
> newfile = sys.argv
> 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.
mystring = sys.argv
infile = sys.argv
outfile = sys.argv
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:
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/optparse.html (deprecated -- do not use this for new code)
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:
More information about the Tutor