Persistent Directory Change?

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri May 31 10:44:00 EDT 2002


"Dave Butler" <davebutlerREMOVE at hotmail.com> wrote in
news:UaLJ8.12059$W04.578566 at twister.rdc-kc.rr.com: 

> I have a need for the current directory from a Python script to
> persist after the script ends. Is this possible? A simple approach
> such as 
> 
> --------------------
> import os
> 
> print os.getcwd()
> os.chdir(r'f:\temp')
> print os.getcwd()
> --------------------
> 
> does not work. It seems the directory change occurs in the Python
> process, but not in the command prompt which called it.

That is the normal behaviour for most systems: changes in a program's 
environment do not affect the environment of the parent process. Not that 
windows really has a parent/child relationship between processes...

> 
> I am using Python 2.1 under Windows 2000.
> 
> Any suggestions for accomplishing this?
Oops, I think I just dropped something on the keyboard. Read it and weep:
----- begin perverse.cmd ------
@call :run %* & goto :EOF
'''
:run
@echo off
for %%p in (python.exe) do (
   for /F "tokens=1*" %%q in ('%%~$PATH:p -x "%~f0" %*') do %%q %%r
)
goto :EOF
'''
import sys
commandstream = sys.stdout
sys.stdout = sys.stderr
# Anything printed to commandstream will be interpreted

print "Directory changing script"
print "Arguments:", str.join(" ", sys.argv)
print >>commandstream, "cd \\"
----- end perverse.cmd -----
BTW, this needs to find python.exe on your path.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list