Passing parameters at the command line (New Python User)

Steven Bethard steven.bethard at gmail.com
Mon Sep 24 15:09:43 EDT 2007


cjt22 at bath.ac.uk wrote:
> Hi there. I just wondered whether anyone could recommend the correct
> way I should be passing command line parameters into my program. I am
> currently using the following code:
> 
> def main(argv = None):
> 
> 
>     file1=  "directory1"
>     file2 =  "directory2"
> 
> 
>     if argv is None:
>         args = sys.argv[1:]
> 
>     if len(args) == 0:
>         Initialise.init(0)
>         Process.processCon(file1, 0)
>         Output.print()
> 
>     for i in range(len(args)):
>         if args[i] == "-no":
>             Initialise.init(0)
>             Process.processCon(file2,1)
>             Output.print()
> 
>         if args[i] == "-not":
>            Initialise.init(1)
>             Process1.process(stepStore, firstSteps)
>             Output.print1()
> 
> 
> 
> if __name__ == "__main__":
>     main()
> 
> 
> Have I used bad syntax here so that a user can either run the program
> with commands:
> main.py
> main.py -no
> main.py -not
> 
> If I also wanted an option file to be passed in at the command line
> for 'main.py' and 'main.py -no' what would be the best way to go about
> this? I have never used Python to pass in arguments at the command
> line so any help would be much appreciated.

A solution using argparse (http://argparse.python-hosting.com/):

     import argparse

     def main(no=False, nott=False):
         file1 = "directory1"
         file2 = "directory2"

         if nott:
             print 'Initialise.init(1)'
             print 'Process1.process(stepStore, firstSteps)'
             print 'Output.print1()'
         else:
             print 'Initialise.init(0)'
             if no:
                 print 'Process.processCon(file2, 1)'
             else:
                 print 'Process.processCon(file1, 0)'
             print 'Output.print()'

     if __name__ == "__main__":
         parser = argparse.ArgumentParser()
         parser.add_argument('-no', action='store_true')
         parser.add_argument('-not', action='store_true', dest='nott')
         args = parser.parse_args()
         main(no=args.no, nott=args.nott)

Note that I've used print statements since I don't have your Initialize, 
Process, etc. objects. If I knew what "-no" and "-not" meant better, I 
could give you a better suggestion, e.g. where you parse the 0 or 1 
value for Initialize.init directly from the command line.

STeVe



More information about the Python-list mailing list