Changing directory from a python script: how to not open a new shell [duplicate]

Deadly 提交于 2020-07-09 06:14:34

问题


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 part of a script I wrote to bookmark folders I visit often in the terminal. A part of the script goes (cd's) to the bookmarked directory. I use it in the following way

~/olddir$ bk.py go [handle to bookmarked directory]
~/bookmarkeddir$

But, the thing I don't like is that a new bash shell is created, so when I need logout, I have to press CTRL+D multiple times.

The question is, can I change directory without creating a new shell? Is this possible using modules existent in python 2.4, or do I need to go to a higher version?

Edit: My question is more duplicate of this question:

Change directory of a parent process from a child process


回答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.



来源:https://stackoverflow.com/questions/43611307/changing-directory-from-a-python-script-how-to-not-open-a-new-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!