python - 从 python 脚本更改目录 : how to not open a new shell

标签 python bash shell os.path

我有以下代码:

import os

unixshell=os.environ["SHELL"]
dir="/home/user/somewhere"
if os.path.isdir(dir):
    os.chdir(dir)
    os.system(unixshell)

这是我为在终端中经常访问的文件夹添加书签而编写的脚本的一部分。脚本的一部分进入(cd)到添加书签的目录。我按以下方式使用

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

但是,我不喜欢的是创建了一个新的 bash shell,所以当我需要注销时,我必须按 CTRL+D多次。

问题是,我可以在不创建新 shell 的情况下更改目录吗?使用 python 2.4 中存在的模块是否可以实现这一点,或者我是否需要使用更高版本?

编辑:我的问题与这个问题更加重复:

Change directory of a parent process from a child process

最佳答案

问题是python在子进程中运行,并且它“不能”改变父进程的当前目录(我说“不能” ,但可能有一些调试器可以做到这一点 - 不要去那里!)。

最简单的解决方案是使用函数。例如:

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

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

将其放入名为 bk.sh 的文件中(例如)。

要编译并加载函数,请执行以下操作:

. bk.sh

然后每当你想改变目录时使用bk

与函数的区别在于它在当前进程中运行,它不会创建新的 shell。

关于python - 从 python 脚本更改目录 : how to not open a new shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43611307/

相关文章:

bash - 使用自动 bash 脚本检查 FTP 中是否存在文件

bash - 为什么 bash 提示符(PS1)会附加 ghost 命令?

python - python装饰器中变量的范围——改变参数

linux - 查找在特定工作目录中运行的所有进程

bash - 如何在命令行上从 sbt-dynver 获取版本?

c - 从由同一脚本编译的 C 程序中退出 shell 脚本

c++ - 获取 C 中后台 shell 命令的 PID

Python 名称缩写查找

python - 在Python中使用group by和排序后如何获得数据框中销量前3名的数据?

python - 对 python2 和 python3 使用相同代码的编码 + 加密 + pad 出现问题