1. 程式人生 > >Python學習筆記-內置函數

Python學習筆記-內置函數

lin model http go1.6 inf dba 發送 繼承 print

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)

[root@SSAVL2470 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))

[root@SSAVL2470 day]# python check_codis2.py

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

存儲需要監控的網頁地址,並轉換為字典:

[root@SSAVL2470 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"]

[root@SSAVL2470 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‘}

分解字典:

[root@SSAVL2470 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 ‘

[root@SSAVL2470 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()表示子進程執行完後再執行父進程,將當前結果輸出到當前屏幕上

[root@SSAVL2614 ~]# 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。

默認父進程不等待新進程結束

[root@SSAVL2614 ~]# python 7_subprocess.py

hello world

main process

以下該腳步相當於ls |grep py

[root@SSAVL2614 ~]# 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,

[root@SSAVL2614 ~]# 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學習筆記-內置函數