0

Is there a way in python that if i create a .py file and then will import in a different .py file which has the catch clauses for all the possible exceptions, in such a way

suppose we have a .py file lets say test1

test1.py:

import xyz          
x=5;
print x;
func1()

Now we have test2.py ,which has a try block and except caused for all the possible exceptions. So what I need is that I want the content of test1.py to come inside the try of test2.py .Is there a way either or invoking or importing that I can achieve this?

test2.py

import traceback
import sys
import linecache
# import your file here

try:
    import first

    # invoke your files main method here and run the module
    # it is normal behavior to expect an indentation error if your file and method have not been invoked correctly


except SyntaxError as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        #print(sys.exc_info())
        formatted_lines = traceback.format_exc().splitlines()
        #print(formatted_lines)
        temp=formatted_lines[len(formatted_lines) - 3].split(',')
        line_no = str(formatted_lines[len(formatted_lines) - 3]).strip('[]')
        line=line_no.strip(',')
        #print(line[1])

        print " The error method thrown by the stacktrace is  " "'" ,e , "'"
        print " ********************************************* Normal Stacktrace*******************************************************************"
        print(traceback.format_exc())
user1495220
  • 111
  • 1
  • 2
  • 15
  • Could you please provide real examples of test1.py and test2.py? – alex_jordan Nov 12 '12 at 19:37
  • 1
    you can put the import into a try/except block, if it's that what you mean. – mata Nov 12 '12 at 19:37
  • 1
    @mata, if it's already imported, it won't work. That needs reload(test2) with some additional checks. – alex_jordan Nov 12 '12 at 19:40
  • @alex_jordan i don't really think that what's he ment to do, but the question doesn't really make it clear. 'the content of test1.py to come inside the try of test2.py' doesn't really make sense. user1495220 - could you clarify what you mean. and you should choose a better title. – mata Nov 12 '12 at 19:47

2 Answers2

2

How about:

test2.py:

try:
    import test1
except ...:
    ...

If an exception is raised while importing test1, the try...except block in test2 will have a chance to deal with it.


Or, you could put the code in test1.py inside of a main function:

def main():    
    import xyz          
    x=5;
    print x;
    func1()

and have test2.py look like this:

import test1

try:
    import first
    # invoke your files main method here and run the module
    test1.main()
except SyntaxError as e:
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • @ubuntu That is working i tried ,my concern is suppose i dont want to touch test2.py and can write a script which will automatically put the data of test1.py in test2.py...is there a way to do it suppose we invoke test1.py using test2.py? – user1495220 Nov 12 '12 at 21:21
  • What does test2.py look like? – unutbu Nov 12 '12 at 21:30
  • Like a user only need to run test2.py and provide the name of the test1.py we have something like py_compile in java which only complies a .py file and convert it into .pyc file so is there a way tht i run test2.py and call complied test1.py import py_compile # explicitly compile this module py_compile.compile("py-compile-example-1.py") – user1495220 Nov 12 '12 at 21:38
  • No, no -- what is the actual code inside test2.py that we can not change? – unutbu Nov 12 '12 at 21:40
  • ok i will put the code of test2.py in the question,actually we want to we can test2.py as a tool for all the programs ,basically in test2.py i m printing all the exception in more descriptive way(with line number and extended description.. – user1495220 Nov 12 '12 at 21:42
  • Ya tht is working ,bt i wont something so tht if i run test2.py with compiled version of test1.py then it should directly catch the exceptions of test1.py without changing anything in test2.py – user1495220 Nov 12 '12 at 22:08
0

You might want to check out decorators. There is a pretty in depth description of them here Understanding Python Decorators.

#TEST1.py
from exception_catcher import exception_catcher
@exception_catcher
def testfun1(a,b,c):
    d = a+b+c
    return d

print testfun1('c','a','t')
print testfun1('c',5,'t')

The decorator class

#exception_catcher.py
class exception_catcher(object):
def __init__(self,f):
    self.fun = f

def __call__(self,*args,**kwargs):
    try:
        return self.fun(*args,**kwargs)
    except:
        return "THERE WAS AN EXCEPTION"

The command line

>> python TEST1.py
cat
THERE WAS AN EXCEPTION

Hope that helps.

Community
  • 1
  • 1
Landon
  • 144
  • 1
  • 5