You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用os.getcwd()触发FileNotFoundError的原因排查

Why does os.getcwd() throw a FileNotFoundError in my test setup?

Problem Description

I'm encountering a FileNotFoundError when calling os.getcwd() in my test's setUp() method. Here's the relevant code:

def setUp(self):
    try:
        self.previous_dir=os.getcwd()
    except:
        print("no file?")
    try:
        self.test_dir.mkdir(parents=True, exist_ok=True)
        os.chdir(self.test_dir)
        self.logger.debug(f'CDed to {self.test_dir}')
    except (IOError, TypeError) as ioe:
        self.logger.error(f'Unable to make or CD to {self.test_dir}')
        sys.exit(1)

I switch back to self.previous_dir and delete the temporary directory in my tearDown() method. Could this error be caused by trying to access a directory that's already been deleted?


Answer

Great question! Yes, that’s exactly one of the most common triggers for a FileNotFoundError when calling os.getcwd().

Here’s why this happens: When your process’s current working directory is deleted (whether by another part of your test code, a separate thread, or an external process), the OS loses the reference to that directory’s inode. Even though your process still "thinks" it’s in that directory, the directory itself no longer exists—so when you call os.getcwd() to resolve the path, the OS can’t find it and throws the error.

Looking at your code, this scenario could happen if:

  • A previous test run’s tearDown() failed to switch back to the original directory, then deleted the old working directory
  • Another concurrent process or test case deleted the directory your current process was using
  • The directory was removed outside of your test suite entirely

Recommendations to Fix This

  1. Avoid bare except clauses: Your current bare except catches all exceptions, which makes it hard to diagnose exactly what’s going wrong. Instead, explicitly catch FileNotFoundError to handle this specific scenario.
  2. Add a fallback directory: If the current working directory is gone, fall back to a known, always-available directory (like your home directory or /tmp) to ensure tearDown() has a valid path to switch back to.
  3. Log meaningful warnings: Instead of a vague "no file?" print statement, log details about the error to help debug future issues.

Here’s a revised version of your setUp() code incorporating these changes:

def setUp(self):
    try:
        self.previous_dir = os.getcwd()
    except FileNotFoundError:
        # Fallback to home directory if current working dir is deleted
        self.previous_dir = os.path.expanduser("~")
        self.logger.warning("Current working directory was deleted; falling back to home directory")
    except Exception as e:
        self.logger.error(f"Unexpected error retrieving current directory: {str(e)}")
        sys.exit(1)
    
    try:
        self.test_dir.mkdir(parents=True, exist_ok=True)
        os.chdir(self.test_dir)
        self.logger.debug(f'Changed directory to {self.test_dir}')
    except (IOError, TypeError) as ioe:
        self.logger.error(f'Failed to create or switch to test directory {self.test_dir}: {str(ioe)}')
        sys.exit(1)

内容的提问来源于stack exchange,提问作者Ray Salemi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:21:14