python模块学习(二)
configparser模块
软件常见文档格式如下:
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org]User = hg [topsecret.server.com]Port = 50022ForwardX11 = no
如果想用python生成一个这样的文档怎么做呢?
import configparser config = configparser.ConfigParser()config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {}config['bitbucket.org']['User'] = 'hg'config['topsecret.server.com'] = {}topsecret = config['topsecret.server.com']topsecret['Host Port'] = '50022' # mutates the parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'<br>with open('example.ini', 'w') as configfile: config.write(configfile)
增删改查
import configparserconfig = configparser.ConfigParser()#---------------------------------------------查print(config.sections()) #[]config.read('example.ini')print(config.sections()) #['bitbucket.org', 'topsecret.server.com']print('bytebong.com' in config)# Falseprint(config['bitbucket.org']['User']) # hgprint(config['DEFAULT']['Compression']) #yesprint(config['topsecret.server.com']['ForwardX11']) #nofor key in config['bitbucket.org']: print(key)# user# serveraliveinterval# compression# compressionlevel# forwardx11print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]print(config.get('bitbucket.org','compression'))#yes
#---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))config.add_section('yuan')config.remove_section('topsecret.server.com')config.remove_option('bitbucket.org','user')config.set('bitbucket.org','k1','11111')config.write(open('i.cfg', "w"))
hashlib模块
用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlibm=hashlib.md5()# m=hashlib.sha256()m.update('hello'.encode('utf8'))print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592m.update('alvin'.encode('utf8'))print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4afm2=hashlib.md5()m2.update('helloalvin'.encode('utf8'))print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib# ######## 256 ########hash = hashlib.sha256('898oaFs09f'.encode('utf8'))hash.update('alvin'.encode('utf8'))print (hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7
python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密:
import hmach = hmac.new('alvin'.encode('utf8'))h.update('hello'.encode('utf8'))print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940
subprocess模块
当我们需要调用系统的命令的时候,最先考虑的os模块。用os.system()和os.popen()来进行操作。但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成我们需要的操作。
subprocess模块允许一个进程创建一个新的子进程,通过管道连接到子进程的stdin/stdout/stderr,获取子进程的返回值等操作。
subprocess.PIPE
在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。
import subprocess# subprocess.Popen('ls')p=subprocess.Popen('ls',stdout=subprocess.PIPE)#结果跑哪去啦?print(p.stdout.read())#这这呢:b'__pycache__\nhello.py\nok.py\nweb\n'
这是因为subprocess创建了子进程,结果本在子进程中,if 想要执行结果转到主进程中,就得需要一个管道,即 : stdout=subprocess.PIPE
subprocess.STDOUT
创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。
Popen的方法
Popen.poll() 用于检查子进程是否已经结束。设置并返回returncode属性。Popen.wait() 等待子进程结束。设置并返回returncode属性。Popen.communicate(input=None)与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。 Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:如果希望通过进程的stdin向其发送数据,在创建Popen对象的时候,参数stdin必须被设置为PIPE。同样,如 果希望从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。Popen.send_signal(signal) 向子进程发送信号。Popen.terminate()停止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程。Popen.kill()杀死子进程。Popen.stdin 如果在创建Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。否则返回None。Popen.stdout 如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回 None。Popen.stderr 如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回 None。Popen.pid 获取子进程的进程ID。Popen.returncode 获取进程的返回值。如果进程还没有结束,返回None。
supprocess模块的工具函数
supprocess模块提供了一些函数,方便我们用于创建进程来实现一些简单的功能。subprocess.call(*popenargs, **kwargs)运行命令。该函数将一直等待到子进程运行结束,并返回进程的returncode。如果子进程不需要进行交互,就可以使用该函数来创建。subprocess.check_call(*popenargs, **kwargs)与subprocess.call(*popenargs, **kwargs)功能一样,只是如果子进程返回的returncode不为0的话,将触发CalledProcessError异常。在异常对象中,包 括进程的returncode信息。 check_output(*popenargs, **kwargs)与call()方法类似,以byte string的方式返回子进程的输出,如果子进程的返回值不是0,它抛出CalledProcessError异常,这个异常中的returncode包含返回码,output属性包含已有的输出。getstatusoutput(cmd)/getoutput(cmd)这两个函数仅仅在Unix下可用,它们在shell中执行指定的命令cmd,前者返回(status, output),后者返回output。其中,这里的output包括子进程的stdout和stderr。
演示
import subprocess#1# subprocess.call('ls',shell=True)'''hello.pyok.pyweb'''# data=subprocess.call('ls',shell=True)# print(data)'''hello.pyok.pyweb0'''#2# subprocess.check_call('ls',shell=True)'''hello.pyok.pyweb'''# data=subprocess.check_call('ls',shell=True)# print(data)'''hello.pyok.pyweb0'''# 两个函数区别:只是如果子进程返回的returncode不为0的话,将触发CalledProcessError异常#3# subprocess.check_output('ls')#无结果# data=subprocess.check_output('ls')# print(data) #b'hello.py\nok.py\nweb\n'

