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
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.
3 Comments
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'],)