Search code examples
pythonbashcdsubshell

Change directory from python script for calling shell


I would like to build a python script, which can manipulate the state of it's calling bash shell, especially it's working directory for the beginning.

With os.chdir or os.system("ls ..") you can only change the interpreters path, but how can I apply the comments changes to the scripts caller then?

Thank you for any hint!


Solution

  • You can't do that directly from python, as a child process can never change the environment of its parent process.

    But you can create a shell script that you source from your shell, i.e. it runs in the same process, and in that script, you'll call python and use its output as the name of the directory to cd to:

    /home/choroba $ cat 1.sh
    cd "$(python -c 'print ".."')"
    /home/choroba $ . 1.sh
    /home $