2

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?

4
  • Do you want to run filename.py from the shell or just call descendants from elsewhere in your code? Commented Nov 9, 2010 at 22:42
  • run it in the shell. i know how to call descendants from within my code but not from shell Commented Nov 9, 2010 at 22:45
  • Um.. If you're trying to pass arguments to your python program from the shell you can use sys.argv Commented Nov 9, 2010 at 23:07
  • you should make your question clear that you want to run it from the shell. Its still unclear to me if you want to run it in the python shell or in a bash shell. Commented Dec 6, 2013 at 0:24

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

Do all my functions need to have self as first argument?
Spawn: all methods need self as the first argument. functions do not.
@Wooble: Thanks Wooble! I was not around.
@Spawn: As Wooble answers. :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.