[Pythonmac-SIG] accessing my modules from within Python

Bob Ippolito bob at redivi.com
Sun Jan 16 04:08:01 CET 2005


On Jan 15, 2005, at 21:43, Kirk Durston wrote:

> I'm just starting to learn Python. When I write a module in one of my 
> text programs (MSWord, or Textedit) and save it as a text file in on 
> my harddrive, and then go to the terminal window to import it, I get a 
> message saying it either can't find the file or can't open it. I do 
> put the .py suffix on when I save the module, but no success. I have 
> been saving my modules in different places, the last of which was in 
> library/python/2.3/sitepackages ... no success. The test module I’ve 
> written is called bogus.py
>
>  If I start python in the terminal window and then type 'import bogus' 
> I get a message saying 'Import error: No module named bogus'
>
>  If I try and launch the python module by typing 'python bogus.py' I 
> get a message "python: can't open file 'bogus.py' "
>
>  Question: Can I use TextEdit or MS Word to write modules just so long 
> as I put a .py suffix on the file?

If and only if the file is saved as plain text.

I wouldn't recommend using either of these editors as they don't have 
any built-in support for programming (syntax highlighting, completion, 
indentation, etc.) and you will probably have the tabs vs. spaces 
problem.  You should ideally use a text editor more suitable for 
programming, such as Xcode.  If you use Xcode, make sure to uncheck 
"Editor uses tabs" in the Text Editing preference pane before writing 
any code.

>  Question: How can I save a module such that Python can find and open 
> it?

There is some useful information about how Python modules are located 
in the Python tutorial <http://docs.python.org/tut/node8.html>.

The global location where add-on modules should be placed is dependent 
on which Python you are using.  If you are using the Python 2.3.0 that 
comes with Mac OS X 10.3.x, then this location is 
<file:///Library/Python/2.3>.  Otherwise, it depends on which 
distribution of Python you installed and how you installed it.

If you would like to place your modules somewhere else, you can create 
a plain-text pth file that points to this other desired location.  
Documentation for this feature is described in the site module 
documentation <http://www.python.org/doc/lib/module-site.html>.

Running Python files from the command line is like running anything 
else from the command line.  When you say "python bogus.py", bogus.py 
MUST be in the current directory, or else it won't work.  Either you 
need to change to the directory that bogus.py is in, or pass in the 
complete path to bogus.py.  A quick way to do this is to just type 
"python ", drag bogus.py to your Terminal window to paste the file's 
full path, and press return.

-bob


More information about the Pythonmac-SIG mailing list