Skip to content Skip to sidebar Skip to footer

Changing Directory From A Python Script: How To Not Open A New Shell

I have the following piece of code: import os unixshell=os.environ['SHELL'] dir='/home/user/somewhere' if os.path.isdir(dir): os.chdir(dir) os.system(unixshell) This is p

Solution 1:

The problem is that python runs in a child process, and it "can't" alter the current directory of the parent (I say "can't", but there are probably some debuggers that could do it - don't go there!).

The simplest solution is to use a function instead. For example:

bk() {
    dir="/home/user/somewhere"

    # equivalent to "if os.path.isdir(dir): os.chdir(dir)"[[ -d $dir ]] && cd "$dir"
}

Put this into a file called bk.sh (for example).

To compile and load the function do:

. bk.sh

Then use bk whenever you want to change directory.

The difference with a function is that it runs in the current process, it does not create a new shell.

Post a Comment for "Changing Directory From A Python Script: How To Not Open A New Shell"