【问题标题】:Is there a good way to handle command line options on scripts you may import later?有没有一种好方法来处理稍后可能导入的脚本的命令行选项?
【发布时间】:2019-06-07 10:07:21
【问题描述】:

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

#!/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

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

【问题讨论】:

标签: python command-line-arguments python-import


【解决方案1】:

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

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客户端想要的。)

【讨论】:

    猜你喜欢
    • 2012-04-17
    • 2023-03-31
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多