简体   繁体   English

如何使用 python 更改用户的 shell 当前目录? (ubuntu/linux)

[英]how to change user's shell current directory using python ? (ubuntu/linux)

We can change the current directory in the shell:我们可以改变shell中的当前目录:

username@hostname:~/f1$ cd ~/f2
username@hostname:~/f2$ 

is it possible to write a python (v2.7 and / or v3) which changes the current directory to one programatically determined?是否可以编写一个 python(v2.7 和/或 v3),将当前目录更改为以编程方式确定的目录?

Eg例如

username@hostname:~/f1$ python change_dir.py
username@hostname:~/f2$ 

As chepner and Sraw correctly said, a child process cannot change the current directory of its parent.正如 chepner 和 Sraw 正确所说,子进程不能更改其父进程的当前目录。 So, what you can do is to let the Python program output the desired directory and use this output in a cd command:所以,你可以做的是让 Python 程序 output 所需的目录,并在cd命令中使用这个 output:

cd `python print_dir.py`

Maybe you mean something like this:也许你的意思是这样的:

import os
os.chdir(os.path.join(os.path.dirname(os.getcwd()), 'f2'))

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

相关问题 如何知道/更改 Python shell 中的当前目录? - How to know/change current directory in Python shell? 如何将Python程序的当前工作目录更改为用户的主目录? - How do I change the current working directory of a Python program to the user's home directory? 在Python中更改用户的当前目录 - Change current directory for user in Python 在 Python 中更改调用者的当前工作目录 - Change caller's current working directory in Python Python的基本外壳。 如何更改目录? - Basic shell with Python. How to change directory? Python:是否可以在不更改实际当前目录的情况下更改Windows命令行shell当前目录? - Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory? 在当前目录中打开python shell - Open python shell in the current directory How can I configure PyCharm's Python console so that I can run Linux shell commands on Ubuntu 18.04 WSL? - How can I configure PyCharm's Python console so that I can run Linux shell commands on Ubuntu 18.04 WSL? 如何在python脚本中更改Linux的目录? - How to change the directory of Linux in python script? 如何在 Linux 中使用 Shell 或 Python 创建目录的哈希? - How can I create a hash of a directory in Linux in Shell or Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM