Newby Python Programming Question

Jean-Michel Pichavant jeanmichel at sequans.com
Tue May 15 05:26:15 EDT 2012


Coyote wrote:
> CM writes:
>
>   
>> I don't know Spyder IDE, but I don't think this should happen; could
>> there just be a simple mistake?  Because you first refer to the .py
>> file as 'file_utils.py' but then you refer to the file as
>> 'pwd.py'...which is also the name of your function. Room for
>> confusion...so could you test this by saving only your one function
>> (below), give the .py a new name to avoid confusion (like test_pwd.py)
>> and then running *that* through Spyder IDE?
>>
>> def pwd():
>>     import os
>>     print os.getcwd()
>>     
>
> I probably explained the situation badly. I have a file pwd.py with these two lines of code in it:
>
>     import os
>     print os.getcwd()
>
> If I start a new Spyder IDL session and "run" this file by choosing RUN from the menu bar, the directory is printed twice. This appears to me now to be an IDE error, because if I use a runfile command, the directory is printed only once, as I expect.
>
>    >>>runfile('pwd.py')
>     C:\Users\coyote\pyscripts
>
> I've been playing around with a couple of IDEs because I liked the one I used with IDL and I wanted to use something similar for Python. The IDLDE was an Eclipse variant, but I've tried installing Eclipse before for something else and I'm pretty sure I don't need *that* kind of headache on a Friday afternoon. Unless, of course, I need a good excuse to head over to the Rio for the margaritas. :-)
>
> Cheers,
>
> David
>   
Could be that the IDE is first importing the file before executing it, 
that would be strange.
Since you have print statements at the module level it is executed on 
import.

Anyway in order to avoid any issue, as everybody does, you better write :

pwd.py:

import os

def getcwd():
    print os.getcwd()

if __name__ == '__main__': # true if this file is used as program entry 
point
    getcwd()

That way you can either execute your script as a program, or use it as a 
module.

JM


Note : there is a 'pwd' module (linux password db), thus it would be 
wise to avoid naming any file pwd.py, or your statement 'import pwd' may 
yield unexpected results.



More information about the Python-list mailing list