Python学习笔记-内置函数

Posted kingleoric

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习笔记-内置函数相关的知识,希望对你有一定的参考价值。

json

SSAVL2470 10.90.24.81

将json编码的字符串转换为一个Python的数据结构

json_str = json.loads(doc)

如果将一个Python的数据结构转换为json编码的字符串用json.dumps(json_str)

如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:

# Writing JSON data

with open(‘data.json‘, ‘w‘) as f:

  json.dump(data, f)

# Reading data back

with open(‘data.json‘, ‘r‘) as f:

  data = json.load(f)

 

 

[[email protected] day]# cat check_codis2.py

#!/usr/bin/python

import json

 

class Student(object):

    def __init__(self, name, age, score):

        self.name = name

        self.age = age

        self.score = score

s = Student(‘Bob‘, 20, 88)

def student2dict(std):

    return {

        ‘name‘: std.name,

        ‘age‘: std.age,

        ‘score‘: std.score

    }

print(json.dumps(s, default=student2dict))

[[email protected] day]# python check_codis2.py

{"age": 20, "score": 88, "name": "Bob"}

 

存储需要监控的网页地址,并转换为字典:

[[email protected] day]# cat check_codis.py

#!/usr/bin/python

import urllib2

import json

response=urllib2.urlopen("http://10.130.11.211:8080/topom?forward=cep-codis-test")

doc = response.read()

json_str = json.loads(doc)

print json_str.keys()

print "compile is",json_str["compile"]

#print "stats is",json_str["stats"]

print "model is",json_str["model"]

print "version is",json_str["version"]

print "config is",json_str["config"]

[[email protected] day]# python check_codis.py

[u‘compile‘, u‘stats‘, u‘model‘, u‘version‘, u‘config‘]

compile is 2016-06-12 13:50:20 +0800 by go version go1.6.2 linux/amd64

