2017-01-03 20 views
1

我有一個Python腳本,我從命令行運行。該腳本,它使用sys.argv,需要具備以下六(6)參數:如何在Python腳本中向用戶顯示所需的參數?

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 

我運行此腳本每天多次,因此具有記憶的參數的順序。

但是,也有其他人可能不經常運行腳本,不知道所需的參數(和/或序列)。

有沒有辦法讓他們查詢參數列表(以及每個參數的例子)?也許文檔字符串?

謝謝!

+6

是,使用['argparse'](https://docs.python.org/3/library/argparse.html)模塊。 – Kasramvd

+0

或嘗試使用['click'](http://click.pocoo.org/5/)。無論哪種方式,如果參數未被傳遞,您的腳本將會投訴,並且可以在用戶執行'./script --help'時自行記錄。 – wildwilhelm

+0

如果不是可選的,請考慮將'-'放在它的前面。所以四號參數變成了「全部」或「有限」。期望它的選擇形式與選項(al)的含義相矛盾。 – BlackJack

回答

1

有多種選擇:

  • 使用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選項的腳本,將打印出的文檔字符串頂部,與參數幫助文本的其餘部分。這可以ofcourse也以簡單的if來實現:

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