Python subprocess、configparser、yaml模块

来源:互联网 发布:沈阳软件开发招聘 编辑:程序博客网 时间:2024/06/02 01:18

yaml模块

http://www.pyyaml.org/wiki/PyYAMLDocumentation

安装方式1:

pip install pyyaml

安装方式2:

Download the source package PyYAML-x.tar.gz and unpack it. Go to the directory PyYAML-x and run

$ python setup.py install

Loading YAML

If a string or a file contains several documents, you may load them all with the yaml.load_all function.

Warning: It is not safe to call yaml.load with any data received from an untrusted source! yaml.load is as powerful as pickle.load and so may call any Python function. Check the yaml.safe_load function though.

The function yaml.load converts a YAML document to a Python object.

(python35) [root@vm7-1201-pure lockey]# cat test.py import yamlx=yaml.load("""- Hesperiidae- Papilionidae- Apatelodidae- Epiplemidae""")print(x)(python35) [root@vm7-1201-pure lockey]# python test.py ['Hesperiidae', 'Papilionidae', 'Apatelodidae', 'Epiplemidae']

从yaml文件中读取配置

(python35) [root@vm7-1201-pure lockey]# cat x.yaml global:  scrape_interval:     15s  evaluation_interval: 15s  external_labels:    cluster_name: 'promgen'rule_files:  - "/etc/prometheus/promgen.rule/*"alerting:  alertmanagers:  - static_configs:    - targets:      - localhost:9093
with open('x.yaml') as fp:     content = yaml.load(fp)     print(content)

Dumping YAML

The yaml.dump function accepts a Python object and produces a YAML document.>>> print(yaml.dump({'name': 'Silenthand Olleander', 'race': 'Human','traits': ['ONE_HAND', 'ONE_EYE']}))name: Silenthand Olleanderrace: Humantraits: [ONE_HAND, ONE_EYE]

写入文件:

>>> data{'race': 'Human', 'name': 'Silenthand Olleander', 'traits': ['ONE_HAND', 'ONE_EYE']}>>> with open('dmp.yaml','w') as fp:...     yaml.dump(data,fp)>>> print(yaml.dump(range(5), default_flow_style=False))!!python/object/apply:builtins.range- 0- 5- 1

configparser模块

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,生成一个空字典topsecret["Host Port"] = "50022"            #给字典添加键值对topsecret["Forwardx11"] = "no"config["DEFAULT"]["Forwardx11"] = "yes"with open("config_file.ini","w") as configfile:    config.write(configfile)

(python35) [root@vm7-1201-pure prometheus]# python config-parser.py
(python35) [root@vm7-1201-pure prometheus]# cat config_file.ini
[DEFAULT]
serveraliveinterval = 45
compressionlevel = 9
compression = yes
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

>>> import configparser>>> config = configparser.ConfigParser()>>> config.sections()[]>>> config.read('config_file.ini')['config_file.ini']>>> config.sections()['bitbucket.org', 'topsecret.server.com']>>> 

下面来看看configparser模块中文件的增删改查:
复制代码

sec = config.remove_section("bitbucket.org")config.write(open("config_file.ini","w"))#添加新的字段到文件中# sec = config.has_section("alex")# config.add_section("alex")# config["alex"]["age"] = "21"# config.write(open("config_file.ini","w"))config['bitbucket.org']['user']#修改字段中的文件信息config.set("alex","age","28")config.write(open("config_file.ini","w"))

subprocess模块

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.systemos.spawn*
  1. subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
    1.1 参数args描述了子进程中需要执行的命令;
    1.2 父进程会等待子进程的结束,并获得call函数的返回值
    1.3 如果子进程不需要进行交互,就可以使用该函数来创建
    >>> import subprocess    >>> cmd = ['ls', '-l']    >>> ret = subprocess.call(cmd)
>>> subprocess.run(["ls", "-l"])>>> 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 Dec  6 06:23 /dev/null\n')
  1. subprocess.check_all(args, *, stdin=None, stdout=None, stderr=None, shell=False)
    2.1 check_all()与call()唯一的区别在于返回值。如果args执行之后的返回值为0,那么check_all返回0;如果返回值不为0,那么将raise出来一个CalledProcessError
  2. subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
    3.1 子进程执行args中的命令,并将其输出形成字符串返回
    3.2 如果返回值非零,那么将raise一个CalledProcessError。这一对象实例中有returncode属性以及output属性(args命令的output)
  3. subprocess.Popen()
    4.1 详细格式:class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
    4.2 Popen对象创建后,主程序不会自动等待子进程完成。我们必须调用对象的wait()方法,父进程才会等待 (也就是阻塞block)
    4.3 Popen中封装的其他函数:
    4.3.1 Popen.poll():检查子进程的状态,查看子进程是否结束
    4.3.2 Popen.wait():等待子进程的结束
    4.3.3 Popen.communicate(input=None):与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:如果希望通过进程的stdin向其发送数据,在创建Popen对象的时候,参数stdin必须被设置为PIPE。同样,如果希望从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。
    4.3.4 Popen.send_signal(signal):向子进程发送信号
    4.3.5 Popen.terminate():停止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程
    4.3.6 Popen.kill():杀死子进程
    4.3.7 Popen.stdin:如果在创建Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令;否则返回None
    4.3.8 Popen.stdout:如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令;否则返回None
    4.3.9 Popen.stderr:如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令;否则返回None
    4.3.10 Popen.pid:获取子进程的进程ID
    4.3.11 Popen.returncode:获取进程的返回值。如果进程还没有结束,返回None
原创粉丝点击