Python:捕捉异常在函数外部工作,但不在函数内
问题描述:
我有一个奇怪的问题,我无法解决自己。Python:捕捉异常在函数外部工作,但不在函数内
如果我执行需要两个单独的outside_func.py
端子,第二执行捕捉BlockingIOError异常并打印消息:
outside_func.py
import fcntl
import time
# Raise BlockingIOError if same script is already running.
try:
lockfile = open('lockfile', 'w')
fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print('Script already running.')
time.sleep(20)
如果我做相同的inside_func.py
没什么被捕获并且没有消息被打印:
inside_func.py
import fcntl
import time
# Raise BlockingIOError if same script is already running.
def script_already_running():
try:
lockfile = open('lockfile', 'w')
fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print('Script already running.')
script_already_running()
time.sleep(20)
任何想法?
答
当您离开函数时文件会关闭,因此两个片段不相同,在代码片段中,尝试是以外的函数仍然存在对该文件对象的引用睡眠呼叫等进一步调用打开锁文件正确的错误。如果您通过移动睡在函数内部改变功能,你会看到错误引发的,现在你有可比性代码:
import fcntl
import time
# Raise BlockingIOError if same script is already running.
def script_already_running():
try:
lockfile = open('lockfile', 'w')
fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print('except')
sleep(20)
邮编能重现问题。 –
听起来像一个问题,你在发布的代码之外改变的东西,你没有意识到是非常重要的。 – user2357112
我更新了例子。现在问题应该是可重现的。 – Rotareti