【问题标题】:Change working directory from python or shell script从 python 或 shell 脚本更改工作目录
【发布时间】:2017-03-21 20:30:24
【问题描述】:

我喜欢在 python 或 bash 中做这样的事情,程序转换给定的文件路径并移动当前的 shell。

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

这里

some_path1 -> prog.py -> some_path2

我尝试使用 subprocess.call 或 os.chdir,但它不起作用,任何想法将不胜感激。

【问题讨论】:

  • 你不能那样做。 cd 是内置的。
  • 你的 python 代码在它自己的子进程中运行。它不能cd它的父进程

标签: python bash shell


【解决方案1】:

因为 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"
}

【讨论】:

  • 太好了,我喜欢这个主意。
  • 解决几乎不可能的问题的好方法。如果您认为这是最好的答案,@Ulka 接受答案。
【解决方案2】:

如果您使用source. 运行shell 脚本,它可能会更改您的shell 的当前工作目录。如果你像这样运行你的脚本,你只需要一个cd 命令。如果您在没有source. 的情况下运行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)。

【讨论】: