[Tutor] How to run a .py file or load a module?
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
> 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
> the function with an argument. That works, naturally.
> I've also tried this:
> >>>import countdown
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
> 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).
> b) Import the function in the interactive interpreter, and call it like so:
> without getting the abovementioned error.
The script would then look like:
times = int(sys.argv) # The argument given on the command line
if n <=0:
print 'Blast off!'
More information about the Tutor