如何从命令行测试多功能python文件中的一个python函数?

时间:2013-12-06 17:58:11

标签: python

我有一个python文件something.py,里面有很多函数。我想一次测试一个函数传入变量并测试输出。如何使用变量从命令行测试一个函数以查看输出?

2 个答案:

答案 0 :(得分:3)

启动解释器并导入模块。

~$ 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)

你不会看到这个确切的文字,但是类似的东西:YMMV。


完整示例:

这是something.py:

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

现在你在shell中与something.py在同一个目录中(在我的情况下是~/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)
>>>

如果你有各种python安装,请拨打你需要的,例如python2.7python3.3python3.4。或者指向其中一个的链接,例如在我的邮箱(/usr/bin/)python上,指向python2.7(/usr/bin/)python3的链接指向python3.3

答案 1 :(得分:0)

您需要在模块中设置一些特殊功能,以便能够从命令提示符调用其中包含的函数。类似的东西:

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:])

现在:

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

结果:

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