2015-04-02 66 views
0

我对linux中的python脚本非常陌生,并且在终端中执行它们。我正在尝试调试几个互相交互的脚本,但我不明白如何在命令行中访问脚本的某些部分。下面是我正在练习的示例测试脚本。使用类和函数在命令行中调试Python

文件名为:

test.py 

的脚本是:

class testClass(): 

    def __init__(self, test): 

     self.test = test 

    def testing(): 

     print "this wont print" 


def testing2(): 

    print "but this works" 

在终端,如果我去到该文件所在的文件夹,然后尝试打印测试()函数

python -c 'import test; print test.testClass.testing()' 

我得到一个错误说

Traceback (most recent call last): 
File "<string>", line 1, in <module> 
TypeError: unbound method testing() must be called with testClass instance as first argument (got nothing instead) 

但如果我尝试打印testing2()函数

python -c 'import test; print test.testing2()' 

它将打印“但这部作品”

我怎么会去执行测试()函数,使其打印。我尝试过把各种论点放在那里,但没有任何作用。

感谢

+1

'testing2()'是一个函数,而'testClass.testing()'是一个**方法**。您需要先创建一个'testClass'的实例,然后在该实例上调用'testing()'。但为了实现这一点,你需要使''(')'将'self'作为第一个参数(或者将其定义为一个静态方法,如果这是你真正想要的)。 – 2015-04-02 15:32:46

+0

另外,没有理由使用非常有限的'python -c'...''。相反,通过在你的shell上运行'python'(从同一个工作目录)启动一个[交互式Python解释器](https://docs.python.org/2/tutorial/interpreter.html#interactive-mode),然后输入相同的语句,并享受[交互式检查](https://docs.python.org/2/tutorial/introduction.html#using-python-as-a-calculator)您的代码的好处。 – 2015-04-02 15:48:09

+0

是的,我甚至不知道这是一件事哈哈。将从现在起用 – 2015-04-02 15:52:42

回答

1

你的类应该是:

class testClass(): 
    def __init__(self, test): 
     self.test = test 

    def testing(self): 
     print "this wont print" 

的方法需要用的testClass一个实例被称为:

test.testClass("abc").testing() 

其中​​代表你test__init__说法。或者:

t = test.testClass("abc") 
test.testClass.testing(t) 

作为一个shell命令:

python -c 'import test; print test.testClass("abc").testing()' 

有关更多信息,请参见Difference between a method and a functionWhat is the purpose of self?

+0

得到它的所有帮助 – 2015-04-02 15:51:50