3

【Python】optparse

 3 years ago
source link: https://www.guofei.site/2021/05/08/optparse.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【Python】optparse

2021年05月08日

Author: Guofei

文章归类: Python语法 ,文章编号: 1206


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2021/05/08/optparse.html

Edit
# tst_optparse.py

# 1. 键值对的形式:
# python tst_optparse.py -f filename1
parser.add_option('-f', '--file', dest='filename', help='a file name')
# dst: 存到哪个变量里面,例子是存到 opt.filename 里面

# 2. 单一键的形式
# python tst_optparse.py -v
parser.add_option('-v', '--verbose', dest='is_verbose', action='store_const', const='yes', help='Is it process verbosely?')
# 如果有 -v,那么就 opts.is_verbose='yes',否则是 None

# 定义默认,如果不定义默认,默认就是 None
parser.set_default('filename', 'default_filename')

# 解析
(opts, args) = parser.parse_args()
# 这个解析可以有入参,
# 例如 (opts, args) = parser.parse_args(['-v', '-f', 'my_file'])

opts.filename # 返回 filename1
args # list,额外“找不到成对匹配的”,放到 args里面
python tst_optparse.py -h
python tst_optparse.py -help
python tst_optparse.py --help

您的支持将鼓励我继续创作!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK