Python命令列引數解析Demo

2021-08-18 10:11:08 字數 3159 閱讀 9521

文章** python–命令列引數解析demo

寫沒有操作介面的程式時,最討厭的就是引數解析問題,尤其是很多引數那種,下面是乙個小demo,拿出來與各位分享:

# -*- coding:utf8 -*-

import os

import datetime

import sys

from optparse import optionparser

defget_user_paras

():try:

opt = optionparser()

opt.add_option('--host_ip',

dest='host_ip',

type=str,

help='the ip of the check host')

opt.add_option('--run',

action="store_true",

dest="is_run",

default=false,

help="run the scripts")

opt.add_option('--view',

action="store_false",

dest="is_run",

default=false,

help="only view but not run the scripts")

opt.add_option('--show_type',

dest="show_type",

type=int,

default=0,

help="0 or 1, 0 only show the ****** data, 1 show the full data")

(options, args) = opt.parse_args()

is_valid_paras = true

error_messages =

host_ip = options.host_ip

is_run = options.is_run

show_type = options.show_type

ifnot host_ip:

is_valid_paras = false

if show_type not

in [0, 1]:

is_valid_paras = false

if is_valid_paras:

user_paras =

return user_paras

else:

for error_message in error_messages:

print(error_message)

opt.print_help()

return

none

except exception as ex:

print("exception :".format(str(ex)))

return

none

defmain

(): user_paras = get_user_paras()

if user_paras is

none:

sys.exit(0)

info = "host_ip:, is_run:, show_type:"

info = info.format(user_paras["host_ip"],

user_paras["is_run"],

user_paras["show_type"])

print(info)

if __name__ == '__main__':

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來放問引數值。

對於引數較多或者引數值較大的情況,個人還是比較喜歡使用引數配置檔案來實現,簡單而且方便編輯,如建立乙個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

defmain

(): print("is_run:, host_ip:".format(runconfig.is_run,runconfig.host_ip))

print("run_scripts:".format(runconfig.run_scripts))

if __name__ == '__main__':

main()

python解析命令列引數

使用乙個先進的模組名為argparse,跟unix程式的命令列引數很像。直接對code做個筆記 import sys import argparse def main args print first name directory s args.first name print first para...

解析命令列引數

include include include include int make argv const char astr,const char delimiters,char argvp void free argv char argvp int main int argc,char argv i...

Python的命令列引數解析

命令列引數解析在程式語言中基本都會碰到,python中內建了乙個用於命令項選項與引數解析的模組argparse。下面主要介紹兩種解析python命令列引數的方式。解析python中命令列引數的最傳統的方法是通過sys.argv。demo如下 usr env python python coding ...