[Tutor] Help

Alan Gauld alan.gauld at freenet.co.uk
Fri Dec 3 09:51:05 CET 2004


> I need to know how to run another module through one what is the
command do
> I have to include a path name and if there is any special way I have
to save
> the file

See my tutor for more info on modules and functions.

The short answer is that if you create a module
(ie a python file) and put the code into functions, then you
can impot the module and execute the functions.

Any code that is not in a function will be executed when you
import the module. Thus:


###############
# File: mymodule.py
print 'welcome to my module'

def myfunction():
    print 'this is my function'

def another():
    return 42
##################

#################
# file myprogram.py
import mymodule

mymodule.myfunction()
print mymodule.another()
mymodule.myfunction()
##################

When I run myprogram.py I get:

welcome to my module
this is my function
42
this is my function

The first line gets printed by the import statement,
the second,third and fourth by the function calls.
Notice that the first line can only be generated once
but the functions can be used as often as you like.
So the best course of action is to put all the module
code into functions and you can access those as and
when you need them.

Notice too that the module is just a regular python file,
there is nothing special needed to make it "a module".
Provided it is in the same folder as your program, or
anywhere in pythons search path (sys.path) python will
import it without need for any path specifications etc.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list