调用os.getcwd()触发FileNotFoundError的原因排查
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
- Avoid bare
exceptclauses: Your current bareexceptcatches all exceptions, which makes it hard to diagnose exactly what’s going wrong. Instead, explicitly catchFileNotFoundErrorto handle this specific scenario. - 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 ensuretearDown()has a valid path to switch back to. - 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

