第5天学习

来源:互联网 发布:apk编程自动发短信 编辑:程序博客网 时间:2024/05/30 22:42

冒泡排序

numbList = [25,43,1,2,19,55,21,999]这里有一个列表,要求对这个列表从大到小排序for m in range(1, len(numbList)):    for i in range(len(numbList) - m):        tmp = data[i+1]        data[i+1] = data[i]        data[i] = tmp

模块,用一砣代码实现了某个功能的代码集合。

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

自定义模块内置标准模块(又称标准库)开源模块

序列化模块 json pickle

import picklea = {'name':'xiaohong','age':15}#将字典写入文件with open('1.txt','w') as f:    f.write(pickle.dumps(a))#从文件中读取字典with open('1.txt','rb') as f:    pickle.loads(f.read())import json#将字典写入文件with open('1.txt','w') as f:    f.write(json.dumps(a))#从文件中读取字典with open('1.txt','r') as f:    json.loads(f.read())pickle和json的区别在于pickle是python独有的的,其他语言是无法读物通过pickle写入文件的序列,而json是通用的其他语言也可以读取,pickle能够支持Python所有的字符类型,包括函数def login():    print('haha')info = {'name':'xiaohong','age':13,'func':login}with open('1.txt','w') as f:    f.write(pickle.dumps(info))with open('1.txt','r') as f:    data = pickle.loads(f.read())执行函数 data['func']()

常用模块

os模块

Python和系统进行交互模块

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cdos.curdir  返回当前目录: ('.')os.pardir  获取当前目录的父目录字符串名:('..')os.makedirs('dirname1/dirname2')    可生成多层递归目录os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirnameos.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirnameos.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印os.remove()  删除一个文件os.rename("oldname","newname")  重命名文件/目录os.stat('path/filename')  获取文件/目录信息os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"os.pathsep    输出用于分割文件路径的字符串os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'os.system("bash command")  运行shell命令,直接显示os.environ  获取系统环境变量os.path.abspath(path)  返回path规范化的绝对路径os.path.split(path)  将path分割成目录和文件名二元组返回os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素os.path.exists(path)  如果path存在,返回True;如果path不存在,返回Falseos.path.isabs(path)  如果path是绝对路径,返回Trueos.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回Falseos.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

time & datetime模块

 #_*_coding:utf-8_*_import time# print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来 8 # print(time.altzone)  #返回与utc时间的时间差,以秒计算\ 9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",10 # print(time.localtime()) #返回本地时间 的struct time对象格式11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式12 13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上15 16 17 18 # 日期字符串 转成  时间戳19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式20 # print(string_2_struct)21 # #22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳23 # print(struct_2_stamp)24 25 26 27 #将时间戳转为字符串格式28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式30 31 32 33 34 35 #时间加减36 import datetime37 38 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.94192539 #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-1940 # print(datetime.datetime.now() )41 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+342 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-343 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时44 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+3045 46 47 #48 # c_time  = datetime.datetime.now()49 # print(c_time.replace(minute=3,hour=2)) #时间替换

random模块

随机数import randomprint random.random()print random.randint(1,2)print random.randrange(1,10)生成随机验证码 import randomcheckcode = ''for i in range(4):    current = random.randrange(0,4)    if current != i:        temp = chr(random.randint(65,90))    else:        temp = random.randint(0,9)    checkcode += str(temp)print checkcode

SYS模块

sys.argv           命令行参数List,第一个元素是程序本身路径sys.exit(n)        退出程序,正常退出时exit(0)sys.version        获取Python解释程序的版本信息sys.maxint         最大的Int值sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.platform       返回操作系统平台名称sys.stdout.write('please:')val = sys.stdin.readline()[:-1]

shelve 模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

import shelved = shelve.open('shelve_test') #打开一个文件class Test(object):    def __init__(self,n):        self.n = nt = Test(123) t2 = Test(123334)name = ["alex","rain","test"]d["test"] = name #持久化列表d["t1"] = t      #持久化类d["t2"] = t2d.close()

xml处理模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式如下,就是通过<>节点来区别数据结构的:

<?xml version="1.0"?><data>    <country name="Liechtenstein">        <rank updated="yes">2</rank>        <year>2008</year>        <gdppc>141100</gdppc>        <neighbor name="Austria" direction="E"/>        <neighbor name="Switzerland" direction="W"/>    </country>    <country name="Singapore">        <rank updated="yes">5</rank>        <year>2011</year>        <gdppc>59900</gdppc>        <neighbor name="Malaysia" direction="N"/>    </country>    <country name="Panama">        <rank updated="yes">69</rank>        <year>2011</year>        <gdppc>13600</gdppc>        <neighbor name="Costa Rica" direction="W"/>        <neighbor name="Colombia" direction="E"/>    </country></data>

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml  

import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")root = tree.getroot()print(root.tag)#遍历xml文档for child in root:    print(child.tag, child.attrib)    for i in child:        print(i.tag,i.text)#只遍历year 节点for node in root.iter('year'):    print(node.tag,node.text)

修改和删除xml文档内容

