[Tutor] passing variable to python script

paul brian paul1brian at gmail.com
Fri Oct 14 11:15:04 CEST 2005


There are several approaches ranging from the simple but limited to
rather advanced.

raw_input is the simplest but it is to be deprecated, and more
importantly it limits you to entering commands after the script is
running. automation becomes harder

$ myscript <arg> <arg>

Those args are put into a list called sys.argv where sys.argv[0] is
the name of the script you ran and any subsequent ones are sys.argv[1]
{2] etc etc

However my favourite is optparse module, which allows you to set up
what options you like (for example $ myscript -q
--outfile=/home/foo.txt) and will carefully check their validity,
provide defaults, convert to floats etc where needed, and there is a
cool easygui addon.



On guido's Artima weblog there is a good article on using special main
cases - it is pretty "deep" so do not worry if you cannot put it all
to use - at least you know where you can get to.


The above $ myscript <arg> is the best way to call a script, because
you can run it from the command line automatically, manually, and if
you use the convention of wrapping the script in a main() function,
then putting this at the bottom of the file

if __name__ == '__main__':
  main()

(ie you have a function addTwoNumbers(a,b), and main takes args[1] and
args[2] and passes them to addTwoNumbers)

Then main() will only be run when the script is called from the
command line, meaning the same code can be import'ed and addTwoNumbers
can be called from any other python program.

HTH


On 10/14/05, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > i want to pass an argument (a number) to a python
> > script when running it:
> >> python script.py <number>
> >
> > i want to be able to use <number> within script.py
> > as a parameter.
> >
> > how do i set this up?
>
> This is covered in the 'talking to the user' topic in my tutorial.
>
> The short answer is use sys.argv
>
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741


More information about the Tutor mailing list