Newby Python Programming Question

Maarten maarten.sneep at knmi.nl
Fri May 11 12:38:29 EDT 2012


On Friday, May 11, 2012 5:25:20 PM UTC+2, Coyote wrote:

> I am migrating to Python after a 20+ year career writing IDL programs exclusively. I have a really simple question that I can't find the answer to in any of the books and tutorials I have been reading to get up to speed.

Welcome here.

> I have two programs. The first is in a file I named file_utils.py:
> 
>    def pwd():
>        import os
>        print os.getcwd()

Move the import tot the root level of the file:

    import os

    def pwd():
        print(os.getcwd())

(and print() is a function these days)

> The second is in a file I named pwd.py:
> 
>    import os
>    print os.getcwd()
> 
> Here is my question. I am using the Spyder IDE to run these programs. If I type these commands, I get exactly what I want, the name of my current directory.
> 
> But, if I "run" the pwd.py script by selecting the "Run" option from the IDE menu, the directory is printed *twice* in the output window. Why is that?

I'd say this is a bug or feature of the IDE. If I use ipython I get:

In [1]: %run mypwd
/nobackup/users/maarten/tmp/coyote

I tried to use Eclipse, but I don't think I'll do that again. I otherwise never use an IDE, it makes me confused. I don't know what the IDE is doing. Note that there is a standard module (at least on unix/linux) with the name pwd, but I guess that the IDE is not confused.

I do recommend you read http://docs.python.org/howto/doanddont.html as a starting point to avoid learning some bad habits, especially on importing. You probably already found https://www.cfa.harvard.edu/~jbattat/computer/python/science/idl-numpy.html

For scripts that are intended to be run from the command line, I use:

#!/usr/bin/env python

import os
def pwd():
    return os.getcwd()

if __name__ == "__main__":
    print(pwd())

This will allow you to import the module (without side effects) and call the function, as well as 'running' the file. This increases the usefullness of the module. There are other advantages, especially when the scripts involves (many) variables.

Maarten



More information about the Python-list mailing list