识别图中二维码,欢迎关注python宝典
python模块学习(二)的更多相关文章
- 【转】Python模块学习 - fnmatch & glob
[转]Python模块学习 - fnmatch & glob 介绍 fnmatch 和 glob 模块都是用来做字符串匹配文件名的标准库. fnmatch模块 大部分情况下使用字符串匹配查找特 ...
- 【目录】Python模块学习系列
目录:Python模块学习笔记 1.Python模块学习 - Paramiko - 主机管理 2.Python模块学习 - Fileinput - 读取文件 3.Python模块学习 - Confi ...
- Python模块学习filecmp文件比较
Python模块学习filecmp文件比较 filecmp模块用于比较文件及文件夹的内容,它是一个轻量级的工具,使用非常简单.python标准库还提供了difflib模块用于比较文件的内容.关于dif ...
- Python基础学习二
Python基础学习二 1.编码 utf-8编码:自动将英文保存为1个字符,中文3个字符.ASCll编码被囊括在内. unicode:将所有字符保存为2给字符,容纳了世界上所有的编码. 2.字符串内置 ...
- python模块学习第 0000 题
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果. 类似于图中效果: 好可爱>%<! 题目来源:https://github.com/Yixiao ...
- Python模块学习:logging 日志记录
原文出处: DarkBull 许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net ...
- 解惑Python模块学习,该如何着手操作...
Python模块 晚上和朋友聊天,说到公司要求精兵计划,全员都要有编程能力.然后C.Java.Python-对于零基础入门的,当然是选择Python的人较多了.可朋友说他只是看了简单的语法,可pyth ...
- Python模块学习
6. Modules If you quit from the Python interpreter and enter it again, the definitions you have made ...
- 扩展Python模块系列(二)----一个简单的例子
本节使用一个简单的例子引出Python C/C++ API的详细使用方法.针对的是CPython的解释器. 目标:创建一个Python内建模块test,提供一个功能函数distance, 计算空间中两 ...
随机推荐
- Docker 方式运行 jenkins
原文地址:https://testerhome.com/topics/5798 简介说明 docker 是官方推荐的一种 jenkins 启动方式. 打开 jenkins 的官网,点击进入的是: ht ...
- Docker 基础概念科普 和 常用操作介绍
Docker 基础概念 Docker是什么? Docker的思想来自于集装箱,集装箱解决了:在一艘大船上,可以把货物规整的摆放起来.并且各种各样的货物被集装箱标准化了,集装箱和集装箱之 ...
- unity, 内存profile,ImageEffects Temp和Unity GI SystemTex RGBM
最近用unity的Profiler对公司项目进行内存profile,发现一些问题,记录一下. 用Memory Area的Detailed View,用法见:http://docs.unity3d.co ...
- MySql(一):linux 安装mysql数据库——yum安装法
mysql数据库有多种安装方式,本文只介绍在Linux服务器上最实用.最快捷的mysql server安装方法.一.Linux服务器yum安装(CentOS6.3 64位)所有在服务器上执行的命令,都 ...
- atitit.MIZIAN 陕北方言 特有词汇 大词典 attilax 整理 a--g v1 q31.xlsx
atitit.MIZIAN 陕北方言 特有词汇 大词典 attilax 整理 a--g v1 q31.xlsx 1 Mizian陕北方言 english英语 spain西班牙语 cantonese粤 ...
- 代码转换工具 Java to C#
http://www.tangiblesoftwaresolutions.com/ (Java 2 C#) http://www.tangiblesoftwaresolutions.com/Produ ...
- C++程序设计(第4版)读书笔记_C++概览:基础知识
变量赋值 常用的变量赋值都是用“=”去赋值的 ; 但是如果把一个浮点数赋值给i的话,就会造成精度损失,在C++中最好使用初始化列表的方式“{}”给变量赋值,这样可以保证不会发生某些可能导致信息丢失的类 ...
- Django学习之第三方储存服务器的使用
最近,越来越多的公司采用第三方储存来作为视频,图片的储存工具. 国内的像七牛,阿里云的OSS,国外的像亚马逊的S3,微软的azure都是非常有名的第三方储存. 下面以阿里的OSS为例,来介绍第三储存的 ...
- openWRT自学---针对backfire版本的主要目录和文件的作用的分析整理
特别说明:要编译backfire版本,一定要通过svn下载:svn co svn://svn.openwrt.org/openwrt/branches/backfire,而不能使用http://dow ...
- CSS学习(二)- 有关 hasLayout 和 BFC
1. hasLayout 概念说明 ‘Layout’ 可以被某些 CSS property(特性)不可逆的触发,而某些 HTML 元素本身就具有 layout . ‘Layout’ 在 IE 中可以通 ...