0

I have a python file something.py that has a lot of functions inside of it. I want to test one function at a time passing in variables and testing the output. How do I do I test one function from the command line with a variable to see the output?

2 Answers 2

3

Launch the interpreter and import the module.

~$ python
Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from something import yourfunc
>>> yourfunc(a,b,c,d)

You won't see this exact text, but something similar: YMMV.


Full example:

This is something.py:

def funcA(): return 'A'
def twice(n): return 2 * n
def swap(a, b): return b, a

Now you are in your shell in the same directory as something.py (in my case ~/stackoverflow):

~/stackoverflow$ python
Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from something import twice, swap
>>> twice(24)
48
>>> swap(1,2)
(2, 1)
>>>

If you have various python installations, call the one you need, e.g. python2.7, python3.3, python3.4. Or a link to one of them, e.g. on my box (/usr/bin/)python links to python2.7 and (/usr/bin/)python3 links to python3.3.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the Python interpreter. I think the OP wants to use the commandline/terminal. You should at least tell him how to launch the interpreter.
@iCodez Something like this?
Yea. I know it seems redundant, but if you are inexperienced with Python, you may not know about the interpreter.
0

You would need to setup something special in your module to be able to call functions contained in it from the command prompt. Something like:

def a(*args, **kwargs):
    print("fn a, called with: {}".format(str(args)))

def b(*args, **kwargs):
    print("fn b, called with: {}".format(str(args)))

def call_fn(args):
    fn, args = args[0], args[1:]
    if len(args) == 1:
        args = args[0]

    fn = eval(fn)
    fn(args)

if __name__ == '__main__':
    import sys    
    call_fn(sys.argv[1:])

Now:

c:\temp>python my_module.py a arg1, arg2, kwarg1=something

results in:

fn a, called with: (['arg1,', 'arg2,', 'kwarg1=something'],)

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.