試圖讓我的腳本更通用,所以我添加了一些標誌。我的問題是,只有當你輸入-h時,該幫助纔有效。我想在沒有選擇標誌時調用-h。python腳本envoke -h或--help如果沒有選項
例如:
python 0_log_cleaner.py
Traceback (most recent call last):
File "0_log_cleaner.py", line 51, in <module>
getFiles(options.path,options.org_phrase,options.new_phrase,options.org_AN,options.new_AN,options.dst_path)
File "0_log_cleaner.py", line 37, in getFiles
for filename in os.listdir(path):
TypeError: coercing to Unicode: need string or buffer, NoneType found
,但如果我添加-h我得到:
python 0_log_cleaner.py -h
用法:例:
python 0_log_cleaner.py --sp original_logs/ --dp clean_logs/ --od CNAME --nd New_CNAME --oan 10208 --nan NewAN
Options:
-h, --help show this help message and exit
--sp=PATH Path to the source logs ie original_logs/
--dp=DST_PATH Path to where sanitized logs will be written to ie
clean_logs
--od=ORG_PHRASE original domain name ie www.clientName.com, use the command
-od clientName
--nd=NEW_PHRASE domain name to replace -od. ie -od clientName -nd domain
makes all log that use to be www.clientName.com into
www.domain.com
--oan=ORG_AN original AN number
--nan=NEW_AN AN number to replace original. ie -oan 12345 -nan AAAA1
replaces all instances of the AN number 12345 with AAAA1
編輯3回答 樣品我代碼來生產^
import argparse
import sys
usage = "Description of function"
parser = argparse.ArgumentParser(description=usage)
parser.add_argument("--sp", dest="path", help='Path to the source logs ie logs/')
...
...(additional add arugments)
args = parser.parse_args()
def getFiles(path,org_phrase,new_phrase,org_AN,new_AN,dst_path):
if not len(sys.argv) > 1:
parser.print_help()
else:
run your logic
你解析你的選擇如何?如果您仍在使用['optparse'](https://docs.python.org/2/library/optparse.html):切換到(不推薦使用)[argparse](https://docs.python .org/2.7/library/argparse.html)和[覆蓋'.error()'](http://stackoverflow.com/questions/3636967/python-argparse-how-can-i-display-help-automatically-在錯誤)。 – dhke
@dhke剛剛被認爲是argparse – chowpay