How to create function and skip it if it fails

Asked by Gaurish Kaushal

I perform an Import operation on my application.

1. How should i transform it into a function
2. If that function fails, i want to skip it and move to next steps.

It would be great help i can do this.

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
Gaurish Kaushal
Solved:
Last query:
Last reply:
Revision history for this message
RaiMan (raimund-hocke) said :
#1

def myFunction():
     print ("I may fail")
     if (some_condition):
         print ("success")
         return True
    else:
         print ("fail")
         return False

if myFunction():
    # will bes skipped if failed (myFunction returns False)
    # success do something
# start of next step

see faq 1800 on indentation

Revision history for this message
Roman Podolyan (podolyan-roman) said :
#2

> 1. How should i transform it into a function
> 2. If that function fails, i want to skip it and move to next steps.

Don't know why you want this (if import fails - functions from that module can't be called... maybe some test question? :) ), but I did some research and found that it is possible to make skippable import in Python(Jython).

So the code is:

    def importfail():
            try:
                    import blahblahblah
            except ImportError:
                    popup('Blah-blah-blah import failed!')

    importfail()

See version with indentation and highlighted syntax here: http://pastebin.com/qSA6kmy3

I tested the code in Sikuli X RC3+ (R930). Because module blahblahblah doesn't exist (of course, cap) - function produces pop-up.

If you want just to skip import - replace "popup('Blah-blah-blah import failed!')" statement with "pass" keyword for doing nothing.

Revision history for this message
Roman Podolyan (podolyan-roman) said :
#3

Further reading on Python try-except constructions, very useful for trying something and if try fails - skipping it or doing something else : http://docs.python.org/tutorial/errors.html#handling-exceptions

Revision history for this message
Gaurish Kaushal (gaurish-kaushal) said :
#4

Thanks for the Reply. Really Helpful.
Raiman, u are doing great job here. I have seen in one of the article where your name is mentioned for your hard work.