简体   繁体   English

为什么 os.chdir() 不会更改我当前的工作目录?

[英]Why won't os.chdir() change my current working directory?

When I enter the following into my terminal shell, my current working directory won't change.当我在终端 shell 中输入以下内容时,我当前的工作目录不会改变。 I don't get any error codes.我没有收到任何错误代码。

import os
os.chdir('/Users/*myname*/Documents')

When I exit the shell and enter "pwd" in the terminal, I keep getting /Users/*myname* .当我退出 shell 并在终端中输入“pwd”时,我不断收到/Users/*myname* It won't change the current working directory to Documents .它不会将当前工作目录更改为Documents Can someone help me with this?有人可以帮我弄这个吗?

Every process has its own "current working directory".每个进程都有自己的“当前工作目录”。 os.chdir changes the current working directory of the python process executing it: os.chdir更改执行它的 python 进程的当前工作目录:

>>> import os
>>> os.getcwd()
'/'
>>> os.chdir('/tmp')
>>> os.getcwd()
'/tmp'

Once you exit the python process and return to the shell process that spawned it.一旦退出 python 进程并返回到产生它的 shell 进程。 the working directory of that process won't be affected.该进程的工作目录不会受到影响。

This is not how chdir works.这不是chdir的工作方式。

Any command you give using os module works within Python context and not the terminal context.您使用os模块给出的任何命令都可以在 Python 上下文而不是终端上下文中工作。

Ex - You open a terminal in /Users/abc and then run a python interpreter there, you will get a working directory within that python interpreter and now if you make any changes in current path it will work but within that python context and it wont affect where your terminal was open.例如-您在/Users/abc中打开一个终端,然后在那里运行 python 解释器,您将在该 python 解释器中获得一个工作目录,现在如果您对当前路径进行任何更改,它将工作,但在该 Z23EEEB4347BDD26BFC6B7EEtZA3B7 上下文中影响您的终端打开的位置。

Try this - after changing to a directory, make a file using python and you will get the file where you chdir .试试这个 - 切换到一个目录后,使用python创建一个文件,你会得到你chdir所在的文件。

You can imagine the python shell as a separate process.您可以将 python shell 想象为一个单独的进程。 Once you are into that shell you are transferred into "another terminal" where you can programmatically interact with the file system using a library like os .进入 shell 后,您将被转移到“另一个终端”,您可以使用类似os的库以编程方式与文件系统进行交互。
You can try listing all the files inside the current directory after changing directory to verify the change.您可以尝试在更改目录后列出当前目录中的所有文件以验证更改。 Insert os.listdir() just after os.chdir('/Users/myname/Documents') .os.chdir('/Users/myname/Documents')之后插入os.listdir() ) 。

However, once you exit the python shell you are back to the previous shell process where you started.但是,一旦您退出 python shell,您就会回到您开始的前一个 shell 进程。 There, the current working directory hasn't changed.在那里,当前工作目录没有改变。

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

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