有没有一种好的方法来处理您以后可能导入的脚本的命令行选项?

Is there a good way to handle command line options on scripts you may import later?

假设您正在编写一个脚本,您希望能够直接从命令行执行或在其他地方导入函数。作为命令行可执行文件,您可能希望将标志作为选项传递。如果稍后导入脚本,将每个选项作为每个函数的参数可能会变得乏味。下面我有一个脚本,我希望它使用详细选项来说明我的观点。

#!/usr/bin/python

def getArgs():
    parser = argparse.ArgumentParser()
    parser.add_argument('input',type=int)
    parser.add_argument('-v','--verbose',action='store_true')
    return parser.parse_args()

def main(input,verbose):
    result = calculation(input,verbose) 
    if verbose:
        print(str(input) + " squared is " + str(result))
    else:
        print(result)

def calculation(input,verbose):
    if verbose:
        print("Doing Calculation")
    result = input * input
    return result 

if __name__ == '__main__': #checks to see if this script is being executed directly, will not run if imported into another script
    import argparse
    args=getArgs()
    if args.verbose:
        print("You have enabled verbosity")
    main(args.input,args.verbose)

这是一些说明性的执行

user@machine ~ $ ./whatever.py 7
49
user@machine ~ $ ./whatever.py -v 7
You have enabled verbosity
Doing Calculation
7 squared is 49
user@machine ~ $ python
Python 3.7.3 (default, Mar 26 2019, 21:43:19) 
[GCC 8.2.1 20181127] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import whatever
>>> whatever.main(7,False)
49
>>> whatever.main(7,True)
Doing Calculation
7 squared is 49

此脚本有效,但我相信在您稍后导入脚本的情况下,有一种更简洁的方法来处理命令行选项,例如强制使用默认选项。我想一个选择是将该选项视为全局变量,但我仍然怀疑有一种不那么冗长(双关语)的方式将这些选项包含在以后的函数中。

当你有许多共享公共参数的函数时,将参数放在一个对象中并考虑使函数方法成为其类型:

class Square:
  def __init__(self,v=False): self.verb=v
  def calculate(self,x):
    if self.verb: print(…)
    return x*x
  def main(self,x):
    if self.verb: print(…)
    y=self.calculate(x)
    print("%s squared is %s"%(x,y) if self.verb else y)

if __name__=="__main__":
  args=getArgs()
  Square(args.verbose).main(args.input)

False 的默认值通常是 API 客户想要的。)