程序有没有办法在python中调用另一个程序?
让我解释一下我的问题:
我正在构建一个应用程序(程序1),我也在编写一个调试器来捕获程序1 { a typical try : except: }
代码块中的异常(程序2)。现在我想发布程序2,以便对于像prog 1这样的任何应用程序,prog 2可以处理异常(使我的工作更容易)。我只想让prog 1使用一段简单的代码,如:
import prog2
我的困惑源于这样一个事实:我怎样才能做到这样的事情,如何在prog 1中调用prog 2,即它应该起作用,因为prog 1中的所有代码都应该在{{1}中运行} prog 2试试阻止。
关于如何做到这一点或开始指导的任何指示我们都非常感激。
注意:我使用python 2.7和IDLE作为我的开发人员工具。
答案 0 :(得分:1)
尝试了execfile()
了吗?阅读有关如何从脚本执行另一个脚本的信息。
答案 1 :(得分:1)
我认为你需要考虑类而不是脚本。
这个怎么样?
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'
我猜你的目录中有这样的东西:
program1.py
(主程序)program2.py
(调试器)__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'
这里我们将program1的整个对象传递给program2的BugCatcher对象。然后我们访问该对象的一些属性以验证它是我们期望的。