简体   繁体   中英

Restarting a Loop if an error occurs in python

I am having some trouble with a script which produces an IndexError around 1 out 1000 times its run.

The script is an add on for a piece of software that I cant actually edit or it crashes the external software im using this for.

I am calling this script multiple times from my own script is there any way to detect if an error has occurred and loop back to try running the script again? (The script has multiple random elements, this is why the risk to repeated failures is low). I would prefer to go into the add on script and edit it manually but this doesnt appear to be an option

I have the following using the PYPI goto statement ( https://pypi.org/project/goto-statement/ ) and using except, however the error doesnt appear to be recognized and I get the same error message as I would get without the goto or except statements.

def function (stuff thats passed into the other script):
    for i in range(5000):
        print(i)
        try:
            runscript (info passed into script) 
        except IndexError:
            print(i,'fails')
            continue

There are many things wrong with this, lets go over it:

from goto import with_goto

You should avoid using goto as it can cause strange code timelines and make it difficult to read or understand your code.

def function:

You forgot your parenthesis, it should look like def function():

for i in range(5000):

Replace this with while i < 5000

print(i,'fails')

If you are trying to make an error message, use raise() .

i=i+1

In a python for loop, it automatically increments.

Can you... just... not?

def func():
  for i in range(5000):
    try:
      runscript
    except IndexError:
      return False
  return True

while not func():
  pass

This will run your function until it manages to do whatever runscript is 5000 times in a row, but it doesn't have any weird bytecode manipulation. There are other ways as well:

successes = 0
while successes < 5000:
  try:
    runscript
    successes += 1
  except IndexError:
    successes = 0

It should be clear that this is a Bad Idea™ based on this quote at the bottom of that page:

The idea of goto in Python isn't new. There is another module that has been released as April Fool's joke in 2004.

If you're trying to use something that was originally released as an April Fool's joke, there's probably a better way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM