3

Observe the following:

$ pwd
/home/username

$ python
>>> import os
>>> os.chdir("/")

# Ctrl + D
$ pwd
/home/username

But I want to be in the / dir after exiting the python interpreter, is that possible using python?

I would like to know because I want to make a platform independent script(using python) where an optional convenience command cd's the user into a certain directory.

Bentley4
  • 10,678
  • 25
  • 83
  • 134
  • I do not believe this is possible in the way you intend. read this thread for more details. http://stackoverflow.com/questions/3786678/change-working-directory-in-shell-with-a-python-script – Bryan Aug 10 '13 at 22:38
  • 4
    Related / possible dupe: [How do I set the working directory of the parent process?](http://stackoverflow.com/q/2375003) – Martijn Pieters Aug 10 '13 at 22:38
  • Hrm, I meant the other link, but it'll do. – Martijn Pieters Aug 10 '13 at 22:41
  • Thanks Martijn. If you like you can put the links into a seperate answer so I can accept an answer. – Bentley4 Aug 10 '13 at 22:46

1 Answers1

5

But I want to be in the / dir after exiting the python interpreter, is that possible using python?

It is not possible. Neither by using Python or any other "acceptable" way. By acceptable, I mean "without outrageously hacking your system (with gdb for example)" ;)

More seriously, when the user launch an executable from a shell, the child process will run in its own environment, which is mostly a copy of its parent environment. This environment contains "environment variables" as well as the "current working directory", just to name those two.

Of course, a process can alter its environment. For example to change its working directory (like when you cd xxx in you shell). But since this environment is a copy this does not alter the parent's environment in any way. And there is no standard way to access your parent environment.

Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125