首页 文章 精选 留言 我的

精选列表

搜索[博客系统],共10000篇文章
优秀的个人博客,低调大师

[雪峰磁针石博客]python经典面试题:列表和元组有什么异同?

python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 列表和元组是Python中最常用的两种数据结构,字典是第三种。 相同点: 都是序列 都可以存储任何数据类型 可以通过索引访问 语法差异 使用方括号[]创建列表,而使用括号()创建元组。 请看以下示例: >>> l = ["https://china-testing.github.io/", "https://www.oscobo.com/"] >>> t = ("https://china-testing.github.io/", "https://www.oscobo.com/") >>> print(l) ['https://china-testing.github.io/', 'https://www.oscobo.com/'] >>> print(t) ('https://china-testing.github.io/', 'https://www.oscobo.com/') >>> print(type(l)) <class 'list'> >>> print(type(t)) <class 'tuple'> 是否可变 列表是可变的,而元组是不可变的,这标志着两者之间的关键差异。 我们可以修改列表的值,但是不修改元组的值。 由于列表是可变的,我们不能将列表用作字典中的key。 但可以使用元组作为字典key。 >>> l[1] = "https://www.jianshu.com/u/69f40328d4f0" >>> l ['https://china-testing.github.io/', 'https://www.jianshu.com/u/69f40328d4f0'] >>> t[1] = "https://www.jianshu.com/u/69f40328d4f0" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment 重用与拷贝 元组无法复制。 原因是元组是不可变的。 如果运行tuple(tuple_name)将返回自己。 >>> copy_t = tuple(t) >>> print(t is copy_t) True >>> copy_l = list(l) >>> print(l is copy_l) False 参考资料 讨论 项目实战讨论QQ群630011153 144081101 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 python工具书籍下载-持续更新 大小差异 Python将低开销的较大的块分配给元组,因为它们是不可变的。 对于列表则分配小内存块。 与列表相比,元组的内存更小。 当你拥有大量元素时,元组比列表快。列表的长度是可变的。 >>> l = ["https://china-testing.github.io/", "https://www.oscobo.com/"] >>> t = ("https://china-testing.github.io/", "https://www.oscobo.com/") >>> print(l.__sizeof__()) 56 >>> print(t.__sizeof__()) 40 同构与异构 习惯上元组多用于用于存储异构元素,异构元素即不同数据类型的元素,比如(ip,port)。 另一方面,列表用于存储异构元素,这些元素属于相同类型的元素,比如[int1,in2,in3]。

优秀的个人博客,低调大师

[雪峰磁针石博客]自动化测试框架pytest教程1-快速入门

第1章 快速入门 什么是pytest? pytest是强大的Python测试工具,它可以用于所有类型和级别的软件测试。 Pytest可以被开发团队,QA团队,独立测试小组,实践TDD的个人和开放源代码项目。实际上,整个互联网上的项目都是从unittest或者nose转向pytest,包括Mozilla和Dropbox。为什么?因为pytest提供强大的功能,如'断言'重写,第三方插件模型,强大但简单的fixture模型。 pytest是软件测试框架,这意味着pytest是命令行工具。它会自动找到你写的测试,运行测试并报告结果。可编写插件或安装第三方来扩展插件。它可以用来测试Python发行版。它很容易与其他工具对接,如持续集成和网页自动化。 Pytest脱颖而出的原因: 简单 易读 用assert来测试失败,而不是self.assertEqua

优秀的个人博客,低调大师

[雪峰磁针石博客]python工具库介绍-dubbo:通过telnet接口访问dubbo服务

