我有多个脚本在调用python脚本(https://github.com/alvations/meanie)时给出一个数字列表作为参数来计算不同的方法:
例如,harmonic_mean()
:
# -*- coding: utf-8 -*-
import math
def harmonic_mean(x): # x is a list of values.
""" Returns the harmonic mean given a list of values. """
return len(x) / sum([1/i for i in x])
def main(means):
print "Input:", means
means = map(float,means)
print "harmonic mean = ", harmonic_mean(means)
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
sys.stderr.write('Usage: python %s mean1 mean2 mean3 ... \n' % sys.argv[0])
sys.exit(1)
main(sys.argv[1:])
和root_mean_square()
# -*- coding: utf-8 -*-
import math
def root_mean_square(x): # x is a list of values.
""" Returns the root mean square (rms) given a list of values. """
return math.sqrt(sum([i*i for i in x])/len(x))
def main(means):
print "Input:", means
means = map(float,means)
print "root mean square = ", root_mean_square(means)
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
sys.stderr.write('Usage: python %s mean1 mean2 mean3 ... \n' % sys.argv[0])
sys.exit(1)
main(sys.argv[1:])
如您所见,这两个脚本完全相同,只是调用不同的mean()
函数并在main()
打印不同的输出。我如何组合它们并允许用户在控制台/终端上调用它时给出一个平均选项参数/参数?例如。组合脚本是调用meannie.py
:
$ python meanie.py harmonic 1 2 3
$ python meanie.py hm 1 2 3
上面的命令应该提供与调用相同的输出(这就是用户现在调用harmonic_mean()脚本的方式):
$ python hm.py 1 2 3
答案 0 :(得分:1)
Python具有一流的功能;他们像其他一切一样反对,可以用同样的方式传递。所以你只需要一种方法将用户输入映射到指定的函数,然后将其传递给main
函数:
def harmonic_mean(x):
...
def root_mean_square(x):
...
MEAN_FUNCS_MAP = {
'hm': harmonic_mean,
'harmonic': harmonic_mean,
'rms': root_mean_square,
}
def main(mean_fn, means):
print "Input:", means
means = map(float,means)
print "root mean square = ", mean_fn(means)
if __name__ == '__main__':
import sys
if len(sys.argv) < 3 or sys.argv[1] not in MEAN_FUNCS_MAP:
sys.stderr.write('Usage: python %s <function> <mean1> <mean2> <mean3> ... \n' % sys.argv[0])
sys.exit(1)
main( MEAN_FUNCS_MAP[sys.argv[1]], sys.argv[2:] )
您还应该查看argparse模块,它比滚动您自己的命令行界面更不容易出错。