简体   繁体   English

使用 python 在终端中更改目录

[英]Change directory in terminal using python

I'm writing a simple script to change the present working directory to some other directory.我正在编写一个简单的脚本来将当前工作目录更改为其他目录。 The following script works okay until the program terminates, after which I'm back to my home directory.以下脚本可以正常工作,直到程序终止,然后我回到我的主目录。

#!/usr/bin/python

import os

if __name__ == '__main__':
    os.chdir("/home/name/projects/python")
    os.system("pwd")
    print 'dir changed'

Output is:输出是:

bash:~$ python chdir.py
/home/name/projects/python
dir changed
bash:~$ pwd
/home/name

I want the directory change to remain even after the program has exited.即使在程序退出后,我也希望目录更改保持不变。 Any ideas how to do it?任何想法如何做到这一点?

Edit : What I really want to do is this: I use this directory frequently and instead of doing cd <path> every time I open the terminal, I just write ./progname and it changes the directory.编辑:我真正想做的是:我经常使用这个目录,而不是每次打开终端时都执行cd <path> ,我只写./progname并更改目录。

If you want the directory change to remain even after the program has exited.如果您希望即使在程序退出后目录更改仍保留。 You can end the python script with os.system("/bin/bash") , this will leave you in bash shell inside the new directory.您可以使用os.system("/bin/bash")结束 python 脚本,这将使您处于新目录中的 bash shell 中。

#!/usr/bin/python
import os
if __name__ == '__main__':
    os.chdir("/home/name/projects/python")
    os.system("pwd")
    os.system("/bin/bash")

For the need raised in your comment "I use this directory frequently and instead of doind cd <path> every time I open the terminal, I just write ./progname and it changes the directory"对于您在评论中提出的需求“我经常使用这个目录,而不是每次打开终端时 doind cd <path> ,我只写./progname并更改目录”
I would suggest using bash alias which will change directory:我建议使用 bash 别名来更改目录:

bash:~$ alias mycd='cd /home/name/projects/python'

and use this alias in bash shell in order to change the directory:并在 bash shell 中使用此别名以更改目录:

bash:~$ mycd

You can add this alias to your .bashrc - which will allow you to use this alias every time.您可以将此别名添加到您的.bashrc - 这将允许您每次都使用此别名。

In case someone would like to do this without python - this is most simply done with a .bash_profile file.如果有人想在没有 python 的情况下执行此操作 - 最简单的方法是使用.bash_profile文件。

Steps:脚步:

  1. Type this into your .bash_profile.将此输入到您的 .bash_profile 中。 You can open this file with pico.你可以用 pico 打开这个文件。
pico ~/.bash_profile
  1. Then create a shortcut (called an alias), you can do whatever phrase you want.然后创建一个快捷方式(称为别名),你可以做任何你想做的短语。
alias cdd="cd ~/frequent/my-directory"
  1. Then source your .bash_profile file.然后获取您的.bash_profile文件。
source ~/.bash_profile

Now, you just run your aforementioned shortcut, and this switches your directory, with many less key strokes!现在,您只需运行前面提到的快捷方式,即可切换您的目录,而且击键次数更少!

Macbook-Spen:~ spen$ cdd
Macbook-Spen:my-directory spen$ 

Sources:资料来源:

import os
os.system('cd /home/name/projects/python')

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

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