Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change directory in python so it remains after running the script?

Tags:

python

I'm trying to change the terminal directory through a python script. I've seen this post and others like it so I know about os.chdir, but it's not working the way I'd like. os.chdir appears to change the directory, but only for the python script. For instance I have this code.

#! /usr/bin/env python
import os

os.chdir("/home/chekid/work2/")
print os.getcwd()

Unfortunately after running I'm still in the directory of the python script (e.g. /home/chekid) rather than the directory I want to be in. See below.

gandalf(pts/42):~> pwd
/home/chekid

gandalf(pts/42):~> ./changedirectory.py
/home/chekid/work2

gandalf(pts/42):~> pwd
/home/chekid

Any thoughts on what I should do?

Edit: Looks like what I'm trying to do doesn't exist in 'normal' python. I did find a work around, although it doesn't look so elegant to me.

 cd `./changedirectory.py`
like image 944
che_kid Avatar asked Dec 04 '15 18:12

che_kid


1 Answers

You can't. The shell's current directory belongs to the shell, not to you.

(OK, you could ptrace(2) the shell and make it call chdir(2), but that's probably not a great design, won't work on Windows, and I would not begin to know how to do it in pure Python except that you'd probably have to mess around with ctypes or something similar.)

You could launch a subshell with your current working directory. That might be close enough to what you need:

os.chdir('/path/to/somewhere')
shell = os.environ.get('SHELL', '/bin/sh')
os.execl(shell, shell)
# execl() does not return; it replaces the Python process with a new shell process

The original shell will still be there, so make sure you don't leave it hanging around. If you initially call Python with the exec builtin (e.g. exec python /path/to/script.py), then the original shell will be replaced with the Python process and you won't have to worry about this. But if Python exits without launching the shell, you'll be left with no shell open at all.

like image 132
Kevin Avatar answered Oct 25 '22 10:10

Kevin