0

有没有办法让一个程序在 python 中调用另一个程序?

让我解释一下我的问题:

  1. 我正在构建一个应用程序(程序 1),我还在编写一个调试器来捕获程序 1 { a typical try : except: }代码块中的异常(程序 2)。现在我想发布程序 2,这样对于像 prog 1 这样的任何应用程序,prog 2 都可以处理异常(让我的工作更轻松)。我只希望 prog 1 使用一段简单的代码,例如:

    import prog2
    
  2. 我的困惑源于这样一个事实,即我该如何做这样的事情,如何在 prog 1 中调用 prog 2,即它应该像 prog 1 中的所有代码都应该在{try: (prog 1) , except:}prog 2 try 块中运行一样运行。

任何关于我如何做到这一点的指示或开始的方向,我们将不胜感激。

注意:我使用 python 2.7 和 IDLE 作为我的开发工具。

4

2 回答 2

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

程序1

from program2 import BugCatcher

class MainClass:    
   def __init__(self, a):       
      self.property = a


obj = MainClass('hell') 
bugs = BugCatcher(obj)

程序2

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 对象。然后我们访问该对象的一些属性来验证它是否是我们所期望的。

于 2012-10-19T18:22:53.533 回答
1

试过execfile()了吗?阅读有关如何从脚本执行另一个脚本的信息。

于 2012-10-19T18:15:22.270 回答