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模块学习(二)的更多相关文章

  1. 【转】Python模块学习 - fnmatch & glob

    [转]Python模块学习 - fnmatch & glob 介绍 fnmatch 和 glob 模块都是用来做字符串匹配文件名的标准库. fnmatch模块 大部分情况下使用字符串匹配查找特 ...

  2. 【目录】Python模块学习系列

    目录:Python模块学习笔记 1.Python模块学习 - Paramiko  - 主机管理 2.Python模块学习 - Fileinput - 读取文件 3.Python模块学习 - Confi ...

  3. Python模块学习filecmp文件比较

    Python模块学习filecmp文件比较 filecmp模块用于比较文件及文件夹的内容,它是一个轻量级的工具,使用非常简单.python标准库还提供了difflib模块用于比较文件的内容.关于dif ...

  4. Python基础学习二

    Python基础学习二 1.编码 utf-8编码:自动将英文保存为1个字符,中文3个字符.ASCll编码被囊括在内. unicode:将所有字符保存为2给字符,容纳了世界上所有的编码. 2.字符串内置 ...

  5. python模块学习第 0000 题

    将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果. 类似于图中效果: 好可爱>%<! 题目来源:https://github.com/Yixiao ...

  6. Python模块学习:logging 日志记录

    原文出处: DarkBull    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net ...

  7. 解惑Python模块学习,该如何着手操作...

    Python模块 晚上和朋友聊天,说到公司要求精兵计划,全员都要有编程能力.然后C.Java.Python-对于零基础入门的,当然是选择Python的人较多了.可朋友说他只是看了简单的语法,可pyth ...

  8. Python模块学习

    6. Modules If you quit from the Python interpreter and enter it again, the definitions you have made ...

  9. 扩展Python模块系列(二)----一个简单的例子

    本节使用一个简单的例子引出Python C/C++ API的详细使用方法.针对的是CPython的解释器. 目标:创建一个Python内建模块test,提供一个功能函数distance, 计算空间中两 ...

随机推荐

  1. Jenkins2.x Pipeline持续集成交互

    原文地址:http://blog.csdn.net/aixiaoyang168/article/details/72818804 Pipeline的几个基本概念: Stage: 阶段,一个Pipeli ...

  2. csv导出文件中有html

    最近遇到再导出csv文件时,csv文件中包含html代码 一开始以为导出的数据量太大,减少数据后仍然出现html代码,此时想到应该与数据有关,仔细观察csv中的数据,有的单元里面是空值, 对比原始数据 ...

  3. c++ 类内部 使用 new delete

    低级错误: /** * @clusterNums 默认为5 分类数目 * @xyVector 处理后点云数据 x y顺序存储 */ int GMM::runGMM(int clusterNums, c ...

  4. Atitit.创建快捷方式 windows快捷方式的原理

    Atitit.创建快捷方式 windows快捷方式的原理 1. Windows中有2种快捷方式的文件:1 2. Jshortcut2 2.1. 提示新不上jshortcut.dll2 2.2. 使用w ...

  5. Atitit. 数据库-----catalog与schema的设计区别以及在实际中使用 获取数据库所有库表 java jdbc php  c#.Net

    Atitit. 数据库-----catalog与schema的设计区别以及在实际中使用 获取数据库所有库表 java jdbc php  c#.Net 1. -catalog与schema的设计区别1 ...

  6. Xcode7中你一定要知道的炸裂调试神技【转载】

    Xcode7中苹果为我们增加了两个重要的debug相关功能.了解之后觉得非常实用,介绍给大家. 1.Address Sanitizer: 妈妈再也不用担心 EXC_BAD_ACCESS EXC_BAD ...

  7. imx6 uboot启动流程分析

    参考http://blog.csdn.net/skyflying2012/article/details/25804209 这里以imx6平台为例,分析uboot启动流程对于任何程序,入口函数是在链接 ...

  8. mysql存储引擎的种类与差别(innodb与myisam)

    查找数据库的存数引擎: show engines show variables like '%storage_engine%' 更改数据库的引擎更改配置文件/etc/my.cnf 改动default- ...

  9. JDBC mysql 中文乱码

    中文乱码似乎是程序编写中永恒的一个话题和难点,就比如MySQL存取中文乱码,但我想做任何事情,都要有个思路才行,有了思路才知道如何去解决问题,否则,即使一时解决了问题,但过后不久又碰到同样的问题可能又 ...

  10. flask/sqlalchemy - OperationalError: (sqlite3.OperationalError) no such table

    狗书第五章 记得要先创建表 执行 db.create_all()语句来创建表 https://segmentfault.com/q/1010000005794140