Python Learning notes-built-in functions

Source: Internet
Author: User

Json

SSAVL2470 10.90.24.81

Converts a JSON-encoded string into a Python data structure

Json_str = Json.loads (DOC)

If you convert a Python data structure to a JSON-encoded string with Json.dumps (JSON_STR)

If you are dealing with files instead of strings, you can use Json.dump () and Json.load () to encode and decode JSON data. For example:

# 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": +, "score": "," "Name": "Bob"}

Store the address of the Web page you want to monitor and convert it to a dictionary:

[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.nova Local 2.6.32-504.1.3.el6.x86_64 #1 SMP Tue Nov 17:57:25 UTC 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 '}

Decomposition dictionary:

[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%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 [All]: Stdout.read ()

OUT[11]: ' 123\nhelloworldzhailiang\n '

in [+]: from subprocess import popen,pipe

In []: P=popen ([' ls '],stdin=pipe,stdout=pipe,stderr=pipe)

In []: P.stdout

OUT[15]: <open file ' <fdopen> ', mode ' RB ' at 0x184bd20>

in [+]: 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 is a child process, the print "main process" is the parent process, p.wait () indicates that the child process finishes executing the parent process, outputting the current result to the current screen

[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, respectively, represent the standard input, output, and error handles of the program. They can be pipe, file descriptor or file object, or set to none, which means inheriting from the parent process.

Popen.stdin: If the Popen object is created, the parameter stdin is set to Pipe,popen.stdin will return a file object for the policy child process send instruction. Otherwise, none is returned.

Popen.stdout: If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, none is returned.

Popen.stderr: If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, none is returned.

Default parent process does not wait for new process to end

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

Hello World

Main process

The following steps are equivalent to 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 execution Shell:

#!/usr/bin/env python

#-*-Coding:utf-8-*-

Import OS

Import Platform

Import subprocess

Import commands

Def subproc ():

Print "System process number:"

Subprocess.call ("Ps-ef|wc-l", Shell=true)

Def os_popen ():

Print "IP address:"

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 = "Command execution succeeded ...."

cls_node2 = "Command execution failed ...."

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 ()

Python in Oracle communicates with 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

There's a more simple datetime, and I don't remember.

Python Learning notes-built-in functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.