Request for feedback on my first Python program

Skip Montanaro skip at pobox.com
Fri May 30 13:00:32 EDT 2003


    >> >def main():
    >> >    if len(sys.argv) != 2:
    >> >        usage(sys.argv[0])
    >> >    f = open(sys.argv[1], "r")
    >> 
    >> This is generally a Bad Idea; your functions should be generic and
    >> sys.argv handling should be done under "if __name__=='__main__':".

    Peter> I don't entirely agree.  Although I can see calling main as 

    Peter>    if __name__ == '__main__':
    Peter>        main(sys.argv[1:]) 

    Peter> anything more than this seems less readable.  

One pattern I picked up from some of the scripts in the Python distribution
is to extract the program name at module scope, refer to it in the
docstring, and substitute it in the usage() function.  Of course, main()
gets called with sys.argv[1:] as its sole parameter.  For an example, look
at Tools/scripts/db2pickle.py in the Python distribution:

    http://tinyurl.com/d2a3

Skip





More information about the Python-list mailing list