编程杂谈

说明思想:用Miniconda管理多个Python版本,在使用poetry创建虚拟环境的时候,指定Miniconda环境里的Py版本使用前的准备安装Miniconda链接:https://docs.conda.io/en/latest/miniconda.html安装poetry链接:https://bigdataboy.cn/post-399.html创建环境使用Miniconda创建多个Py版本的环境创建不同Python版本的虚拟环境condacreate-nPy3.9python=3.9查看环境condaenvlist使用第一步初始化poetry,使用命令:poetryinit,如果不是新项目直接跳到第二步这里有个坑,poetry指定Py版本的时候,只好写成这种格式~3.8(支持3.8.<3.9.0),不然会报版本不一致的错误,原因就是conda下载的版本是3.8.x,两处版本支持范围要严格一直F:\Tools\pyCode\test>poetryinitThiscommandwillguideyouthroughcreatingyourpyproject.tomlconfig.Packagename[test]:Version[0.1.0]:Description[]:Author[‘zbigdataboy‘<876545500@qq.com>,ntoskip]:bigdataboyLicense[]:CompatiblePythonversions[^3.9]:~3.8Wouldyouliketodefineyourmaindependenciesinteractively?(yes/no)[yes]noWouldyouliketodefineyourdevelopmentdependenciesinteractively?(yes/no)[yes]noGeneratedfile[tool.poetry]name="test"version="0.1.0"description=""authors=["bigdataboy"][tool.poetry.dependencies]python="~3.8"[tool.poetry.dev-dependencies][build-system]requires=["poetry-core>=1.0.0"]build-backend="poetry.core.masonry.api"Doyouconfirmgeneration?(yes/no)[yes]yes第二步peotry使用指定的解释器如果报版本不一致的错误,看第一步的坑poetryenvuseD:\ProgramData\miniconda3\envs\Py3.8\python.exe第三步安装相关依赖poetryinstall

Python极客

说明poetry是一个Python虚拟环境和依赖管理的工具,oetry和pipenv类似,另外还提供了打包和发布的功能。安装安装不成功,大多数是网站被墙了macOS&Linuxcurl-sSLhttps://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py|python-windows在powershell使用该命令(Invoke-WebRequest-Urihttps://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py-UseBasicParsing).Content|python-会自动添加到环境变量,需要重新打开powershell,查看是否安装成功配置使用前修改这些配置后,更好用查看当前配置poetryconfig--list-------------------PSC:\Users\ASUS>poetryconfig--listcache-dir="D:\\Python\\peotry_env"experimental.new-installer=trueinstaller.parallel=truevirtualenvs.create=truevirtualenvs.in-project=truevirtualenvs.path="{cache-dir}\\virtualenvs"#D:\Python\peotry_env\virtualenvs修改配置poetryconfigcache-dirD:\\Python\\peotry_envpoetryconfigvirtualenvs.in-projecttrue创建项目该命令,会建立一个目录结构poetrynewdemo结构demo├──pyproject.toml├──README.rst├──demo│└──__init__.py└──tests├──__init__.py└──test_demo.py其中pyproject.toml文件将协调项目及其依赖项[tool.poetry]name="demo"version="0.1.0"description=""authors=["‘zbigdataboy‘<876545500@qq.com>"][tool.poetry.dependencies]python="^3.9"[tool.poetry.dev-dependencies]pytest="^5.2"[build-system]requires=["poetry-core>=1.0.0"]build-backend="poetry.core.masonry.api"初始化项目这是在项目已经存在的情况下使用,为了创建pyproject.toml管理项目poetryinit添加依赖&库如果项目不存在虚拟环境,将会创建,同时还会创建poetry.lock,用以记录项目依赖的版本poetryaddrequests卸载依赖poetryremoverequests安装依赖项用以使用项目时,依赖于开发时一样poetryinstall修改依赖安装源项目的pyproject.toml文末追加[[tool.poetry.source]]name="tsinghua"url="https://pypi.tuna.tsinghua.edu.cn/simple"虚拟环境执行项目poetry会自动在相应目录寻找该项目的环境poetryrunpythonapp.py显示的激活poetryshell其他命令#显示当前环境信息poetryenvinfo#列出与项目关联的环境(一个项目可能需要不同版本依赖做测试)poetryenvlist#列出当前配置poetryconfig--list导出requirements.txt文件暂时只支持requirements.txt格式#导出requirements.txt文件-f导出格式--output导出文件名poetryexport-frequirements.txt--outputrequirements.txt

Python极客

