2010-11-09 56 views
2

运行时要调用Python函数说我有代码,做一些事情复杂,打印出结果,但是对于这篇文章的目的,说出来只是做这个:如何从终端

class tagFinder: 
    def descendants(context, tag): 
     print context 
     print tag 

但说我有多个在这个类中的功能。我怎样才能运行这个功能?或者甚至当我说我做python filename.py ..我怎样才能调用该功能,并提供输入的上下文和标签?

+0

您是否想从shell运行'filename.py'或者从代码中的其他地方调用'descendants'? – 2010-11-09 22:42:54

+0

在shell中运行它。我知道如何从我的代码中调用后代,但不是从shell中调用 – Spawn 2010-11-09 22:45:50

+0

嗯..如果你想从shell中传递参数给你的python程序,你可以使用sys.argv – Joshkunz 2010-11-09 23:07:20

回答

4
~ python 
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import filename 
>>> a = tagFinder() 
>>> a.descendants(arg1, arg2) 
# output 
0

你可以通过对标准输入Python代码一小段:

python <<< 'import filename; filename.tagFinder().descendants(None, "p")' 

# The above is a bash-ism equivalent to: 
echo 'import filename; filename.tagFinder().descendants(None, "p")' | python 
2

这将抛出一个错误

>>> class tagFinder: 
...  def descendants(context, tag): 
...   print context 
...   print tag 
... 
>>> 
>>> a = tagFinder() 
>>> a.descendants('arg1', 'arg2') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: descendants() takes exactly 2 arguments (3 given) 
>>> 

你的方法应该有第一个参数为自我。

class tagFinder: 
    def descendants(self, context, tag): 
     print context 
     print tag 

除非'context'指的是自我。在这种情况下,您可以使用单一参数进行调用。

>>> a.descendants('arg2') 
+0

我的所有功能都需要自我作为第一个参数吗? – Spawn 2010-11-09 23:16:54

+0

产卵:所有方法都需要自我作为第一个参数。功能不。 – geoffspear 2010-11-09 23:27:59

+0

@Wooble:谢谢Wooble!我不在身边。 – pyfunc 2010-11-10 00:21:39