## 简介 dubbo服务发布之后,我们可以利用telnet命令进行调试、管理。更多资料参见 [Telnet命令参考手册](http://alibaba.github.io/dubbo-doc-static/Telnet+Command+Reference-zh-showComments=true&showCommentArea=true.htm) telnet 调用示例: ```python $ telnet 172.17.103.110 9097 Trying 172.17.103.110... Connected to 172.17.103.110. Escape character is '^]'. dubbo>ls com.oppo.sso.service.onekey.IOnekeyRegister register dubbo>invoke com.oppo.sso.service.onekey.IOnekeyRegister.register({"applicationKey":"mac","imei":"","mobile":"13244448888","createIP":"127.0.0.1","createBy":"172.17.0.1"}) {"configCountry":null,"userIdLong":0,"appPackage":null,"appVersion":null,"accountName":null,"romVersion":null,"resultCode":3001,"thirdStatus":null,"registerType":0,"sendChannel":null,"operator":null,"manufacturer":null,"password":null,"osVersion":null,"lock":false,"model":null,"visitorLocked":false,"OK":false,"brand":null,"email":null,"createIP":null,"deny":false,"encryptEmail":null,"sessionKey":null,"thirdId":null,"passwordOriginal":null,"mobile":null,"applicationKey":null,"thirdpartyOk":false,"userAgent":null,"userName":null,"resultDesc":"应用不存在","userId":0,"encryptMobile":null,"emailStatus":null,"createBy":null,"freePwd":false,"changeTimes":0,"createTime":null,"mobileStatus":null,"oldLock":false,"codeTimeout":null,"lastUpdate":null,"imei":null,"sessionTimeout":0,"sdkVersion":null,"networkID":0,"status":null} elapsed: 98 ms. dubbo> ``` ## Python实现 源码: ```python """ Name: dubbo.py Tesed in python3.5 """ import json import telnetlib import socket class Dubbo(telnetlib.Telnet): prompt = 'dubbo>' coding = 'utf-8' def __init__(self, host=None, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): super().__init__(host, port) self.write(b'\n') def command(self, flag, str_=""): data = self.read_until(flag.encode()) self.write(str_.encode() + b"\n") return data def invoke(self, service_name, method_name, arg): command_str = "invoke {0}.{1}({2})".format( service_name, method_name, json.dumps(arg)) self.command(Dubbo.prompt, command_str) data = self.command(Dubbo.prompt, "") data = json.loads(data.decode(Dubbo.coding, errors='ignore').split('\n')[0].strip()) return data if __name__ == '__main__': conn = Dubbo('172.17.103.110', 9097) json_data = { "applicationKey":"mac", "imei":"", "mobile":"13244448888", "createIP":"127.0.0.1", "createBy":"172.17.0.1" } result = conn.invoke( "com.oppo.sso.service.onekey.IOnekeyRegister", "register", json_data ) print(result) ``` 执行结果: ```python # python3 dubbo.py {'manufacturer': None, 'applicationKey': None, 'OK': False, 'codeTimeout': None, 'password': None, 'encryptEmail': None, 'passwordOriginal': None, 'thirdId': None, 'emailStatus': None, 'freePwd': False, 'sessionTimeout': 0, 'createTime': None, 'osVersion': None, 'lastUpdate': None, 'email': None, 'sdkVersion': None, 'registerType': 0, 'sendChannel': None, 'visitorLocked': False, 'createIP': None, 'thirdStatus': None, 'encryptMobile': None, 'networkID': 0, 'resultCode': 3001, 'brand': None, 'changeTimes': 0, 'userAgent': None, 'imei': None, 'operator': None, 'romVersion': None, 'model': None, 'lock': False, 'sessionKey': None, 'configCountry': None, 'deny': False, 'userIdLong': 0, 'resultDesc': '应用不存在', 'status': None, 'createBy': None, 'thirdpartyOk': False, 'appPackage': None, 'appVersion': None, 'accountName': None, 'userId': 0, 'oldLock': False, 'userName': None, 'mobile': None, 'mobileStatus': None} ``` 更复杂的例子。 源码: ```python import json import telnetlib import socket class Dubbo(telnetlib.Telnet): prompt = 'dubbo>' coding = 'gbk' def __init__(self, host=None, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): super().__init__(host, port) self.write(b'\n') def command(self, flag, str_=""): data = self.read_until(flag.encode()) self.write(str_.encode() + b"\n") return data def invoke(self, service_name, method_name, arg): command_str = "invoke {0}.{1}({2})".format( service_name, method_name, json.dumps(arg)) self.command(Dubbo.prompt, command_str) data = self.command(Dubbo.prompt, "") data = json.loads(data.decode(Dubbo.coding, errors='ignore').split('\n')[0].strip()) return data if __name__ == '__main__': conn = Dubbo('183.131.22.99', 21881) content = { "sign": "FKeKnMEPybHujjBTzz11BrulB5av7pLhJpk=", "partnerOrder": "0511e0d38f334319a96920fa02be02a7", "productDesc": "hello", "paySuccessTime": "2016-08-25 18:33:04", "price": "1", "count": "1", "attach": "from_pay_demo", "date": "20160825", } content_json = json.dumps(content).replace('"', '\\"') json_data = { "requestId": "0511e0d38f334319a96920fa02be02a7", "reqUrl": 'http://www.oppo.com', "httpReqType": "POST", "headerMap": None, "reqContent": content_json, "appId": "10001", "productName": "test", "timeStamp": "1472121184957", "partnerId": "2031", "signType": "MD5", "sign": "23B621FBBF887373C65E553C2222258F", "successResult": "OK", } result = conn.invoke( "com.oppo.pay.notify.api.facade.NotifyApplyService", "httpNotify", json_data ) print(result) ``` 执行结果: ```python $ python3 dubbo.py {'resMsg': 'ǩ', 'data': None, 'errorDetail': 'sign check fail!', 'resCode': '100003', 'success': False} ``` ## 待改进 * 进行多个项目的实验,增加异常处理 ## 参考资料 - [本文最新版本地址](https://china-testing.github.io/python3_lib_dubbo.html) - [本文涉及的python测试开发库](https://github.com/china-testing/python-api-tesing) 谢谢点赞! - [本文相关海量书籍下载](https://github.com/china-testing/python-api-tesing/blob/master/books.md) - [本文源码地址](https://github.com/china-testing/python-api-tesing/tree/master/python3_libraries/_dubbo)

优秀的个人博客,低调大师

[雪峰磁针石博客]python库介绍-argparse: 命令行选项及参数解析

