Python--命令行參數解析Demo


寫沒有操作界面的程序時,最討厭的就是參數解析問題,尤其是很多參數那種,下面是一個小Demo,拿出來與各位分享:

 1 # -*- coding:utf8 -*-
 2 import os
 3 import datetime
 4 import sys
 5 from optparse import OptionParser
 6 
 7 
 8 def get_user_paras():
 9     try:
10         opt = OptionParser()
11         opt.add_option('--host_ip',
12                        dest='host_ip',
13                        type=str,
14                        help='the ip of the check host')
15         opt.add_option('--run',
16                        action="store_true",
17                        dest="is_run",
18                        default=False,
19                        help="run the scripts")
20         opt.add_option('--view',
21                        action="store_false",
22                        dest="is_run",
23                        default=False,
24                        help="only view but not run the scripts")
25         opt.add_option('--show_type',
26                        dest="show_type",
27                        type=int,
28                        default=0,
29                        help="0 or 1, 0 only show the simple data, 1 show the full data")
30         (options, args) = opt.parse_args()
31         is_valid_paras = True
32         error_messages = []
33         host_ip = options.host_ip
34         is_run = options.is_run
35         show_type = options.show_type
36         if not host_ip:
37             error_messages.append("host_ip must be set;")
38             is_valid_paras = False
39         if show_type not in [0, 1]:
40             error_messages.append("show_type only can be 0 or 1;")
41             is_valid_paras = False
42 
43         if is_valid_paras:
44             user_paras = {"host_ip": host_ip, "is_run": is_run, "show_type": show_type}
45             return user_paras
46         else:
47             for error_message in error_messages:
48                 print(error_message)
opt.print_help()
49 return None 50 except Exception as ex: 51 print("exception :{0}".format(str(ex))) 52 return None 53 54 55 def main(): 56 user_paras = get_user_paras() 57 if user_paras is None: 58 sys.exit(0) 59 info = "host_ip:{0}, is_run:{1}, show_type:{2}" 60 info = info.format(user_paras["host_ip"], 61 user_paras["is_run"], 62 user_paras["show_type"]) 63 print(info) 64 65 66 if __name__ == '__main__': 67 main()

 

當使用OptionParser時,會自動增加--help和-h參數,也會自動生成參數幫助,如:

 

對於代碼:

opt.add_option('--run',
               action="store_true",
               dest="is_run",
               default=False,
               help="run the scripts")

--run 表示參數名

action表示將參數值如何處理,常用的有store/store_true/store_false,store即字面意思,store_true即將True作為參數值傳遞給參數,store_false將False作為參數值傳遞給參數

dest表示命令行參數解析后的參數名,

上面代碼中--run作為命令行參數傳遞進來,由於action為store_true,因此參數值為True,解析后的參數名為is_run,通過(options, args) = opt.parse_args() 賦值后,便可以使用options.is_run來放問參數值。

 

更多幫助:https://docs.python.org/2/library/optparse.html

##========================================================##

對於參數較多或者參數值較大的情況,個人還是比較喜歡使用參數配置文件來實現,簡單而且方便編輯,如創建一個run_config.py文件:

# -*- coding:utf8 -*-


# run config
class RunConfig(object):
    is_run = True
    show_status = 1
    host_ip = "192.167.1.1"
    run_scripts = """
SELECT *
FROM TB001
WHERE ID >1000
AND C1<300
"""

然后在其他文件中訪問:

# -*- coding:utf8 -*-
from run_config import RunConfig


def main():
    print("is_run:{0},  host_ip:{1}".format(RunConfig.is_run,RunConfig.host_ip))
    print("run_scripts:{0}".format(RunConfig.run_scripts))


if __name__ == '__main__':
    main()

簡單粗暴,沒那么麻煩,土豹子的做法哈!

 

##===================================================##

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM