Python os.listdir завершается с ошибкой FileNotFoundError, когда каталог существует - PullRequest
1 голос
/ 08 марта 2019

У меня есть следующий код:

def handle_empty_directories(dir):
    if os.path.exists(dir):
        shouter.shout("%s exists" % dir)
    else:
       shouter.shout("%s doesn't exists" % dir)
    entries = os.listdir(dir)
    if entries == []:
        open(os.path.join(dir, Commiter.hed_file), "w").close()
    else:
        if (len(entries) > 1) and (Commiter.hed_file in entries):
            os.remove(os.path.join(dir, Commiter.hed_file))
        for entry in entries:
            if entry not in Commiter.hed_ignore:
                full_entry = os.path.join(dir, entry)
                if (os.path.isdir(full_entry)):
                    Commiter.handle_empty_directories(full_entry)

Иногда вызов os.listdir(dir) завершается неудачно с FileNotFoundError, хотя вызов os.path.exists(dir) говорит, что он существует:

08:57:56 - C:\r2g-wd\sport-6.0.5\SBS\SBS\Light\bin\com\ibm\ArtifactTechnology\ABS\ArtifactBroker exists
Traceback (most recent call last):
  File "migration.py", line 169, in <module>
    migrate()
  File "migration.py", line 80, in migrate
    rtc.acceptchangesintoworkspace(rtc.getchangeentriestoaccept(changeentries, history))
  File "c:\Users\GeoffAlexander\Documents\Nirvana\RTC2Git\git-repositories\rtc2git-migration-tool\rtcFunctions.py", line 304, in acceptchangesintoworkspace
    Commiter.handle_empty_directories(os.getcwd())
  File "c:\Users\GeoffAlexander\Documents\Nirvana\RTC2Git\git-repositories\rtc2git-migration-tool\gitFunctions.py", line 126, in handle_empty_directories
    Commiter.handle_empty_directories(full_entry)
  File "c:\Users\GeoffAlexander\Documents\Nirvana\RTC2Git\git-repositories\rtc2git-migration-tool\gitFunctions.py", line 126, in handle_empty_directories
    Commiter.handle_empty_directories(full_entry)
  File "c:\Users\GeoffAlexander\Documents\Nirvana\RTC2Git\git-repositories\rtc2git-migration-tool\gitFunctions.py", line 126, in handle_empty_directories
    Commiter.handle_empty_directories(full_entry)
  [Previous line repeated 6 more times]
  File "c:\Users\GeoffAlexander\Documents\Nirvana\RTC2Git\git-repositories\rtc2git-migration-tool\gitFunctions.py", line 116, in handle_empty_directories
    entries = os.listdir(dir)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\r2g-wd\\sport-6.0.5\\SBS\\SBS\\Light\\bin\\com\\ibm\\ArtifactTechnology\\ABS\\ArtifactBroker'

Как это может случиться?Я использую Python 3.7.2 в 64-разрядной версии на Windows 10.

1 Ответ

1 голос
/ 08 марта 2019

Скорее всего, это состояние гонки.Между тестированием существует ли период времени, когда каталог существует, а затем что-то с ним делается, в котором он может быть удален другим процессом.

Обычный способ избежать этого - просто попробовать выполнить действие, ибудьте готовы к его провалу, например:

try:
  os.listdir(x)
except FileNotFoundError:
  # log and stop here
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...