有多種選擇:
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(?)
是,使用['argparse'](https://docs.python.org/3/library/argparse.html)模塊。 – Kasramvd
或嘗試使用['click'](http://click.pocoo.org/5/)。無論哪種方式,如果參數未被傳遞,您的腳本將會投訴,並且可以在用戶執行'./script --help'時自行記錄。 – wildwilhelm
如果不是可選的,請考慮將'-'放在它的前面。所以四號參數變成了「全部」或「有限」。期望它的選擇形式與選項(al)的含義相矛盾。 – BlackJack