快速入门 argparse是一个完整的参数处理库。参数可以根据add_argument()的action选项触发不同action。支持的action有存储参数(单个,或作为列表的一部分);存储常量的值(对布尔开关true/false有特殊处理)。默认动作是存储参数值。支持type(指定存储类型)和dest(指定存储变量)等参数。 然后使用函数parse_args()进行参数解析,这个函数的输入默认是sys.argv[1:],也可以使用其他字符串列表。选项使用GNU/POSIX语法处理,可以混合选项和参数值。parse_args的返回值是一个包含命令参数的Namespace。所有参数以属性的形式存在,比如args.myoption。 下面是一个简单的示例:argparse_short.py import argparse parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print(parser.parse_args(['-a', '-bval', '-c', '3'])) 执行结果: $ python3 argparse_short.py Namespace(a=True, b='val', c=3) 长参数argparse_long.py import argparse parser = argparse.ArgumentParser( description='Example with long option names', ) parser.add_argument('--noarg', action="store_true", default=False) parser.add_argument('--witharg', action="store", dest="witharg") parser.add_argument('--witharg2', action="store", dest="witharg2", type=int) print( parser.parse_args( ['--noarg', '--witharg', 'val', '--witharg2=3'] ) ) 执行结果 $ python3 argparse_long.py Namespace(noarg=True, witharg='val', witharg2=3) 混合可选和必选参数:argparse_arguments.py import argparse parser = argparse.ArgumentParser( description='Example with nonoptional arguments', ) parser.add_argument('count', action="store", type=int) parser.add_argument('units', action="store") print(parser.parse_args()) 执行结果 $ python3 argparse_arguments.py 3 inches Namespace(count=3, units='inches') $ python3 argparse_arguments.py some inches usage: argparse_arguments.py [-h] count units argparse_arguments.py: error: argument count: invalid int value: 'some' $ python3 argparse_arguments.py usage: argparse_arguments.py [-h] count units argparse_arguments.py: error: the following arguments are required: count, units 参数action有: store:默认action模式,存储值到指定变量。store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。store_true / store_false:布尔开关。可以2个参数对应一个变量。append:存储值到列表,该参数可以重复使用。append_const:存储值到列表,存储值在参数的const部分指定。version 输出版本信息然后退出。 下面是各种action的示例:argparse_action.py import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', action='store', dest='simple_value', help='Store a simple value') parser.add_argument('-c', action='store_const', dest='constant_value', const='value-to-store', help='Store a constant value') parser.add_argument('-t', action='store_true', default=False, dest='boolean_t', help='Set a switch to true') parser.add_argument('-f', action='store_false', default=True, dest='boolean_f', help='Set a switch to false') parser.add_argument('-a', action='append', dest='collection', default=[], help='Add repeated values to a list') parser.add_argument('-A', action='append_const', dest='const_collection', const='value-1-to-append', default=[], help='Add different values to list') parser.add_argument('-B', action='append_const', dest='const_collection', const='value-2-to-append', help='Add different values to list') parser.add_argument('--version', action='version', version='%(prog)s 1.0') results = parser.parse_args() print('simple_value = {!r}'.format(results.simple_value)) print('constant_value = {!r}'.format(results.constant_value)) print('boolean_t = {!r}'.format(results.boolean_t)) print('boolean_f = {!r}'.format(results.boolean_f)) print('collection = {!r}'.format(results.collection)) print('const_collection = {!r}'.format(results.const_collection)) 执行结果如下,注意'simple_value'等被自动化转化为大写 $ python3 argparse_action.py -h usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f] [-a COLLECTION] [-A] [-B] [--version] optional arguments: -h, --help show this help message and exit -s SIMPLE_VALUE Store a simple value -c Store a constant value -t Set a switch to true -f Set a switch to false -a COLLECTION Add repeated values to a list -A Add different values to list -B Add different values to list --version show program's version number and exit $ python3 argparse_action.py -s value simple_value = 'value' constant_value = None boolean_t = False boolean_f = True collection = [] const_collection = [] $ python3 argparse_action.py -c simple_value = None constant_value = 'value-to-store' boolean_t = False boolean_f = True collection = [] const_collection = [] $ python3 argparse_action.py -t simple_value = None constant_value = None boolean_t = True boolean_f = True collection = [] const_collection = [] $ python3 argparse_action.py -f simple_value = None constant_value = None boolean_t = False boolean_f = False collection = [] const_collection = [] $ python3 argparse_action.py -a one -a two -a three simple_value = None constant_value = None boolean_t = False boolean_f = True collection = ['one', 'two', 'three'] const_collection = [] $ python3 argparse_action.py -B -A simple_value = None constant_value = None boolean_t = False boolean_f = True collection = [] const_collection = ['value-2-to-append', 'value-1-to-append'] $ python3 argparse_action.py --version argparse_action.py 1.0 可选前缀 ArgumentParser函数中的选项prefix_chars可以指定前缀。默认使用UNIX风格,命令行使用‘-’作为前缀。可以使用windows的’/’或者其他符号。 argparse_prefix_chars.py import argparse parser = argparse.ArgumentParser( description='Change the option prefix characters', prefix_chars='-+/', ) parser.add_argument('-a', action="store_false", default=None, help='Turn A off', ) parser.add_argument('+a', action="store_true", default=None, help='Turn A on', ) parser.add_argument('//noarg', '++noarg', action="store_true", default=False) print(parser.parse_args()) 执行结果 $ python3 argparse_prefix_chars.py -h usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg] Change the option prefix characters optional arguments: -h, --help show this help message and exit -a Turn A off +a Turn A on //noarg, ++noarg $ python3 argparse_prefix_chars.py +a Namespace(a=True, noarg=False) $ python3 argparse_prefix_chars.py -a Namespace(a=False, noarg=False) $ python3 argparse_prefix_chars.py //noarg Namespace(a=None, noarg=True) $ python3 argparse_prefix_chars.py ++noarg Namespace(a=None, noarg=True) $ python3 argparse_prefix_chars.py --noarg usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg] argparse_prefix_chars.py: error: unrecognized arguments: --noarg 处理配置文件中的参数 argparse_with_shlex.py import argparse from configparser import ConfigParser import shlex parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) config = ConfigParser() config.read('argparse_with_shlex.ini') config_value = config.get('cli', 'options') print('Config :', config_value) argument_list = shlex.split(config_value) print('Arg List:', argument_list) print('Results :', parser.parse_args(argument_list)) 其中argparse_with_shlex.ini文件的内容如下: [cli] options = -a -b 2 执行结果 $ python3 argparse_with_shlex.py Config : -a -b 2 Arg List: ['-a', '-b', '2'] Results : Namespace(a=True, b='2', c=None) 上面例子使用了ConfigParser来读取配置,再用shlex来切割参数。也可以通过fromfile_prefix_chars 告知argparse输入参数为文件。 argparse_fromfile_prefix_chars.py import argparse import shlex parser = argparse.ArgumentParser(description='Short sample app', fromfile_prefix_chars='@', ) parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print(parser.parse_args(['@argparse_fromfile_prefix_chars.txt'])) argparse_fromfile_prefix_chars.txt -a -b 2 执行结果 $ python3 argparse_fromfile_prefix_chars.py Namespace(a=True, b='2', c=None) 帮助 自动生成 Argparse会自动生成的帮助和版本信息。ArgumentParser的add_help参数控制帮助的生成,默认是开启。 argparse_with_help.py import argparse parser = argparse.ArgumentParser(add_help=True) parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print(parser.parse_args()) 下例就关闭帮助: argparse_without_help.py import argparse parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print(parser.parse_args()) 执行结果 $ python argparse_with_help.py -h usage: argparse_with_help.py [-h] [-a] [-b B] [-c C] optional arguments: -h, --help show this help message and exit -a -b B -c C $ python argparse_without_help.py -h usage: argparse_without_help.py [-a] [-b B] [-c C] argparse_without_help.py: error: unrecognized arguments: -h 自定义帮助 argparse_custom_help.py import argparse parser = argparse.ArgumentParser(add_help=True) parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) print('print_usage output:') parser.print_usage() print() print('print_help output:') parser.print_help() 执行结果 $ python3 argparse_custom_help.py print_usage output: usage: argparse_custom_help.py [-h] [-a] [-b B] [-c C] print_help output: usage: argparse_custom_help.py [-h] [-a] [-b B] [-c C] optional arguments: -h, --help show this help message and exit -a -b B -c C argparse_raw_description_help_formatter.py import argparse parser = argparse.ArgumentParser( add_help=True, formatter_class=argparse.RawDescriptionHelpFormatter, description=""" description not wrapped""", epilog=""" epilog not wrapped""", ) parser.add_argument( '-a', action="store_true", help="""argument help is wrapped """, ) parser.print_help() 执行结果 $ python3 argparse_raw_description_help_formatter.py usage: argparse_raw_description_help_formatter.py [-h] [-a] description not wrapped optional arguments: -h, --help show this help message and exit -a argument help is wrapped epilog not wrapped argparse_raw_text_help_formatter.py import argparse parser = argparse.ArgumentParser( add_help=True, formatter_class=argparse.RawTextHelpFormatter, description=""" description not wrapped""", epilog=""" epilog not wrapped""", ) parser.add_argument( '-a', action="store_true", help="""argument help is not wrapped """, ) parser.print_help() 执行结果 $ python3 argparse_raw_text_help_formatter.py usage: argparse_raw_text_help_formatter.py [-h] [-a] description not wrapped optional arguments: -h, --help show this help message and exit -a argument help is not wrapped epilog not wrapped argparse_metavar_type_help_formatter.py import argparse parser = argparse.ArgumentParser( add_help=True, formatter_class=argparse.MetavarTypeHelpFormatter, ) parser.add_argument('-i', type=int, dest='notshown1') parser.add_argument('-f', type=float, dest='notshown2') parser.print_help() 执行结果 $ python3 argparse_metavar_type_help_formatter.py usage: argparse_metavar_type_help_formatter.py [-h] [-i int] [-f float] optional arguments: -h, --help show this help message and exit -i int -f float 组织解析器 公共解析器:通过父子类来实现。 见argparse_parent_base.py: import argparse parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--user', action="store") parser.add_argument('--password', action="store") argparse_uses_parent.py import argparse import argparse_parent_base parser = argparse.ArgumentParser( parents=[argparse_parent_base.parser], ) parser.add_argument('--local-arg', action="store_true", default=False) print(parser.parse_args()) 注意:父类关闭了help。子类却默认开启了help。执行结果: $ python3 argparse_uses_parent.py -h usage: argparse_uses_parent.py [-h] [--user USER] [--password PASSWORD] [--local-arg] optional arguments: -h, --help show this help message and exit --user USER --password PASSWORD --local-arg 参数冲突 argparse_conflict_handler_resolve.py import argparse parser = argparse.ArgumentParser(conflict_handler='resolve') parser.add_argument('-a', action="store") parser.add_argument('-b', action="store", help='Short alone') parser.add_argument('--long-b', '-b', action="store", help='Long and short together') print(parser.parse_args(['-h'])) 执行结果 $ python3 argparse_conflict_handler_resolve.py usage: argparse_conflict_handler_resolve.py [-h] [-a A] [--long-b LONG_B] optional arguments: -h, --help show this help message and exit -a A --long-b LONG_B, -b LONG_B Long and short together argparse_conflict_handler_resolve2.py、 import argparse parser = argparse.ArgumentParser(conflict_handler='resolve') parser.add_argument('-a', action="store") parser.add_argument('--long-b', '-b', action="store", help='Long and short together') parser.add_argument('-b', action="store", help='Short alone') print(parser.parse_args(['-h'])) 执行结果 $ python3 argparse_conflict_handler_resolve2.py usage: argparse_conflict_handler_resolve2.py [-h] [-a A] [--long-b LONG_B] [-b B] optional arguments: -h, --help show this help message and exit -a A --long-b LONG_B Long and short together -b B Short alone 参数分组 默认有可选参数和必选参数组。 argparse_default_grouping.py import argparse parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('--optional', action="store_true", default=False) parser.add_argument('positional', action="store") print(parser.parse_args()) 执行结果 $ python3 argparse_default_grouping.py -h usage: argparse_default_grouping.py [-h] [--optional] positional Short sample app positional arguments: positional optional arguments: -h, --help show this help message and exit --optional 前面的用户名和密码就可以分组: argparse_parent_with_group.py import argparse parser = argparse.ArgumentParser(add_help=False) group = parser.add_argument_group('authentication') group.add_argument('--user', action="store") group.add_argument('--password', action="store") argparse_uses_parent_with_group.py import argparse import argparse_parent_with_group parser = argparse.ArgumentParser( parents=[argparse_parent_with_group.parser], ) parser.add_argument('--local-arg', action="store_true", default=False) print(parser.parse_args()) 执行结果 $ python3 argparse_uses_parent_with_group.py -h usage: argparse_uses_parent_with_group.py [-h] [--user USER] [--password PASSWORD] [--local-arg] optional arguments: -h, --help show this help message and exit --local-arg authentication: --user USER --password PASSWORD 互斥选项 使用add_mutually_exclusive_group()可以添加互斥选项: argparse_mutually_exclusive.py import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-a', action='store_true') group.add_argument('-b', action='store_true') print(parser.parse_args()) 执行结果 $ python3 argparse_mutually_exclusive.py -h usage: argparse_mutually_exclusive.py [-h] [-a | -b] optional arguments: -h, --help show this help message and exit -a -b $ python3 argparse_mutually_exclusive.py -a Namespace(a=True, b=False) $ python3 argparse_mutually_exclusive.py -b Namespace(a=False, b=True) $ python3 argparse_mutually_exclusive.py -a -b usage: argparse_mutually_exclusive.py [-h] [-a | -b] argparse_mutually_exclusive.py: error: argument -b: not allowed with argument -a 嵌套解析 argparse_subparsers.py import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='commands') # A list command list_parser = subparsers.add_parser( 'list', help='List contents') list_parser.add_argument( 'dirname', action='store', help='Directory to list') # A create command create_parser = subparsers.add_parser( 'create', help='Create a directory') create_parser.add_argument( 'dirname', action='store', help='New directory to create') create_parser.add_argument( '--read-only', default=False, action='store_true', help='Set permissions to prevent writing to the directory', ) # A delete command delete_parser = subparsers.add_parser( 'delete', help='Remove a directory') delete_parser.add_argument( 'dirname', action='store', help='The directory to remove') delete_parser.add_argument( '--recursive', '-r', default=False, action='store_true', help='Remove the contents of the directory, too', ) print(parser.parse_args()) 执行结果 $ python3 argparse_subparsers.py -h usage: argparse_subparsers.py [-h] {list,create,delete} ... positional arguments: {list,create,delete} commands list List contents create Create a directory delete Remove a directory optional arguments: -h, --help show this help message and exit $ python3 argparse_subparsers.py create -h usage: argparse_subparsers.py create [-h] [--read-only] dirname positional arguments: dirname New directory to create optional arguments: -h, --help show this help message and exit --read-only Set permissions to prevent writing to the directo ry $ python3 argparse_subparsers.py delete -r foo Namespace(dirname='foo', recursive=True) 高级参数处理 可变参数:数字N代表N的参数,?0或者1个参数。*0或者多个参数。+1或者多个参数。 argparse_nargs.py import argparse parser = argparse.ArgumentParser() parser.add_argument('--three', nargs=3) parser.add_argument('--optional', nargs='?') parser.add_argument('--all', nargs='*', dest='all') parser.add_argument('--one-or-more', nargs='+') print(parser.parse_args()) 执行结果 $ python3 argparse_nargs.py -h usage: argparse_nargs.py [-h] [--three THREE THREE THREE] [--optional [OPTIONAL]] [--all [ALL [ALL ...]]] [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]] optional arguments: -h, --help show this help message and exit --three THREE THREE THREE --optional [OPTIONAL] --all [ALL [ALL ...]] --one-or-more ONE_OR_MORE [ONE_OR_MORE ...] $ python3 argparse_nargs.py Namespace(all=None, one_or_more=None, optional=None, three=None) $ python3 argparse_nargs.py --three usage: argparse_nargs.py [-h] [--three THREE THREE THREE] [--optional [OPTIONAL]] [--all [ALL [ALL ...]]] [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]] argparse_nargs.py: error: argument --three: expected 3 argument(s) $ python3 argparse_nargs.py --three a b c Namespace(all=None, one_or_more=None, optional=None, three=['a', 'b', 'c']) $ python3 argparse_nargs.py --optional Namespace(all=None, one_or_more=None, optional=None, three=None) $ python3 argparse_nargs.py --optional with_value Namespace(all=None, one_or_more=None, optional='with_value', three=None) $ python3 argparse_nargs.py --all with multiple values Namespace(all=['with', 'multiple', 'values'], one_or_more=None, optional=None, three=None) $ python3 argparse_nargs.py --one-or-more with_value Namespace(all=None, one_or_more=['with_value'], optional=None, three=None) $ python3 argparse_nargs.py --one-or-more with multiple values Namespace(all=None, one_or_more=['with', 'multiple', 'values'], optional=None, three=None) $ python3 argparse_nargs.py --one-or-more usage: argparse_nargs.py [-h] [--three THREE THREE THREE] [--optional [OPTIONAL]] [--all [ALL [ALL ...]]] [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]] argparse_nargs.py: error: argument --one-or-more: expected at least one argument 参数类型 argparse_type.py import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', type=int) parser.add_argument('-f', type=float) parser.add_argument('--file', type=open) try: print(parser.parse_args()) except IOError as msg: parser.error(str(msg)) 执行结果 $ python3 argparse_type.py -i 1 Namespace(f=None, file=None, i=1) $ python3 argparse_type.py -f 3.14 Namespace(f=3.14, file=None, i=None) $ python3 argparse_type.py --file argparse_type.py Namespace(f=None, file=<_io.TextIOWrapper name='argparse_type.py' mode='r' encoding='UTF-8'>, i=None) $ python3 argparse_type.py -i a usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE] argparse_type.py: error: argument -i: invalid int value: 'a' $ python3 argparse_type.py -f 3.14.15 usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE] argparse_type.py: error: argument -f: invalid float value: '3.14.15' $ python3 argparse_type.py --file does_not_exist.txt usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE] argparse_type.py: error: [Errno 2] No such file or directory: 'does_not_exist.txt' Choices可以指定参数的选项: argparse_choices.py import argparse parser = argparse.ArgumentParser() parser.add_argument( '--mode', choices=('read-only', 'read-write'), ) print(parser.parse_args()) 执行结果 $ python3 argparse_choices.py -h usage: argparse_choices.py [-h] [--mode {read-only,read-write}] optional arguments: -h, --help show this help message and exit --mode {read-only,read-write} $ python3 argparse_choices.py --mode read-only Namespace(mode='read-only') $ python3 argparse_choices.py --mode invalid usage: argparse_choices.py [-h] [--mode {read-only,read-write}] argparse_choices.py: error: argument --mode: invalid choice: 'invalid' (choose from 'read-only', 'read-write') 文件参数 argparse_FileType.py import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', metavar='in-file', type=argparse.FileType('rt')) parser.add_argument('-o', metavar='out-file', type=argparse.FileType('wt')) try: results = parser.parse_args() print('Input file:', results.i) print('Output file:', results.o) except IOError as msg: parser.error(str(msg)) 执行结果 $ python3 argparse_FileType.py -h usage: argparse_FileType.py [-h] [-i in-file] [-o out-file] optional arguments: -h, --help show this help message and exit -i in-file -o out-file $ python3 argparse_FileType.py -i argparse_FileType.py -o tmp_\ file.txt Input file: <_io.TextIOWrapper name='argparse_FileType.py' mode='rt' encoding='UTF-8'> Output file: <_io.TextIOWrapper name='tmp_file.txt' mode='wt' encoding='UTF-8'> $ python3 argparse_FileType.py -i no_such_file.txt usage: argparse_FileType.py [-h] [-i in-file] [-o out-file] argparse_FileType.py: error: argument -i: can't open 'no_such_file.txt': [Errno 2] No such file or directory: 'no_such_file.txt' 自定义action 自定义action是argparse.Action的子类可以处理add_argument中的参数定义相关的参数,并返回一个可调用对象。构造函数会处理参数定义,仅仅需要处理__call__函数。__call__函数中parser代表解释器,namespace用于返回解释结果,value为要处理的参数,option_string用于触发action(对可选参数,永远是None。 argparse_custom_action.py import argparse class CustomAction(argparse.Action): def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None): argparse.Action.__init__(self, option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar, ) print('Initializing CustomAction') for name, value in sorted(locals().items()): if name == 'self' or value is None: continue print(' {} = {!r}'.format(name, value)) print() return def __call__(self, parser, namespace, values, option_string=None): print('Processing CustomAction for {}'.format(self.dest)) print(' parser = {}'.format(id(parser))) print(' values = {!r}'.format(values)) print(' option_string = {!r}'.format(option_string)) # Do some arbitrary processing of the input values if isinstance(values, list): values = [v.upper() for v in values] else: values = values.upper() # Save the results in the namespace using the destination # variable given to our constructor. setattr(namespace, self.dest, values) print() parser = argparse.ArgumentParser() parser.add_argument('-a', action=CustomAction) parser.add_argument('-m', nargs='*', action=CustomAction) results = parser.parse_args(['-a', 'value', '-m', 'multivalue', 'second']) print(results) 执行结果 $ python3 argparse_custom_action.py Initializing CustomAction dest = 'a' option_strings = ['-a'] required = False Initializing CustomAction dest = 'm' nargs = '*' option_strings = ['-m'] required = False Processing CustomAction for a parser = 4315836992 values = 'value' option_string = '-a' Processing CustomAction for m parser = 4315836992 values = ['multivalue', 'second'] option_string = '-m' Namespace(a='VALUE', m=['MULTIVALUE', 'SECOND']) 参考资料 本文相关书籍下载 紧张整理更新中,讨论 钉钉免费群21745728 qq群144081101 567351477 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 英文参考

