开发者

os.getcwd() throws Exception

开发者 https://www.devze.com 2023-03-09 09:41 出处:网络
I have situation when the current directory becomes invalid (ie, when some program deletes it). My Python script calls os.getcwd() which terminates with following exception

I have situation when the current directory becomes invalid (ie, when some program deletes it). My Python script calls os.getcwd() which terminates with following exception

OSError: [Errno 2] No such file or directory

Ideally, it my script would automatically cd into parent directory in开发者_开发知识库 such situation. When is the recommended strategy for implementing this?

Note, if I try ls from the shell, I get ls: cannot open directory .: Stale NFS file handle


Ideally, it my script would automatically cd into parent directory in such situation. When is the recommended strategy for implementing this?

Just use try/except block for that, that's what for we have them :)

try:
    os.getcwd()
except OSError:
    os.chdir("..")
    os.getcwd()
or something similar...

[edit] Anyway I guess such situation is realy bad for your app - deleted dir, or broken NFS connection etc, and this probably should not be silienced by just change dir - it depends on app of course...

0

精彩评论

暂无评论...
验证码 换一张
取 消