[Tutor] Modules and Python tutorial by S. Thurlow - opinions please

Alan Gauld alan.gauld at btinternet.com
Sun Aug 21 00:53:53 CEST 2011


On 20/08/11 15:25, Lisi wrote:

> ridiculous.  I think that I understand how to write a basic function, but I
> can't work out how to save and call it.

If you literally mean how to write,save and
use a Python function (from within another script)
then I'll have a go:

> How to save and run a bash script:
> Write your script

Same with Python, create a text file with your favourite editor and save 
it with a .py extension. This is now a Python module that you can import 
into any other script. Lets assume you called it mymodule.py.

> save it in the normal manner

Yes, gotta do that with Python too.

> chmod to x for everyone you want to be able to execute it.  (E.g. where owner
> is root: perhaps 744)

You don't need that for a Python module, it only needs to be readable. 
(But if you do make it executable you can add a shebang line at the top 
and then run it directly from the command prompt. But since you only 
want to access the functions within we won't need to do that.)

> Either move the file into a directory on your path, or add the directory that
> the file is in to your path.

Either save the file in a directory in your PYTHONPATH or add the 
directory you saved it in to your PYTHONPATH

> It will now run.

It can now be imported.

So to use your function, let's call it spam(), in your mymodule.py file:

Create a new python script, lets assume its called myfile.py.
add the line

import mymodule

call the function with

myVariable = mymodule.spam()

Save your new Python script file

Execute your new file from Pyhon with

$ python /full/path/to/myfile.py

There is a full worked example in the Functions and Modules
topic in my tutorial...

HTH

Alan G.
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list