zoukankan      html  css  js  c++  java
  • Python基础之常用模块(三)

    1.configparser模块

    该模块是用来对文件进行读写操作,适用于格式与Windows ini 文件类似的文件,可以包含一个或多个节(section),每个节可以有多个参数(键值对)

    配置文件的格式如下:

    [DEFAULT]
    serveralagas = 24
    asdgasg = yes
    sdg = 123
    
    [hello]
    user = hd
    
    [world]
    what = fuck

       这种文件格式就像是一个大字典,每个标题就是一个key,字典中嵌套着字典

      还有需要注意的是,[DEFAULT]中的键值对是公用的,[DEFAULT]可以不写

    怎样由Python中写入这样一个文件呢?

    import configparser
    
    cfp=configparser.ConfigParser()  #就是一个空字典
    
    cfp['DEFAULT']={"serveralagas":24,"asdgasg":'yes',"sdg":123}
    
    cfp['hello']={'user':'hd'}
    
    cfp['world']={'what':'fuck'}
    
    with open('cfp.ini','w')as f:
        cfp.write(f)

    读取文件内容

    #读取文件
    
    import configparser
    
    config=configparser.ConfigParser()
    config.read('cfp.ini')
    
    #查看所有标题
    res=config.sections()
    print(res)  #['hello', 'world']
    
    #查看标题hello下的所有键值对的key
    options=config.options('hello')
    print(options)  #['user', 'serveralagas', 'asdgasg', 'sdg']
    
    #查看标题hello下的所有键值对的(key,value) 格式
    item_list=config.items('hello')
    print(item_list)    #[('serveralagas', '24'), ('asdgasg', 'yes'), ('sdg', '123'), ('user', 'hd')]
    
    #以字符串的形式查看hello标题下user的值
    val=config.get('hello','user')
    print(val)  #hd
    
    #上面那条命令,get可以改成getint,查看整数格式,改成getboolean,查看布尔值格式
    #改成getfloat查看浮点型格式

    修改文件内容

    import configparser
    
    config=configparser.ConfigParser()
    config.read('cfp.ini')
    
    #删除整个标题hello
    config.remove_section('hello')
    
    #删除标题world下的what
    config.remove_option('world','what')
    
    #判段是否存在某个标题
    print(config.has_section('hello'))
    
    #判断标题world下是否有user
    print(config.has_option('world','user'))
    
    #添加一个标题
    config.add_section('zhang')  #如果已经存在则会报错
    
    #在标题下添加name=zhang,age=18的配置
    config.set('zhang','name','zhang')
    config.set('zhang','age',18)#会报错,TypeError: option values must be strings
                                # 必须是字符串形式
    
    #将修改后的内容写入文件,完成最后的修改
    config.write(open('cfp.ini','w'))

    2.subprocess模块

    这个模块允许一个进程创建一个新的子进程,通过管道连接到子进程的stdin/stdout/stderr,并获取子进程的返回值等操作

    这个模块只有一个Popen类

    import subprocess
    
    #创建一个新的进程,与主进程不同步s=subprocess.Popen('dir',shell=True)
    #s是Popen的一个实例化对象s.wait()  #手动控制子进程的执行稍后一点print('ending')  #主进程的命令
    #当然在父进程中还可以对子进程有更多的操作
    s.poll()    #查看子进程的状态
    s.kill()    #终止子进程
    s.send_signal()#向子进程发送信号
    s.terminate() #终止子进程

    还可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并用subprocess.PIPE将多个子进程的输入输出连接在一起,构成管道

    import subprocess
    
    s1=subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE)
    print(s1.stdout.read())
  • 相关阅读:
    Python中re(正则表达式)模块学习
    Django(第一次使用心得,及总结)
    Lunix 安装VMware tools
    主键自动生成办法
    常用的android弹出对话框
    JDBC_mysql---防sql注入,存储图片
    java实现md5加密
    sql语句批量处理Batch
    连接mysql数据库2+操作入门
    Oracle事物基础
  • 原文地址:https://www.cnblogs.com/zhang-can/p/7106635.html
Copyright © 2011-2022 走看看