[Tutor] How to run a .py file or load a module?

Sander Sweers sander.sweers at gmail.com
Mon Apr 27 00:07:19 CEST 2009


2009/4/26 Dayo Adewunmi <contactdayo at gmail.com>:
> I'm looking at recursion in "Think Python", and this is the bit of code:
>
> #!/usr/bin/env python
>
> def countdown(n):
>       if n <= 0:
>               print 'Blastoff!'
>       else:                 print n
>               countdown(n-1)
>
>
> I've typed that in vim and saved as countdown.py, but I'm not sure how to
> run it.
>
> However with this particular function that requires an argument, I'm not
> sure how to run it.
>
> I've had to type it out in the python prompt and then
> call
> the function with an argument. That works, naturally.
>
> I've also tried this:
>
>       >>>import countdown
>       >>>countdown(10)

When you import it lile this the function countdown is part of the
module countdown. So you call it like countdown.countdown(10). Or
import it like "from countdown import countdown" and then your example
will work.

> but this is the error I get:
>
>       Traceback (most recent call last):
>         File "<stdin>", line 1, in <module>
>       NameError: name 'countdown' is not defined
>
> How can I
>
> a) Open my shell, and do something like: $ python countdown.py   but have it
> take an argument and pass it to the function, and execute.

Look at sys.argv which returns a list with the first value being the
script name and the second are the command line argument(s).
http://docs.python.org/library/sys.html

> b) Import the function in the interactive interpreter, and call it like so:
>
>       countdown(10)
>
> without getting the abovementioned error.

See above.

The script would then look like:

#!/usr/bin/env python

import sys

times = int(sys.argv[1]) # The argument given on the command line

def countdown(n):
    if n <=0:
        print 'Blast off!'
    else:
        countdown(n-1)

countdown(times)

Greets
Sander


More information about the Tutor mailing list