简体   繁体   English

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

[英]Change working directory from python or shell script

I like to do something like this in python or bash, where the program transform the given file path and move the current shell. 我喜欢在python或bash中做类似的事情,程序转换给定的文件路径并移动当前的shell。

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

Here 这里

some_path1 -> prog.py -> some_path2

I tried with subprocess.call or os.chdir, but it's not work, any idea will be appreciated. 我尝试使用subprocess.call或os.chdir,但它不起作用,任何想法都将受到赞赏。

Since python runs in its own process, it won't be able to change the current directory of your shell. 由于python在自己的进程中运行,因此无法更改shell的当前目录。 However, you could do something like this: 但是,你可以这样做:

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

It's possible for a shell script to change your shell's current working directory if you run it with source or . 如果使用source或者运行它,shell脚本可能会更改shell的当前工作目录. . If you run your script like this, a cd command will be all you need. 如果你像这样运行你的脚本,你将需要一个cd命令。 If you're running a shell script without source or . 如果您正在运行没有source或的shell脚本. , or if you're running anything that's not a shell script, then there's no nice way to do it, and you'd be forced to resort to nasty hacks like injecting into the process with a debugger (not recommended, but see How do I set the working directory of the parent process? and/or https://unix.stackexchange.com/questions/281994/changing-the-current-working-directory-of-a-certain-process if you really must do this). 或者如果你正在运行任何不是shell脚本的东西,那么就没有好的方法可以做到这一点,并且你不得不采用令人讨厌的黑客方式,比如使用调试器注入进程(不推荐,但请参阅如何操作)我设置父进程的工作目录?和/或https://unix.stackexchange.com/questions/281994/changing-the-current-working-directory-of-a-certain-process如果你真的必须这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM