我有以下代码:
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'
这怎么可能发生?我在Windows 10上运行64位Python 3.7.2。
答案 0 :(得分:1)
这很可能是比赛条件。从测试目录是否存在到对目录进行处理之间存在一段时间,在此期间可以被另一个进程删除。
避免这种情况的通常方法是尝试操作,并为失败做好准备,例如:
try:
os.listdir(x)
except FileNotFoundError:
# log and stop here