[英]Try except statement in python execution
Suppose I am making calls to a web api that requires a wait of 4 seconds after the limit is exceeded. 假设我正在调用一个Web API,超过该限制后需要等待4秒钟。 Using a try except loop and the time package I can have the program pause if the exception is encountered.
如果遇到异常,使用tryexcept循环和时间包可以使程序暂停。 If I am working with pandas indices in an iterative loop, will the program pick up where it left off?
如果我在迭代循环中使用pandas索引,程序会在中断的地方继续执行吗? Example:
例:
i = 0
while i < len(df):
try:
df['A'] = df[i:i + 10].apply(lambda x: api_call(x['B'])[0] + 10)
except IndexError:
time.sleep(5)
i += 10
If the exception is raised on df[12], after the program has paused for 5 seconds, how do I get the program to pick up at the index that caused the exception (signaling that the program exceeded the number of calls allowed)? 如果在df [12]上引发了异常,则在程序暂停5秒钟后,如何使程序从导致异常的索引处接听(信号表示程序超出了允许的调用次数)?
I think you just need an else
block on your try...except
code. 我认为您只需要在
try...except
代码上添加else
块。
i = 0
while i < len(df):
try:
df['A'] = df[i:i + 10].apply(lambda x: api_call(x['B'])[0] + 10)
except IndexError:
time.sleep(5)
else:
i += 10
This makes it so that i += 10
only runs if the try
block doesn't raise an exception. 这使得
i += 10
仅在try
块未引发异常时运行。 Otherwise the loop repeats with the same i
value. 否则,循环将以相同的
i
值重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.