关键字驱动小练习

同一个目录下,创建一个testdata.txt文件,用来放测试的数据

testdata.txt

pri||helloworld
add||2||3

创建pw.py文件,把关键字函数放在这里面

pw.py

def pri(s):
    print(s)

def add(a,b):
    print(a+b)
    return a+b

创建main.py文件,把主程序即脚本放在这里面

main.py

from kw import *
import keyword

with open("testdata.txt") as fp:
    test_data_lines = fp.readlines()

for test_data in test_data_lines:
    test_data = test_data.strip()
    if test_data.count("||")==2:
        func_name,a,b = test_data.split("||")
        command = "%s(%s,%s)" %(func_name,a,b)
        #add(2,3)
        
        #comput(a,b)
        print(eval(command))
    elif test_data.count("||")==1:
        func_name,a = test_data.split("||")
        command = "%s('%s')" %(func_name,a)
        #pri('hello world')
        eval(command)
    else:
        continue

执行main.py

原文地址:https://www.cnblogs.com/ff-gaofeng/p/11274846.html