model is {u‘start_time‘: u‘2016-06-22 16:51:56.982575937 +0800 CST‘, u‘pid‘: 4254, u‘sys‘: u‘Linux cep-elasearch-001.novalocal 2.6.32-504.1.3.el6.x86_64 #1 SMP Tue Nov 11 17:57:25 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux‘, u‘pwd‘: u‘/usr/local/go/src/github.com/CodisLabs/codis/bin‘, u‘admin_addr‘: u‘172.31.0.76:18080‘, u‘product_name‘: u‘cep-codis-test‘}

version is unknown version

config is {u‘coordinator_name‘: u‘zookeeper‘, u‘admin_addr‘: u‘0.0.0.0:18080‘, u‘coordinator_addr‘: u‘10.130.11.69:2181‘, u‘product_name‘: u‘cep-codis-test‘}

 

 

分解字典:

[[email protected] day]# cat check_codis6.py

#!/usr/bin/python

import urllib2

import json

response=urllib2.urlopen("http://10.130.11.211:8080/topom?forward=cep-codis-test")

doc = response.read()

json_str = json.loads(doc)

info = {}

info = json_str["stats"]

for k,v in info.items():

#    print "key is %s,value is %s" %(k,v)

#    print type(v)

    if type(v) == dict:

        for k1,v1 in v.items():

           # print "key1 is %s,value1 is %s" %(k1,v1)

           # print "value1 is %s" %(v1)

            print type(v1)

print ‘end ‘

 

[[email protected] day]# python check_codis6.py

<type ‘bool‘>

<type ‘dict‘>

<type ‘int‘>

<type ‘int‘>

<type ‘list‘>

<type ‘dict‘>

<type ‘list‘>

<type ‘dict‘>

End

 

subprocess

In [4]: stdin,stdout=os.popen2(‘sort‘)

In [5]: stdin.write(‘hello‘)

In [6]: stdin.write(‘world‘)

In [7]: stdin.write(‘zhailiang\n‘)

In [8]: stdin.write(‘123\n‘)

In [9]: stdin.close()

In [11]: stdout.read()

Out[11]: ‘123\nhelloworldzhailiang\n‘

 

In [13]: from subprocess import Popen,PIPE

 

In [14]: p=Popen([‘ls‘],stdin=PIPE,stdout=PIPE,stderr=PIPE)

 

In [15]: p.stdout

Out[15]: <open file ‘<fdopen>‘, mode ‘rb‘ at 0x184bd20>

 

In [16]: p.stdout.read()

Out[16]: ‘1_zhailiang.txt\n2_walk.py\n2_walk_yield.py\n3_du.py\nanaconda-ks.cfg\ncheck_call.py\ninstall.log\ninstall.log.syslog\npip-1.4.1\npip-1.4.1.tar.gz\npip-tools-1.4.0.tar.gz\nsetuptools-2.0\nsetuptools-2.0.tar.gz\nzhailianghash2.py\nzhailianghash.py\n‘

 

P是子进程,print "main process"是父进程,p.wait()表示子进程执行完后再执行父进程,将当前结果输出到当前屏幕上

 

[[email protected] ~]# cat  python 7_subprocess.py

cat: python: No such file or directory

#!/usr/bin/python

from subprocess import Popen,PIPE

#child

p=Popen([‘./test.sh‘],shell=True)

p.wait()

# farther

print "main process"

 

stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。他们可以是PIPE,文件描述符或文件对象,也可以设置为None,表示从父进程继承。

Popen.stdin:如果在创建Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。否则返回None。

Popen.stdout:如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回None。

Popen.stderr:如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回None。

默认父进程不等待新进程结束

[[email protected] ~]# python 7_subprocess.py

hello world

main process

 

以下该脚步相当于ls |grep py

[[email protected] ~]# cat 7_subprocess_1.py

#!/usr/bin/python

from subprocess import Popen,PIPE

p1=Popen([‘ls‘],stdout=PIPE)

p2=Popen([‘grep‘,‘py‘],stdin=p1.stdout,stdout=PIPE)

result=p2.stdout

for i in result:print i,

 [[email protected] ~]# python 7_subprocess_1.py

2_walk.py

2_walk_yield.py

3_du.py

7_subprocess_1.py

7_subprocess.py

check_call.py

。。。。。。

 

Communicate

 

Python执行shell:

#!/usr/bin/env python 

# -*- coding: utf-8 -*-

import os

import platform

import subprocess

import commands

def subproc():

    print "系统进程数:"

    subprocess.call("ps -ef|wc -l",shell=True)

def os_popen():

    print "IP地址:"

    os1 = platform.system()

    if os1 == "Linux":

           print os1

           ip1 =os.popen("/sbin/ifconfig eth0|grep ‘inet addr‘").read().strip().split(":")[1].split()[0]

           print "\033[1;32;40m%s\033[0m" % ip1

 

def os_system():

    os_command = ‘free -m‘

    cls_node1 = "命令执行成功...."

    cls_node2 = "命令执行失败...."

    if os.system(os_command) == 0:

        print "\n\033[1;32;40m%s\033[0m" % cls_node1

    else:

        print "\n\033[1;31;40m%s\033[0m" % cls_node2

def os_commands():

    (status, output) = commands.getstatusoutput(‘pwd‘)

    print status, output

def main():

    subproc()

    os_popen()

    os_system()

    os_commands()

if __name__ == "__main__":

main()

oracle中 python与SQL plus进行通信:

import os

from subprocess import Popen, PIPE

 

sqlplus = Popen(["sqlplus", "-S", "/", "as", "sysdba"], stdout=PIPE, stdin=PIPE)

sqlplus.stdin.write("select sysdate from dual;"+os.linesep)

sqlplus.stdin.write("select count(*) from all_objects;"+os.linesep)

out, err = sqlplus.communicate()

print out

 

This return output similar to:

 

SYSDATE

--------------

02-DEC-11

 

COUNT(*)

--------------

76147

还有个datetime的比较简单,就不记了

以上是关于Python学习笔记-内置函数的主要内容,如果未能解决你的问题,请参考以下文章

python学习笔记:装饰器生成器内置函数json

python学习笔记:装饰器生成器内置函数json

python学习笔记11-python内置函数

Python学习笔记-内置函数

python学习笔记 变量和内置函数

Python学习笔记4-内置函数