2010-11-09 61 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