解决痛点常规定义类的参数,如果参数很多(几十个),这样写,就很不方便classTestInfo():#定义类参数name:str=Noneage:int=None#构造器初始化def__init__(self,name:str,age:int):self.name=nameself.age=age#为了方便打印重写__repr__def__repr__(self):returnf'{self.__class__.__name__}(name={self.name},age={self.age})'if__name__=='__main__':tinfo=TestInfo(name='boy',age=16)print(tinfo)attr写法使用attr的写法,可以少写__init、__repr,并且打印也比较方便fromattrimportattrs,attr,fields_dict@attrsclassInfo():#定义类参数name=attr(type=str,default=None)age=attr(type=int,default=18)if__name__=='__main__':info=Info(name='boy')print(info)print(fields_dict(Info))attr属性用法参数解释type类型,比如int、str等各种类型,默认为Nonedefault属性的默认值,如果没有传入初始化数据,那么就会使用默认值,如果没有默认值定义,那么就是NOTHING,即没有默认值validator验证器,检查传入的参数是否合法,三个参数(实例,属性,值)init是否参与初始化,如果为False,那么这个参数不能当做类的初始化参数,默认是True。metadata元数据,只读性的附加数据converter转换器,进行一些值的处理和转换器,增加容错性kw_only是否为强制关键字参数,默认为Falsefromattrimportattrs,attrdefage_va(instance,attribute,value):"instance:实例attribute:参数value:值"print(instance.name)#boyifvalue>18:raiseValueError(f'age大于18')@attrsclassInfo():#定义类参数name=attr(type=str,default=None)age=attr(type=int,default=17,validator=age_va)if__name__=='__main__':info=Info(name='boy',age=9)print(info)

Python极客

说明使用Anaconda安装,是方便控制虚拟环境Python的版本,不于本机的全局相冲突。比如:全局==>Python3.8/虚拟环境==>Python3.6PyTorch0.4/虚拟环境==>Python3.7PyTorch1.7安装参考:https://bigdataboy.cn/post-342.html安装CUDA正常安装过程就行CUDA(ComputeUnifiedDeviceArchitecture),是显卡厂商NVIDIA推出的运算平台。CUDA是一种由NVIDIA推出的通用并行计算架构,该架构使GPU能够解决复杂的计算问题。下载网站:https://developer.nvidia.com/cuda-downloads历史版本下载:https://developer.nvidia.com/cuda-toolkit-archive检测CUDAcmd输入:nvcc-V安装cuDNNNVIDIAcuDNN是用于深度神经网络的GPU加速库。它强调性能、易用性和低内存开销。NVIDIAcuDNN可以集成到更高级别的机器学习框架中,如谷歌的Tensorflow、加州大学伯克利分校的流行caffe软件。简单的插入式设计可以让开发人员专注于设计和实现神经网络模型,而不是简单调整性能,同时还可以在GPU上实现高性能现代并行计算。cuDNN的下载需要登录,但是nvidia登录时的验证码经常被强(各种办法尝试都不行),登陆难度极大不用登陆小技巧:进入历史版本选择好,右键复制链接(就是资源实际地址),然后使用迅雷等工具下载下载网站:https://developer.nvidia.com/rdp/cudnn-download历史版本:https://developer.nvidia.com/rdp/cudnn-archive解压&移动解压下载的cuDNN把解压的cuDNN里的文件,移动到[路径]\NVIDIAGPUComputingToolkit\CUDA\v11.4\下相应的文件下cnDNN[bin]->CUDN[bin]cnDNN[include]->CUDN[include]cnDNN[lib\x64]->CUDN[lib\x64]添加环境变量把下面两个路径添加进环境变量C:\ProgramFiles\NVIDIAGPUComputingToolkit\CUDA\v11.4\lib\x64C:\ProgramFiles\NVIDIAGPUComputingToolkit\CUDA\v11.4\检测结果cmd运行这个exe程序创建虚拟环境condacreate-npytorchpython=3.7虚拟环境名字:pytorch虚拟环境PY版本:3.7安装PyTorch切换环境condaactivatepytorch查看本机CUDA版本生成安装命令&安装PyTorch有点大,安装时耐心等待PyTorch官网:https://pytorch.org/命令:condainstallpytorchtorchvisiontorchaudiocudatoolkit=11.1-cpytorch-cconda-forge如果下载是在太慢,可以先用其他工具下载好,再本地安装PyTorch国内镜像:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorchcondainstall--use-local~/Downloads/a.tar.bz2验证安装进入pytthonshell进行验证importtorchprint(torch.__version__)print(torch.cuda.is_available())Pycharm使用该环境创建新项目,使用conda管理虚拟环境选择这个环境验证

Python极客

