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, 计算空间中两 ...
随机推荐
- ibatis常用的集中判断语句
http://blog.csdn.net/liaomin416100569/article/details/5344483
- ActiveMQ与MSMQ的异同
http://www.cnblogs.com/luluping/archive/2010/11/03/1867841.html 目前常用的消息队列组建无非就是MSMQ和ActiveMQ,至于 ...
- RabbitMQ 学习笔记(一)特点
RabbitMQ 的具体特点 可靠性: RabbitMQ 使用一些机制来保证可靠性, 如持久化.传输确认及发布确认等. 令灵活的路由: 在消息进入队列之前,通过交换器来路由消息.对于典型的路由功能,R ...
- nodejs 获取指定路径下所有的文件夹名
示例:获取 ./components 下所有的文件夹名称 let components = [] const files = fs.readdirSync('./components') files. ...
- 【Java】取当前.class文件的编译位置
本文与<[C++]求当前exe的执行路径>(点击打开链接)为姊妹篇.C++在win下生成的执行文件是.exe.Java生成的执行文件是.class然后自己主动扔到Java虚拟机中执行.主要 ...
- 62. Search in Rotated Sorted Array【medium】
62. Search in Rotated Sorted Array[medium] Suppose a sorted array is rotated at some pivot unknown t ...
- [: ==: unary operator expected 解决方法
之前在写脚本时遇到了这样的错误 “[: ==: unary operator expected” 这是由于做判断的变量值为空导致的. 谷歌出解决方案: 在变量之后加任意字符.例如,要判断变量un是否为 ...
- CentOS 6.2 安装kdbg
地址:http://pkgs.org/centos-5/centos-x86_64/kdbg-2.0.2-1.2.1.x86_64.rpm.html 百度网盘地址:http://pan.baidu.c ...
- ../lib//libscsdblog.so: undefined reference to `pthread_atfork'
代码中遇到这个问题,但是在makefile中已经添加了-lpthread. 最后发现问题时,引入库的顺序,把-lpthread放在最后就可以了.
- spring 第一篇(1-3):鸟瞰spring蓝图
如你所见,spring框架的核心是关注于如何使用DI.AOP和模板来让企业级java开发变得更简单.spring确实也是这样做的,所以很值得你去使用它.不过spring内容可能比你所能看到的要多很多. ...