Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cd Terminal at a given directory after running a Python script?

I'm working on a simple Python script that can use subprocess and/or os to execute some commands, which is working fine.

However, when the script exits I'd like to cd the actual Terminal (in this case OS X) so on exit, the new files are ready to use in the directory where the have been created. All the following (subprocess.Popen, os.system, os.chdir) can do what I want from within the script (i.e. they execute stuff in the target directory) but on exit leave the Terminal at the script's own directory, not the target directory.

I'd like to avoid writing a shell script to temporary file just to achieve this, if this is at all possible anyway?

like image 759
Dave Everitt Avatar asked May 09 '10 21:05

Dave Everitt


1 Answers

Sadly, no. Processes are not allowed to change the environment of their parent process, and in this case your Python script is a child process of the shell. You could "fake" it by having your Python process set up a new shell - call subprocess to open a shell process and present it to the user, inheriting the modified environment from itself - but that has the downside of forcing the Python process to run continually.

This is really what shell scripts are for.. :-) Someone clearly needs to write a more traditional shell (e.g. closer to Bash than IPython) which can use python as its scripting language.

like image 169
Nick Bastin Avatar answered Nov 02 '22 23:11

Nick Bastin