Sixth day of the Python 11 issue

Source: Internet
Author: User

Common built-in modules

One, json/pickle string

1. JSON

Data exchange between different languages, and memory data exchange between different programs.

is similar to XML.


Import JSON


a={

' DB ': [1, ' Wang '],

' Home ': [' Zhang ', 45],

' Host ': {' name ': ' Ting ', ' age ': 24}

}


#将json写入文件

My_json=json.dumps (a)

F=file (' Data.txt ', ' WB ')

F.write (My_json)


#从文件中读取json

Af2=file (' data.txt ', ' RB ')

Af=af2.read ()

Json_data=json.loads (AF)

Af2.close ()


Dumps and loads are used in programs, dump and load can be written directly to the file, and loaded from the file.


2, Pickle


Import Pickle

a={

' DB ': [1, ' Wang '],

' Home ': [' Zhang ', 45],

' Host ': {' name ': ' Ting ', ' age ': 24}

}

#将字典数据pickle化写入文件

F=file (' Pickle1.txt ', ' W ')

Pickle.dump (A,F)

#从文件中读取pickle的数据:

F=file (' Pickle1.txt ', ' R ')

Pickle2=pickle.load (f)

print ' ===> ', pickle2


Pickle can serialize most of the python data structures, including time formats, classes, functions, and so on.


Note: When you pass files from Windows to Linux, that is, when you upload files across platforms, the official recommendation is ' RB ' or ' WB ' when you open files in Python. such as: File ('/tmp ', ' RB ')


Second, system-related modules

Execute system command:

Os.system () #只返回执行状态

os.spawn*

Os.popen () #可以返回执行结果, but will be discarded

The module that is about to be discarded (this module is not suitable for use on Windows, error):

Commands

Commands.getoutput (' dir ') #获取命令的结果

Commands.getstatus (' dir ') #获取命令的执行状态

Commands.getstatusoutput () #返回结果和状态


Third, subprocess

The above discarded modules are replaced by this module: subprocess

Subprocess.call ([' dir '],shell=true) #直接执行命令, no return result


#以下命令会把执行结果返回给变量

Cmd2=subprocess.check_output ([' dir '],shell=true)

Print CMD2


Check_call is thrown when a command executes an error, and when execution succeeds, it is the same as call.

Cmd2=subprocess.check_call ([' dir '],shell=true)


Popen similar to Os.popen:

Subprocess. Popen (...)


Used to perform complex system commands

Parameters:

The Args:shell command, which can be a string or sequence type (for example: list, tuple)

BufSize: Specifies buffering. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering

stdin, stdout, stderr: Indicates the standard input, output, and error handles of the program, respectively

PREEXEC_FN: Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run

CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process.

Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process.

Shell: Ibid.

CWD: Used to set the current directory of child processes

ENV: The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.

Universal_newlines: Different system line breaks differ, True----agree to use \ n

Startupinfo and Createionflags are only valid under Windows

will be passed to the underlying CreateProcess () function to set some properties of the child process, such as: the appearance of the main window, the priority of the process, etc.

Here are some examples:

Import subprocess

Ret1 = subprocess. Popen (["mkdir", "T1"])

Ret2 = subprocess. Popen ("mkdir T2", shell=true)

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

obj = subprocess. Popen ("mkdir T3", Shell=true, cwd= '/home/dev ',)

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

Import subprocess

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

obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE)

Obj.stdin.write (' Print 1 \ n ')

Obj.stdin.write (' Print 2 \ n ')

Obj.stdin.write (' Print 3 \ n ')

Obj.stdin.write (' Print 4 \ n ')

Obj.stdin.close ()


Cmd_out = Obj.stdout.read ()

Obj.stdout.close ()

Cmd_error = Obj.stderr.read ()

Obj.stderr.close ()


Print Cmd_out

Print Cmd_error

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

Import subprocess


obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE)

Out_error_list = obj.communicate (' print ' hello ')

Print Out_error_list

##

This article from "Linux World" blog, declined reprint!

Sixth day of the Python 11 issue

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.