优秀的个人博客,低调大师

阿里云服务器怎么安装个人博客?安装wordpress程序,创建LAMP环境?

注册域名比较简单,这里就不讲了,直接到阿里云官网注册就行了。 最近阿里云推出了轻量应用型服务器,有一键配置功能,使用方便,1分钟就可以配置了。 注意,请先到阿里云官网 领取幸运券,除了价格上有很多优惠外,还可以参与抽奖。详见:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=2a7uv47d&utm_source=2a7uv47d 1、登录 阿里云官网,点击:轻量应用服务器,如下图: 2、根据需要选择配置,如下图:(再次提醒一下,购买前请先:领取阿里云幸运券,有很多优惠。)

优秀的个人博客,低调大师

[python作业AI毕业设计博客]Functional Programming For Dummies - 2019 函数式编程傻瓜书

函数式编程范例指南 下载地址:https://itbooks.pipipan.com/fs/18113597-335607573 函数式编程主要用于数学计算,包括人工智能和游戏中使用的算法。这种编程范例使得用于数学计算的算法更容易理解,并为非开发人员提供了一种编码算法的简洁方法。目前市场上的书籍具有陡峭的学习曲线,因为它们大多是由开发人员为开发人员编写的。 本书探讨了纯粹(由Haskell语言表示)和不纯(用Python语言表示)方法之间的差异,为像您一样的读者进行函数式编程。纯方法最适合那些不想创建生产代码但需要完全测试算法并证明它们对同行有用的研究人员。不纯的方法最适合生产环境,因为可以在单个应用程序中混合编码范例以更快地生成结果。函数式编程傻瓜书使用这种双管齐下的方法为您提供一种编码方法的一体化方法,否则很难掌握。 •在编码时学习纯粹和不纯洁•深入了解大多数功能程序员用来推导,分析和证明算法价值的过程•受益于Python和Haskell中提供的示例•收集专家作者的专业知识,该作者迄今已编写了一些市场领先的编程书籍 如果您已准备好按摩数据以了解事物如何以新的方式运作,那么您来对地方了!

