[Tutor] how to send command line args to py script

shawn bright nephish at gmail.com
Mon Mar 12 03:07:41 CET 2007


Well, for your first response, its great,
thanks a lot.
shawn

On 3/11/07, Gordon <chaosweevil42 at gmail.com> wrote:
> This is my first time replying to the list, so excuse me if this goes
> out wrong.
>
> Anyhow, you're looking for sys.agrv.  sys.agrv is a list of the
> arguments, with sys.agrv[0] being the script name.
>
> Code:
> ##########
> import sys  #sys.argv is part of the sys module
> def add_two_numbers(a, b):
>     x = a + b
>     return x
> y = float(sys.argv[1]) #This gets the arguments and converts them to numbers
> z = float(sys.argv[2]) #You need to do this because the arguments come
> as strings
> x = add_two_numbers(y,z) #Of course, that means if you put in "python
> add.py 1 fish"
> print x #you'll get an error.  So a try-except clause would be good here.
> ##########
> Run the above script with the formatting "python (filename).py 1 1", not
> "python (filename).py -1 -1", that'll get you negative numbers.
>
> shawn bright wrote:
> > lo there all,
> >
> > i was wondering how to make a python script accept command line arguments.
> > i mean, i have used python scripts from the command line in linux and
> > passed something to it and it knows what to do.
> >
> > like in a function, if i want to do something like this
> >
> > def add_two_numbers(a, b):
> >     x = a + b
> >     return x
> >
> > x = add_two_numbers(4,5)
> > print x
> >
> > how could i do the same from the cli.
> >
> > like python add_two_numbers.py 4 5
> > or maybe python add_two_numbers.py 4, 5
> > or even python add_two_numbers.py -a 4 -b 5
> >
> > is there an easy way to do this ?
> >
> > thanks
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list