我有一个从命令行运行的Python脚本。使用sys.argv的脚本需要以下六(6)个参数:

argument 1:  the script name (e.g. 'TimeSeries.py')
argument 2:  a configuration file (e.g. 'Customer1.cfg')
argument 3:  whether the resulting data is daily granular or hourly granular (e.g. -d or -h)
argument 4:  which data to retrieve (e.g. -all or -limited)
argument 5:  the number of days in the time series (e.g. '30')
argument 6:  the 'as of' date


我每天多次运行该脚本,因此记住了参数的顺序。

但是,还有其他人可能不经常运行脚本,并且不知道所需的参数(和/或顺序)。

他们有没有办法查询参数列表(以及每个参数的示例)?也许是文档字符串?

谢谢!

最佳答案

有多种选择:


使用Click python库并使用此库重新格式化脚本。这会自动创建一个
您可以使用的--help函数。我还没有亲自使用过这个。
使用标准库中的argparse。例如:




import argparse


def get_parser():
    parser = argparse.ArgumentParser(description='Description of your script')
    parser.add_argument('name', help='The script name (e.g. "TimeSeries.py")',
                        metavar="NAME", type=str)
    # other arguments here ...
    return parser

if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()


这将生成一个-h选项,用于每个参数的帮助文本。可以结合我的最后建议:


在文件顶部添加docstring并附带说明。每当未提供任何参数时,请打印出__doc__。再次使用argparse的示例:




"""
argument 1:  the script name (e.g. 'TimeSeries.py')
argument 2:  a configuration file (e.g. 'Customer1.cfg')
argument 3:  whether the resulting data is daily granular or hourly granular (e.g. -d or -h)
argument 4:  which data to retrieve (e.g. -all or -limited)
argument 5:  the number of days in the time series (e.g. '30')
argument 6:  the 'as of' date
"""
import argparse

... # rest of script

def get_parser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('name', help='The script name (e.g. "TimeSeries.py")',
                        metavar="NAME", type=str)
    # other arguments here ...
    return parser

if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()


现在使用-h选项调用脚本,将在顶部打印出文档字符串,并在其余的参数帮助文本中进行打印。当然,这也可以用简单的if实现:

if not args:  # somewhere in your own code
    print(__doc__)
    # exit code(?)

关于python - 如何在Python脚本中向用户显示所需的参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41445440/

10-12 14:18
查看更多