Reputation: 97
Is there a way for a program to invoke another program in python?
Let me explain my problem:
I am building an application (program 1) , I am also writing a debugger to catch exceptions (program 2) in program 1 { a typical try : except: }
block of code . Now I want to release program 2 so that for any application like prog 1 , prog 2 can handle exceptions ( making my work easier) . I just want prog 1 to use a simple piece of code like:
import prog2
My confusion stems from the fact as how can I do something like this , how can I invoke prog 2 in prog 1, ie it should function as all the code in prog 1 should run in the {try: (prog 1) , except:}
prog 2 try block.
Any pointers on how I can do this or a direction to start would we very much appreciated.
Note: I am using python 2.7 and IDLE as my developer tool.
Upvotes: 0
Views: 346
Reputation: 8982
I think you need to think about classes instead of scripts.
What about this?
class MyClass:
def __init__(self, t):
self.property = t
self.catchBugs()
def catchBugs(self):
message = self.property
try:
assert message == 'hello'
except AssertionError:
print "String doesn't match expected input"
a = MyClass('hell') # prints 'String doesn't match expected input'
I guess you have something like this in your directory:
program1.py
(main program)program2.py
(debugger)__init__.py
from program2 import BugCatcher
class MainClass:
def __init__(self, a):
self.property = a
obj = MainClass('hell')
bugs = BugCatcher(obj)
class BugCatcher(object):
def __init__(self, obj):
self.obj = obj
self.catchBugs()
def catchBugs(self):
obj = self.obj
try:
assert obj.property == 'hello'
except AssertionError:
print 'Error'
Here we are passing the whole object of your program1 to the BugCatcher object of program2. Then we access some property of that object to verify that it's what we expect.
Upvotes: 1
Reputation: 25695
tried execfile()
yet? Read up on it on how to execute another script from your script.
Upvotes: 1