import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")root = tree.getroot()#修改for node in root.iter('year'):    new_year = int(node.text) + 1    node.text = str(new_year)    node.set("updated","yes")tree.write("xmltest.xml")#删除nodefor country in root.findall('country'):   rank = int(country.find('rank').text)   if rank > 50:     root.remove(country)tree.write('output.xml')

自己创建xml文档

import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist")name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})age = ET.SubElement(name,"age",attrib={"checked":"no"})sex = ET.SubElement(name,"sex")sex.text = '33'name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})age = ET.SubElement(name2,"age")age.text = '19'et = ET.ElementTree(new_xml) #生成文档对象et.write("test.xml", encoding="utf-8",xml_declaration=True)ET.dump(new_xml) #打印生成的格式 

ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
来看一个好多软件的常见文档格式如下

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes[bitbucket.org]User = hg[topsecret.server.com]Port = 50022ForwardX11 = no

用Python生成这个文档

import configparserconfig = 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'with open('example.ini', 'w') as configfile:   config.write(configfile)

读取这个文档

>>> import configparser>>> config = configparser.ConfigParser()>>> config.sections()[]>>> config.read('example.ini')['example.ini']>>> config.sections()['bitbucket.org', 'topsecret.server.com']>>> 'bitbucket.org' in configTrue>>> 'bytebong.com' in configFalse>>> config['bitbucket.org']['User']'hg'>>> config['DEFAULT']['Compression']'yes'>>> topsecret = config['topsecret.server.com']>>> topsecret['ForwardX11']'no'>>> topsecret['Port']'50022'>>> for key in config['bitbucket.org']: print(key)...usercompressionlevelserveraliveintervalcompressionforwardx11>>> config['bitbucket.org']['ForwardX11']'yes'

修改这个文档

[section1]k1 = v1k2:v2[section2]k1 = v1import ConfigParserconfig = ConfigParser.ConfigParser()config.read('i.cfg')# ########## 读 ###########secs = config.sections()#print secs#options = config.options('group2')#print options#item_list = config.items('group2')#print item_list#val = config.get('group1','key')#val = config.getint('group1','key')# ########## 改写 ###########sec = config.remove_section('group1')#config.write(open('i.cfg', "w"))#sec = config.has_section('wupeiqi')#sec = config.add_section('wupeiqi')#config.write(open('i.cfg', "w"))#config.set('group2','k1',11111)#config.write(open('i.cfg', "w"))#config.remove_option('group2','age')#config.write(open('i.cfg', "w"))

Subprocess模块

    #执行命令,返回命令执行状态 , 0 or 非0    >>> retcode = subprocess.call(["ls", "-l"])    #执行命令,如果命令结果为0,就正常返回,否则抛异常    >>> subprocess.check_call(["ls", "-l"])    0    #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果    >>> subprocess.getstatusoutput('ls /bin/ls')    (0, '/bin/ls')    #接收字符串格式命令,并返回结果    >>> subprocess.getoutput('ls /bin/ls')    '/bin/ls'    #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res    >>> res=subprocess.check_output(['ls','-l'])    >>> res    b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'    #上面那些方法,底层都是封装的subprocess.Popen    poll()    Check if child process has terminated. Returns returncode    wait()    Wait for child process to terminate. Returns returncode attribute.    terminate() 杀掉所启动进程    communicate() 等待任务结束    stdin 标准输入    stdout 标准输出    stderr 标准错误    pid    The process ID of the child process.    #例子    >>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)    >>> p.stdout.read()    b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n'>>> subprocess.run(["ls", "-l"])  # doesn't capture outputCompletedProcess(args=['ls', '-l'], returncode=0)>>> subprocess.run("exit 1", shell=True, check=True)Traceback (most recent call last):  ...subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')调用subprocess.run(...)是推荐的常用方法,在大多数情况下能满足需求,但如果你可能需要进行一些复杂的与系统的交互的话,你还可以用subprocess.Popen(),语法如下:p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE)print(p.stdout.read()可用参数:        args:shell命令,可以是字符串或者序列类型(如:list,元组)        bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲        stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄        preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用        close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。        所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。        shell:同上        cwd:用于设置子进程的当前目录        env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。        universal_newlines:不同系统的换行符不同,True -> 同意使用 \n        startupinfo与createionflags只在windows下有效        将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等终端输入的命令分为两种:    输入即可得到输出,如:ifconfig    输入进行某环境,依赖再输入,如:python##需要交互的命令示例import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n ')obj.stdin.write('print 2 \n ')obj.stdin.write('print 3 \n ')obj.stdin.write('print 4 \n ')out_error_list = obj.communicate(timeout=10)print out_error_list##subprocess实现sudo 自动输入密码import subprocessdef mypass():    mypass = '123' #or get the password from anywhere    return mypassecho = subprocess.Popen(['echo',mypass()],                        stdout=subprocess.PIPE,                        )sudo = subprocess.Popen(['sudo','-S','iptables','-L'],                        stdin=echo.stdout,                        stdout=subprocess.PIPE,                        )end_of_pipe = sudo.stdoutprint "Password ok \n Iptables Chains %s" % end_of_pipe.read()
0 0
原创粉丝点击