Academic Question

Dave Angel davea at ieee.org
Mon Jan 11 10:26:40 EST 2010


Victor Subervi wrote:
> On Sun, Jan 10, 2010 at 3:09 PM, MRAB <python at mrabarnett.plus.com> wrote:
>
>   
>>  browser = form.getfirst('browser', 'all')
>>     
>>> except:
>>>  browser = headers()
>>>
>>> try:
>>>       
>> A bare except, and if an exception _does_ occur, they'll be a NameError
>> because 'headers' isn't defined.
>>
>> <slap with large halibut/>
>>     
>
>
> Oh, not the large halibut again! (I will be cleaning them up ;)
>
>   
>>  os.chdir('%s/..' % cwd)
>>     
>>> sys.path.append(os.getcwd())
>>> from templateFrame import top, bottom
>>> os.chdir(cwd)
>>>
>>> Why doesn't it work if I move the bottom imports to the top? The form
>>> values get lost, even though I chdir to cwd.
>>>
>>>  I try to avoid changing the directory.
>>>       
>
> It's either that or copying them all over to the other dir, which is even
> worse, since I don't want to maintain identical scripts.
> Thanks,
> beno
>
>   
You miss the point.  Rather than doing chdir to change the current 
directory, in order to use getcwd in your sys.path.append, calculate the 
appropriate directory yourself, and use it directly, without changing 
the current directory.  Brute force would be  something like (untested):

   sys.path.append(os.path.join(os.getcwd(), ".."))

You could get trickier by stripping off the last node of the directory 
path, but it shouldn't be necessary.

Incidentally, I'd tend to use os.path.dirname( __main__.file )   rather 
than os.getcwd().  That way it'd work even if current directory was 
changed by something else.  In other words (untested):

    sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

this will add the parent directory of the current module to the os.path.

HTH
DaveA




More information about the Python-list mailing list