优秀的个人博客,低调大师

[雪峰磁针石博客]python标准模块介绍- binascii 二进制和ASCII转换

python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 简介 binascii模块包含很多用来方法来转换二进制和各种ASCII编码的二进制表示法。通常不直接使用这些功能,而是使用封装模块,如uu, base64或binhex。binascii模块包含用C语言编写更快的低级功能,通常为高级模块所使用。 功能:二进制和ASCII转换。 类型:标准模块 相关模块: base64 标准模块。 binhex 标准模块。 uu 标准模块。 quopri 标准模块。 Uu编码 uu编码格式现在已经比较少使用(http://zh.wikipedia.org/wiki/Uuencode),相关函数binascii.a2b_uu(string)和binascii.b2a_uu(data)这里不做介绍。 更多资料参见:http://docs.python.org/2/library/uu.html Binhex编码 Binhex用于Macintosh平台。这里暂不做介绍。相关函数有:binascii.rledecode_hqx(data) ,binascii.rlecode_hqx(data),binascii.b2a_hqx(data) ,binascii.crc_hqx(data, crc)。 更多资料参见: http://docs.python.org/2/library/uu.html Base64编码 binascii.a2b_base64(string):转换的base64数据块为二进制,并返回二进制数据。一次可以传递多行。和base64. b64decode对应。 binascii.b2a_base64(data):转换二进制数据为一行base64编码的ASCII字符。返回字符串包含换行符。根据base64的标准data的长度最大为57。和base64. b64encode对应。 更多资料参见:http://docs.python.org/2/library/base64.html QP码 Quoted-printable,或QP encoding,没有规范的中文译名,可译为“可打印字符引用编码”、“使用可打印字符的编码”。Quoted-printable是使用可打印的 ASCII字符 (如字母、数字与"=")表示各种编码格式下的字符,以便能在7-bit数据通路上传输8-bit数据, 或者更一般地说在非8-bit clean媒体上正确处理数据。这被定义为MIME content transfer encoding,用于e-mail。 QP使用"="开头的转义字符. 一般限制行宽为76,因为有些软件限制了行宽. binascii.a2b_qp(string[, header]):转换引述打印数据块为二进制,并返回二进制数据。多行可以在同一时间被传递。如果可选参数头存在和真实,下划线将被解码为空格。 实际上,QP码是是把’\x00’转换成’=00’,也就是替换’\x’为’=’。 >>> s ='\x00=' >>> s = '=\x00hello' >>> import binascii >>> encoded = binascii.b2a_qp(s) >>> encoded '=3D=00hello' >>> decoded = binascii.a2b_qp(encoded) >>> print decoded =hello >>> print repr(decoded) '=\x00hello' CRC校验和 binascii.crc32(data[, crc]):计算的data 的32位校验和CRC- 32时,crc为初始CRC 。crc32与ZIP文件的校验和一致。 >>> print binascii.crc32("hello world") 222957957 >>> crc = binascii.crc32("hello") >>> crc = binascii.crc32(" world", crc) & 0xffffffff >>> print 'crc32 = 0x%08x' % crc crc32 = 0x0d4a1185 >>> crc 222957957 为了保证跨平台,可以在crc结果上& 0xffffffff。原因如下: Changed in version 2.6: The return value is in the range [-2**31, 2**31-1] regardless of platform. In the past the value would be signed on some platforms and unsigned on others. Use & 0xffffffff on the value if you want it to match Python 3 behavior. Changed in version 3.0: The return value is unsigned and in the range [0, 2**32-1] regardless of platform. 二进制转换 binascii.b2a_hex(data)和binascii.hexlify(data):返回二进制数据的十六进制表示。每个字节被转换成相应的 2位十六进制表示形式。因此,得到的字符串是是原数据长度的两倍。 binascii.a2b_hex(hexstr) 和binascii.unhexlify(hexstr):从十六进制字符串hexstr返回二进制数据。是b2a_hex的逆向操作。 hexstr必须包含偶数个十六进制数字(可以是大写或小写),否则报TypeError。 >>> s = 'hello' >>> b = b2a_hex(s) >>> print b 68656c6c6f >>> a2b_hex(b) 'hello' >>> b = hexlify(s) >>> print b 68656c6c6f >>> unhexlify(b) 'hello' 参考资料 python测试等IT技术支持qq群: 144081101(后期会录制视频存在该群群文件) 591302926 567351477 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 python官方文档:https://docs.python.org/3/library/binascii.html http://effbot.org/librarybook/binascii.htm 其他实例 http://effbot.org/librarybook/binascii.htm 有如下实例: import binascii text = "hello, mrs teal" data = binascii.b2a_base64(text) text = binascii.a2b_base64(data) print text, "<=>", repr(data) data = binascii.b2a_uu(text) text = binascii.a2b_uu(data) print text, "<=>", repr(data) data = binascii.b2a_hqx(text) text = binascii.a2b_hqx(data)[0] print text, "<=>", repr(data) # 2.0 and newer data = binascii.b2a_hex(text) text = binascii.a2b_hex(data) print text, "<=>", repr(data) 执行结果: # python test.py hello, mrs teal <=> 'aGVsbG8sIG1ycyB0ZWFs\n' hello, mrs teal <=> '/:&5L;&\\L(&UR<R!T96%L\n' hello, mrs teal <=> 'D\'9XE\'mX)\'ebFb"dC@&X' hello, mrs teal <=> '68656c6c6f2c206d7273207465616c' 另外单元测试的代码也可供参考:http://svn.python.org/projects/python/branches/tarek_sysconfig/Lib/test/test_binascii.py

资源下载

更多资源
腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册