python - 执行 os.getcwd() 时出错?

标签 python

我遇到了一个对我来说很奇怪的问题。我进行了一些测试以调试出现的问题,当我尝试查找当前工作目录时,出现以下错误:

ipdb> os.getcwd()
*** OSError: [Errno 2] No such file or directory

有什么问题,如何查看当前工作目录?

最佳答案

您当前的工作目录不再存在:

$ mkdir deleteme
$ cd deleteme/
$ ../bin/python
Python 2.7.6 (default, Apr 28 2014, 17:17:35) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'/Users/mj/Development/venvs/stackoverflow-2.7/deleteme'
>>> ^Z
[1]+  Stopped                 ../bin/python
$ cd ..
$ rmdir deleteme
$ fg
../bin/python   (wd: ~/Development/venvs/stackoverflow-2.7/deleteme)

>>> os.getcwd()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory

解决方法是使用 os.chdir() 将您的工作目录更改为现有目录:

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

但是如果您在测试套件中遇到这种情况,那么该测试套件正在使用一个临时工作目录,该目录已被清理。

关于python - 执行 os.getcwd() 时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23889636/

相关文章:

python - 遍历包含字典的两个列表,将匹配附加到第三个列表

python - Mininet 中进程具有不同 PID 空间的主机

python - 为什么我在使用 Python 请求模块向 YouTube API v3 发出 POST 请求时得到 "Request is missing required authentication credential"?

python - 使用 Python 比较两个不同的 csv 列时无法获取缺失的元素

python - 如何在Python Mockito中正确使用verifyNoUnwantedInteractions()?

python - 即时创建文件并转换为 pdf

python - 是否可以确定一个函数是在另一个函数的主体中调用还是作为函数的参数调用?

Python - 传递对象值而不是引用

python - 是否可以在子类模型中使用 Tensorflow Keras 函数式 API?

python - Python (Django) 应用程序中的线程化 SOAP 请求?