从python或shell脚本更改工作目录

2024-04-19 18:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢在python或bash中执行类似的操作,程序将转换给定的文件路径并移动当前shell。在

ulka:~/scc/utils$ python prog.py some_path1
ulka:some_path2$

这里

^{pr2}$

我试过了subprocess.call或者os.chdir公司,但这不是工作,任何想法都会得到赞赏。在


Tags: 文件py路径程序bashutilssomeshell
2条回答

由于python在它自己的进程中运行,它将无法更改shell的当前目录。但是,您可以这样做:

change_path() {
    # prog.py figures out the real path that you want and prints
    # it to standard output
    local new_path=$(python prog.py some_path1)  # could use an argument "$1"
    cd "$new_path"
}

如果使用source.运行shell脚本,它可能会更改shell的当前工作目录。如果您像这样运行脚本,cd命令将是您所需要的。如果您运行的是一个没有source.的shell脚本,或者如果您正在运行任何不是shell脚本的shell脚本,那么没有什么好的方法可以做到,并且您将被迫求助于一些讨厌的黑客操作,比如使用调试器注入进程(不推荐,但如果您确实必须这样做,请参见How do I set the working directory of the parent process?和/或https://unix.stackexchange.com/questions/281994/changing-the-current-working-directory-of-a-certain-process)。在

相关问题 更多 >