Spawn
Spawn

Reputation: 181

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?

Upvotes: 2

Views: 12118

Answers (3)

pyfunc
pyfunc

Reputation: 66739

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')

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 362187

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

Upvotes: 0

Falmarri
Falmarri

Reputation: 48615

~ 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

Upvotes: 4

Related Questions