安装AnacondaAnaconda历史版本:https://repo.anaconda.com/archive/(本文使用:Anaconda3-5.2.0-Windows-x86_64.exe)正常安装过程同意->下一步->下一步->…->跳过(Skip)不安装VS->完成校验安装是否成功打开AnacondaPrompt配置环境变量添加{路径}Anaconda3\Scripts到Path里cmd输入:conda--version常用操作修改下载源可参考清华源官方文:https://mirror.tuna.tsinghua.edu.cn/help/anaconda/打开C:\Users\[电脑用户名]\.condarcchannels:-defaultsshow_channel_urls:truedefault_channels:-https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main-https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r-https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2custom_channels:conda-forge:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudmsys2:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudbioconda:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudmenpo:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudpytorch:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudsimpleitk:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud查看修改后的源命令:condainfo常用命令建议在AnacondaPrompt里使用,而不是在cmd更新全部工具包condaupgrade--all创建指定Py版本虚拟环境condacreate-n[名字]python=[版本号]condacreate-nvenvpython=3.6进入虚拟环境condaactivate[名字]模块安装(进入环境执行)condainstall[模块名]或者pipinstall[模块名]卸载模块(进入环境执行)condaremove[模块名]或者pipuninstall[模块名]卸载环境condaremove-n[环境名]--all查看环境列表condaenvlist

2021-8-25 634 0
Python极客

安装&加载pip3installpymongo-ihttps://mirrors.aliyun.com/pypi/simple/importpymongo连接MongoDB服务client=pymongo.MongoClient("mongodb://localhost:27017/")print(client)--------------#Mongo服务MongoClient(host=['localhost:27017'],document_class=dict,tz_aware=False,connect=True)获取所有数据库dblist=client.list_database_names()print(dblist)-------------#所有数据库名称['admin','config','local']创建数据库&获取数据库对象如果没有该数据库则创建db=client["db"]print(db)---------#db数据库对象Database(MongoClient(host=['localhost:27017'],document_class=dict,tz_aware=False,connect=True),'db')创建集合&获取集合如果没有该集合则创建#创建集合collection=db["collection"]print(sets)-----------#sets集合对象Collection(Database(MongoClient(host=['localhost:27017'],document_class=dict,tz_aware=False,connect=True),'db'),'sets')#获取所有集合sets=db.list_collection_names()print(sets)--------------#该数据库所有集合['collection']插入数据#插入一条数据data={"name":"bigdataboy","age":"18"}x=collection.insert_one(data)print(x.inserted_id)--------#数据的_id5ed666e1bca2037c30662e97#插入多条数据datas=[{"name":"大数据男孩","age":"18"},{"name":"bigdataboy","age":"16","addr":"China"},{"name":"bigdataboy","age":"18"}]x=collection.insert_many(datas)print(x.inserted_ids)---------------------#插入数据的_id[ObjectId('5ed667e044fb69d445e510d8'),ObjectId('5ed667e044fb69d445e510d9'),ObjectId('5ed667e044fb69d445e510da')]自定义_id#链式写法collection=pymongo.MongoClient("mongodb://localhost:27017/")["db"]["collection"]#数据自行固定_iddatas=[{"_id":"1","name":"大数据男孩","age":"18"},{"_id":"2","name":"bigdataboy","age":"16","addr":"China"},{"_id":"3","name":"bigdataboy","age":"18"}]i=collection.insert_many(datas)print(i.inserted_ids)---------------------#插入数据的_id['1','2','3']查看所有数据collection=pymongo.MongoClient("mongodb://localhost:27017/")["db"]["collection"]forxincollection.find():print(x)------------#所有数据{'_id':'1','name':'大数据男孩','age':'18'}{'_id':'2','name':'bigdataboy','age':'16','addr':'China'}{'_id':'3','name':'bigdataboy','age':'18'}

Python极客

