Re-learning the Python series (iv)? WTF?

Source: Internet
Author: User
Tags base64 unpack

Multi-process:

fork()Called once, returned two times, because the operating system automatically copies the current process (called the parent process) to a copy (called a child process),

It then returns within the parent and child processes, respectively
getppid()得到ID of Parent Process
getpid() 得到当前进程的ID

# Multiprocessing.pyimport Osprint ' Process (%s) start ... '% os.getpid () pid = Os.fork () If pid==0:    print ' I am child PR  Ocess (%s) and my parent are%s. '% (Os.getpid (), Os.getppid ()) Else:    print ' I (%s) just created a child process (%s). ' % (Os.getpid (), PID) Process (876) Start ... I (876) just created a child process (877). I am Child process (877) and my parent is 876.

Communication between Processes:

From multiprocessing import process, Queueimport OS, time, random# writes the code of the Data processing execution: def write (q):    for value in [' A ', ' B ', ' C ']:        print ' Put%s to queue ... '% value        q.put (value)        Time.sleep (Random.random ()) # Read data Process Execution code: def read (q): While    True:        value = Q.get (true)        for print ' Get%s from queue. '% valueif __name__== ' __main__ ':    # Parent process creates a queue, and passed to each sub-process:    q = Queue ()    PW = Process (Target=write, args= (Q,))    PR = Process (Target=read, args= (Q,))    # Start child process PW, write:    Pw.start ()    # start child process PR, read:    Pr.start ()    # Wait for PW to end:    pw.join ()    # PR process is a dead loop, Cannot wait for its end, only forcibly terminates:    Pr.terminate ()

Multithreading:

Python's standard library provides two modules: thread and threading , is the thread low-level module, threading is the Advanced module, the thread encapsulation.

In most cases, we only need to use threading this advanced module.

Starting a thread is to pass a function in and create an Thread instance, and then call to start() start executing:

#coding =utf-8import time, threading# code executed by the new thread: Def loop ():    print ' thread%s is running ... '% threading.current_thread (). Name    n = 0 while    N < 5:        n = n + 1        print ' thread%s >>>%s '% (Threading.current_thread (). NA Me, N)        time.sleep (1)    print ' thread%s ended. '% Threading.current_thread (). Nameprint ' thread%s is running ... '% t Hreading.current_thread (). Namet = Threading. Thread (Target=loop, name= ' Loopthread ') T.start () t.join () print ' thread%s ended. '% Threading.current_thread (). Name

。。。。。。。

collectionsThe module provides some useful collection classes that can be selected as needed.

Defaultdict

dictwhen used, if the referenced key does not exist, it will be thrown KeyError . If you want to return a default value when the key does not exist, you can use defaultdict :

#coding =utf-8from Collections Import DEFAULTDICTDD = Defaultdict (lambda: ' N/a ') dd[' a '] = 123print dd[' A ']print dd[' B ']
Ordereddict

dictwhen used, key is unordered. We were dict unable to determine the order of the keys when doing iterations.

If you want to keep the key in order, you can use OrderedDict :

OrderedDictYou can implement a FIFO (first-in-one-out) dict, deleting the first added key when the capacity exceeds the limit:

。。。。。。。。。。。。。。

Base64

>>> base64.b64encode (' i\xb7\x1d\xfb\xef\xff ') ' abcd++//' >>> base64.urlsafe_b64encode (' i\xb7\x1d \xfb\xef\xff ' abcd--__ ' >>> base64.urlsafe_b64decode (' abcd--__ ') ' I\xb7\x1d\xfb\xef\xff '

Python counter Count

#-*-Coding:utf-8-*-"" "  Python Counter counter  Import Module Collections" "" Import collections # Count the occurrences of each character, returning obj as a dictionary Collections. Counter (' Adfsdfsdfswrwerwegfhgfhgh ') print obj# elements = Native Incoming value (' Adfsdfsdfswrwerwegfhgfhgh ') for V in Obj.elements ():    Print v # returns the number given by the parameter to print Obj.most_common (4)

#The execution results show Counter ({‘F': 5,‘D': 3,‘G': 3,‘H': 3,‘S': 3,'w': 3, 'e': 2, 'r': 2, 'a': 1} ' [('f', 5 '), ( 'D', 3), ('g', 3), ('h', 3)]

Please write a = base64 decoding function that can handle the removed:

Import base64text = ' Ywjjza ' if not len (text)%4==0:    print base64.b64decode (text+ "=" * (len (text)%4))

structpackfunction to turn any data type into a string:

>>> Import struct>>> struct.pack (' >i ', 10240099) ' \x00\[email protected] '

Turn it unpack str into the appropriate data type:

>>> struct.unpack (' >ih ', ' \xf0\xf0\xf0\xf0\x80\x80 ') (4042322160, 32896)

Re-learning the Python series (iv)? WTF?

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.