How to call python functions when running from terminal
Say i have code that does something complicated and pr开发者_如何学运维ints the result, but for the purposes of this post say it just does this:
class tagFinder:
def descendants(context, tag):
print context
print tag
But say i have multiple functions in this class. How can i run this function? Or even when say i do python filename.py.. How can i call that function and provide inputs for context and tag?
~ 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
This will throw an error
>>> 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)
>>>
Your method should have first arg as self.
class tagFinder:
def descendants(self, context, tag):
print context
print tag
Unless 'context' is meant to refer to self. In that case, you would call with single argument.
>>> a.descendants('arg2')
You could pass a short snippet of python code on stdin:
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
精彩评论