python getopterror_python3 getopt用法

本文介绍了Python中getopt模块的使用,用于解析命令行参数。讲解了短格式和长格式参数的区别,以及如何处理带值和不带值的参数。通过示例解释了getopt.getopt()函数的参数含义,并展示了正确和错误的使用方式。
摘要由CSDN通过智能技术生成

python channel_builder.py -s /Users/graypn/ -d /Users/graypn/Documents -m 7 --out=report/xx.html

参数也分长格式和短格式

短格式:-s

长格式:--source

opts, args = getopt.getopt(sys.argv[1:], "hs:d:m:v:p:c:",

["help", "src=", "dst=", "major=", "version=", "platform=", "channels="])

这个 opts 是一个字典类型,getopt.getopt(x,y,z) x函数第一个传入参sys.argv[1:],y第二个传段short短数名"hs:d:m:v:p:c:",z第三个是long长参数名["help", "src=", "dst=", "major=", "version=", "platform=", "channels="]

short 用法就是 python test.py -h 111

long用法可以2种 --out=res/tt.html

或者直接 --out res/tt.html

关于第二个参数初学者会很困惑这啥意思:

其实是这样的单独一个字母表示该参数不带值,一个字母加个:比如p:表示该参数后面带值,"hf:-v"也可以写成'-h-f:-v',到底什么意思呢:

55ce3a47ab878dc724369ba89300539d.png

C:\Users\Administrator\PycharmProjects\checkTest\src>python xx.py -h

this is --help

C:\Users\Administrator\PycharmProjects\checkTest\src>python xx.py -f

Traceback (most recent call last):

File "xx.py", line 22, in

opts, args = getopt.getopt(sys.argv[1:], '-hf:-v', ['help', 'filename=', 'version'])

File "C:\Python37\lib\getopt.py", line 95, in getopt

opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])

File "C:\Python37\lib\getopt.py", line 199, in do_shorts

opt)

getopt.GetoptError: option -f requires argument

C:\Users\Administrator\PycharmProjects\checkTest\src>python xx.py -h

this is --help

C:\Users\Administrator\PycharmProjects\checkTest\src>python xx.py -f=aaaa.txt

[*] Filename is =aaaa.txt

意思就是你短参数不需要给我指定值,给我我也没发接受处理比如1000短参数给的值1000也没用,长参数是你必须给我值我才可以进行传参

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值