问题描述
我想实现一个用户态指令,将采取它的参数(路径)并且更改目录到该目录。该计划完成后,我想在shell将在该目录中。所以我想实现 CD
命令,但与外部程序。
是否可以在Python脚本完成或我必须写的bash包装?
例如:
TDI @贝叶斯:/家庭/ $>蟒蛇cd.py TDI
TDI @贝叶斯:/家居/ TDI $>
其他人指出,你不能从一个孩子改变父母的工作目录。
不过,有一种方法可以实现你的目标 - 如果你从shell功能的CD,它的可以的修改工作目录。添加到您的〜/ .bashrc:
函数围棋()
{
CD $(蟒蛇/path/to/cd.py$ 1)
}
您的脚本应该打印的路径要更改的目录。例如,这可能是你cd.py:
#!的/ usr / bin中/蟒蛇
进口SYS
如果sys.argv中[1] =='TDI':打印〜/长/繁琐/路径/要/ TDI
ELIF sys.argv中[1] ==XYZ:打印〜/长/繁琐/路径/要/ XYZ
然后,你可以这样做:
TDI @贝叶斯:/家庭/ $>去TDI
TDI @贝叶斯:/家居/ TDI $>去TDI
I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell to be in that directory. So I want to implement cd
command, but with external program.
Can it be done in a python script or I have to write bash wrapper?
Example:
tdi@bayes:/home/$>python cd.py tdi
tdi@bayes:/home/tdi$>
Others have pointed out that you can't change the working directory of a parent from a child.
But there is a way you can achieve your goal -- if you cd from a shell function, it can change the working dir. Add this to your ~/.bashrc:
function go()
{
cd $(python /path/to/cd.py "$1")
}
Your script should print the path to the directory that you want to change to. For example, this could be your cd.py:
#!/usr/bin/python
import sys
if sys.argv[1] == 'tdi': print '~/long/tedious/path/to/tdi'
elif sys.argv[1] == 'xyz': print '~/long/tedious/path/to/xyz'
Then you can do:
tdi@bayes:/home/$> go tdi tdi@bayes:/home/tdi$> go tdi
这篇关于更改外壳的工作目录与python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!