简体   繁体   中英

How to call python functions when running from terminal

Say i have code that does something complicated and prints 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM