Search code examples
pythondirectorysubprocesscd

Python change users' directory


Does anyone know how someone would use Python to change the current directory a user is in?

I am currently working on a Python script. This script will be used by a user in a terminal/terminal emulator. When certain criteria is met, the script would move the user to the correct directory. The issue I am running into is that I can move the working directory for the Python script, but once the script exits the user is still in the directory they ran the script from. Any ideas on how to achieve this?


Solution

  • Sorry, you can't do that with a program that's launched in the normal way. At least, you can't in a POSIX-compliant OS.

    When you run a script or program in the normal way it gets run in a new process, and of course any changes made in that new process don't affect the parent process: child processes inherit environment from their parent, the parent's environment can't by affected by any changes the child makes to its environment.

    There's kind of a way around this: you can put a cd command into a script and then source that script, which executes the script in the current process rather than running it in a new process. I guess your Python code could create a tiny shell script that changes to the desired directory, but you will still need the user to source that script to make the actual directory change. When I need to do this for my own use, I just print the desired cd command to the shell so I can easily copy & paste it and then hit Enter. :)

    Take a look here for more details about why cd is like this.