从python脚本更改目录:如何不打开新的shell [英] Changing directory from a python script: how to not open a new shell
问题描述
我有以下代码:
import os
unixshell=os.environ["SHELL"]
dir="/home/user/somewhere"
if os.path.isdir(dir):
os.chdir(dir)
os.system(unixshell)
这是我写给我经常在终端访问的书签文件夹的脚本的一部分.脚本的一部分进入(cd)到加了书签的目录.我以以下方式使用
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$
但是,我不喜欢的是创建了一个新的bash shell,因此当我需要注销时,必须多次按下 CTRL + D
.
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.
问题是,我可以在不创建新外壳的情况下更改目录吗?可以使用python 2.4中存在的模块来实现吗?还是我需要使用更高的版本?
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?
我的问题是该问题的重复部分:
My question is more duplicate of this question:
推荐答案
问题是 python
在子进程中运行,并且它不能"更改父级(我说不能",但是可能有些调试器可以做到这一点-不要去那里!).
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"
}
将其放入名为 bk.sh
的文件中(例如).
Put this into a file called bk.sh
(for example).
要编译和加载函数,请执行以下操作:
To compile and load the function do:
. bk.sh
然后,只要您想更改目录,就使用 bk
.
Then use bk
whenever you want to change directory.
与函数的区别在于它在当前进程中运行,不会创建新的shell.
The difference with a function is that it runs in the current process, it does not create a new shell.
这篇关于从python脚本更改目录:如何不打开新的shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!