【发布时间】: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