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

spir denis.spir at free.fr
Mon Apr 27 10:15:23 CEST 2009

Le Sun, 26 Apr 2009 22:35:36 +0100,
Dayo Adewunmi <contactdayo at gmail.com> s'exprima ainsi:

> 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.

When your code is (nicely) organised as a set of funcs or class definitions, you also need a "laucher" usually called "main()". Otherwise python only parses and records the definitions into live objects that wait for someone to tell them what they're supposed to do. I'll stick first at processes without any parameter, like if your func would always countdown from 10.
There are several use patterns:

(1) Program launched from command line.
Just add a call to your func:

(2) Module imported from other prog
Nothing to add to your module.
Instead, the importing code needs to hold:
   import countdown			# the module (file)
   countdown.countdown(n)		# the func itself
   from countdown import countdown	# the func, directly

(3) Both
You need to differenciate between launching and importing. Python provides a rather esoteric idiom for that:
   <func def here>
   if __name__ == "__main__":
The trick is that when a prog is launched directly (as opposed to imported), it silently gets a '__name__' attribute that is automatically set to "__main__". So that the one-line block above will only run when the prog is launched, like in case (1). While nothing will happen when the module is imported -- instead the importing code will have the countdown func available under name 'countdown' as expected, like in case (2). Clear?

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

In the case of an import, as your func definition has the proper parameter, you have nothing to change.
While for a launch from command-line, you need to get the parameter given by the user.
But how? Python provides a way to read the command-line arguments under an attribute called 'argv' of the 'sys' module.
argv is a list which zerost item is the name of the file. For instance if called
   python countdown.py 9
argv holds: ['countdown.py', '9']
Note that both are strings. Then you can catch and use the needed parameter, e.g.

from time import sleep as wait
from sys import argv as user_args

def countdown(n=10):
	if n <= 0:
		print 'Blastoff!'
		print n
def launch():
	if len(user_args) == 1:
		n = int(user_args[1])

if __name__ == "__main__":

(You can indeed put the content of launch() in the if block. But I find it clearer that way, and it happens to be a common practice.)

la vita e estrany

More information about the Tutor mailing list