安装&加载pip3installrequests-ihttps://mirrors.aliyun.com/pypi/simple/importrequestsGET请求#普通请求r=requests.get('https://bigdataboy.cn/')#带Query参数,等价于https://bigdataboy.cn/?key1=value1&key2=value2payload={'key1':'value1','key2':'value2'}r=requests.get('https://bigdataboy.cn/',params=params)#带Headersheaders={'user-agent':'anoyi-app/0.0.1'}r=requests.get('https://bigdataboy.cn/',headers=headers)#带BasicAuthenticationr=requests.get('https://bigdataboy.cn/',auth=('user','pass'))POST请求POST请求-表单提交r=requests.post('https://bigdataboy.cn/',data={'key':'value'})POST请求-x-www-form-urlencodedheaders={'content-type':'application/x-www-form-urlencoded;charset=UTF-8'}r=requests.post('https://bigdataboy.cn/',headers=headers,data='key=value')POST请求-application/jsonpayload={'some':'data'}r=requests.post('https://bigdataboy.cn/',json=payload)其他请求#PUTr=requests.put('https://bigdataboy.cn/',data={'key':'value'})#DELETEr=requests.delete('https://bigdataboy.cn/')#HEADr=requests.head('https://bigdataboy.cn/')#OPTIONSr=requests.options('https://bigdataboy.cn/')网络响应-Reponse基本信息#状态码r.status_code#响应头r.headers#响应Cookier.cookies返回结果#文本内容r.text#二进制r.content#JSONr.json()#流r=requests.get('https://bigdataboy.cn/',stream=True)r.raw.read(10)常用方法URL编码fromrequests.utilsimportquotequote('ab')->'a%20b'URL解码fromrequests.utilsimportunquoteunquote('a%20b')->'ab'自动推断响应编码r.encoding=r.apparent_encoding下载文件r=requests.get('https://bigdataboy.cn/')open('bigdataboy.html','wb').write(r.content)上传文件files={'file':open('report.xls','rb')}r=requests.post(url,files=files)超时设置#单位:秒requests.get('https://bigdataboy.cn/',timeout=0.001)

未分类

高阶函数使用—-函数式编程Python函数的参数可以是:字符串,整数…普通的变量,但Python函数的参数还能是一个函数,返回值也能是一个函数。函数作为参数函数fun()接受一个函数f作为参数首先定义一个主函数函数的第一个参数需要传入一个函数deffun(f,a:int,b:int):returnf(a)+f(b)定义参数函数,只是简单的返回参数deff(num):returnnum使用主函数print(fun(f,1,2))-------------------3函数作为返回值定义返回值函数f()deff(num):returnnum**num定义主函数fun(),直接返回f()函数deffun():#不能加括号,带括号就是调用returnf使用主函数第一个括号调用fun()函数,第二个括号调用返回的函数foo=fun()print(foo)#一个函数print(foo(2))#合并写法print(fun()(2))---------------<functionfat0x000001FD81A62268>44内置的高阶函数sort()排序普通排序使用list=[1,5,6,8,7,6,5,5,2]list.sort(reverse=True)#降序print(list)---------------------------[8,7,6,6,5,5,5,2,1]高级使用—按照指定规则排序按照十位数的大小排序#作为参数的函数deffun(num):returnstr(num)[0]list=[11,51,61,82,72,64,52,512,21]list.sort(key=fun,reverse=True)print(list)------------------------------------[82,72,61,64,51,52,512,21,11]#使用匿名函数合并list=[11,51,61,82,72,64,52,512,21]list.sort(key=lambdanum:str(num)[0],reverse=True)print(list)------------------------------------[82,72,61,64,51,52,512,21,11]map()&filter()函数编程语言通常都会提供map,filter,reduce三个高阶函数。在Python3中,map和filter仍然是内置函数,但是由于引入了列表推导和生成器表达式,他们变得没有那么重要了。列表推导和生成器表达式具有了map和filter两个函数的功能,而且更易于阅读。map生成新的迭代类型list_m=map(lambdanum:num**2,[1,2,3,4,5,6,7])print(list(list_m))print(type(list_m))-------------------[1,4,9,16,25,36,49]<class'map'>列表推导实现map()list_m=[num**2fornumin[1,2,3,4,5,6,7]]print(list_m)-------------[1,4,9,16,25,36,49]同时迭代多个list,生成新的迭代类型的长度是最短list的长度list1=[10,20,30,40]list2=[1,2]list_m=map(lambdaa,b:a+b,list1,list2)print(list(list_m))-------------------[11,22]注意列表推倒中这里是使用的笛卡尔积list1=[10,20,30,40]list2=[1,2]list_m=[a+bforainlist1forbinlist2]print(list_m)-------------[11,12,21,22,31,32,41,42]filter过滤filter参数函数的返回值需要是布尔值list_m=filter(lambdanum:num%2,[1,2,3,4,5,6,7])print(list(list_m))-------------------[1,3,5,7]列表推导实现filter()list_m=[numfornumin[1,2,3,4,5,6,7]ifnum%2==1]print(list_m)-------------[1,3,5,7]reducePython3中reduce被移动到了functools模块中fromfunctoolsimportreduce用法两两做运算fromfunctoolsimportreducenum=reduce(lambdaa,b:a+b,[1,2,3,4,5,6,7],0)#0为a的初始值print(num)----------28