前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之getopt模块

Python之getopt模块

作者头像
全栈程序员站长
发布2022-06-30 19:11:39
3240
发布2022-06-30 19:11:39
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。第一步很简单,只需要: import getopt, sys 第二步处理方法如下(以Python 手册上的例子为例):

代码语言:javascript
复制
try:  
    opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])  
except getopt.GetoptError:  
    # print help information and exit

1. 处理所使用的函数叫getopt() ,因为是直接使用import 导入的getopt 模块,所以要加上限定getopt 才可以。 2. 使用sys.argv[1:] 过滤掉第一个参数(它是执行脚本的名字,不应算作参数的一部分)。 3. 使用短格式分析串”ho:” 。当一个选项只是表示开关状态时,即后面不带附加参数时,在分析串中写入选项字符。当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个”:” 号 。所以”ho:” 就表示”h” 是一个开关选项;”o:” 则表示后面应该带一个参数。 4. 使用长格式分析串列表:[“help”, “output=”] 。长格式串也可以有开关状态,即后面不跟”=” 号。如果跟一个等号则表示后面还应有一个参数 。这个长格式表示”help” 是一个开关选项;”output=” 则表示后面应该带一个参数。 5. 调用getopt 函数。函数返回两个列表:opts 和args 。opts 为分析出的格式信息。args 为不属于格式信息的剩余的命令行参数。opts 是一个两元组的列表。每个元素为:( 选项串, 附加参数) 。如果没有附加参数则为空串” 。 6. 整个过程使用异常来包含,这样当分析出错时,就可以打印出使用信息来通知用户如何使用这个程序。 如上面解释的一个命令行例子为: ‘-h -o file –help –output=out file1 file2’ 在分析完成后,opts 应该是: [(‘-h’, ”), (‘-o’, ‘file’), (‘–help’, ”), (‘–output’, ‘out’)] 而args 则为: [‘file1’, ‘file2’] 第三步主要是对分析出的参数进行判断是否存在,然后再进一步处理。主要的处理模式为:

代码语言:javascript
复制
for o, a in opts:  
    if o in ("-h", "--help"):  
        usage()  
        sys.exit()  
    if o in ("-o", "--output"):  
        output = a 

使用一个循环,每次从opts 中取出一个两元组,赋给两个变量。o 保存选项参数,a 为附加参数。接着对取出的选项参数进行处理。

实践:

代码语言:javascript
复制
qixuan@ubuntu:~/qixuan02$ vi 2.py
  3 import sys;  
  4 import getopt;  
  5   
  6 def usage():  
  7     print("Usage:%s [-a|-o|-c] [--help|--output] args...." %Dsys.argv[0]);
  8 
  9 
 10 if "__main__" == __name__:
 11     #lsArgs = [""];  
 12       
 13     try:
 14         opts,args = getopt.getopt(sys.argv[1:], "ao:c", ["help", "output="]);
 15 
 16         print("============ opts ==================");
 17         print(opts);
 18 
 19         print("============ args ==================");
 20         print(args);
 21 
 22         #check all param  
 23         for opt,arg in opts:
 24             if opt in ("-h", "--help"):
 25                 usage();
 26                 sys.exit(1);
 27             elif opt in ("-t", "--test"):
 28                 print("for test option");
 29             else:
 30                 print("%s  ==> %s" %(opt, arg));
 31 
 32     except getopt.GetoptError:
 33         print("getopt error!");
 34         usage();
 35         sys.exit(1);
"2.py" [New] 35L, 945C written                                                                       
qixuan@ubuntu:~/qixuan02$ python 2.py -a -oaaa -caa --output=out file1 t file2 -d
============ opts ==================
[('-a', ''), ('-o', 'aaa'), ('-c', ''), ('-a', ''), ('-a', ''), ('--output', 'out')]
============ args ==================
['file1', 't', 'file2', '-d']
-a  ==> 
-o  ==> aaa
-c  ==> 
-a  ==> 
-a  ==> 
--output  ==> out
qixuan@ubuntu:~/qixuan02$

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/132174.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档