Python learns day14 processes and threads

Source: Internet
Author: User
Tags nslookup

    Process

#********* Creating a single process through process fromMultiprocessingImportProcessImportOS#code to be executed by the child processdefRun_proc (name):Print('Run Child process%s (%s) ...'% (name, Os.getpid ()))#gets the name of the current process, the PID valueif __name__=='__main__': Print('Parent process%s.'%os.getpid ()) P= Process (Target=run_proc, args= ('Test',))#the name of the function passing in the child process, giving the child process a name Print('Child process would start.') P.start () P.join ()Print('Child process end.')#Parent process 9976.#Child process would start.#Run Child Process Test (9368) ...#Child process end.#************* creates multiple processes through the pool, with parameters within the pool being the maximum number of concurrently executing processes fromMultiprocessingImportPoolImportOS, time, RandomdefLong_time_task (name):Print('Run Task%s (%s) ...'%(name, Os.getpid ())) Start=time.time () time.sleep (Random.random ()* 3) End=time.time ()Print('Task%s runs%0.2f seconds.'% (name, (End-start )))if __name__=='__main__': Print('Parent process%s.'%os.getpid ()) P= Pool (4) forIinchRange (5): P.apply_async (long_time_task, args=(i,))Print('waiting-subprocesses done ...') P.close () P.join ()Print('All subprocesses is done .')#Parent process 8808.#waiting-subprocesses done ...#Run Task 0 (2956) ...#Run Task 1 (5296) ...#Run Task 2 (8432) ...#Run Task 3 (8412) ...#Task 3 runs 0.10 seconds.#Run Task 4 (8412) ...#Task 2 runs 0.41 seconds.#Task 4 runs 1.61 seconds.#Task 1 runs 1.90 seconds.#Task 0 runs 2.09 seconds.#All subprocesses is done .#****************** subprocess can let us start a child process conveniently, and then control its input and output, Nslookup is a command under the terminal, can find the IP of the specified URLImportsubprocessPrint('$ nslookup www.python.org') R= Subprocess.call (['nslookup','www.python.org'])#A child process was created and Nslookup www.python.org was enteredPrint('Exit Code:', R)" "" "#************** If the child process also needs input, you can enter it through the communicate () methodImportsubprocessPrint('$ nslookup') P= subprocess. Popen (['nslookup'], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, stderr=subprocess. PIPE) output, err= P.communicate (b'Set q=mx\npython.org\nexit\n')Print(Output.decode ('GBK'))#Print (Output.decode (' utf-8 ')) source code is utf-8 but will error, look at the comments below is the coding problem, change to GBK is good#because pycharm default is Utf-8, which also leads to the above example is garbled, ' $ nslookup www.baidu.com ' equivalent to the command run in cmd, the command is displayed after the result is also cmd results, \#and the cmd itself default encoding is GBK, so there will be garbled. Workaround: File>>settings>>file encodings>>project Encoding: (select GBK)Print('Exit Code:', P.returncode)#The above code is equivalent to executing command nslookup at the command line, and then manually entering:#Set Q=MX#python.org#Exit#The output is as follows#$ nslookup#server:192.168.19.4#address:192.168.19.4#53# #non-authoritative Answer:#python.org Mail exchanger = mail.python.org.# #authoritative answers can found from:#mail.python.org Internet address = 82.94.164.166#mail.python.org has AAAA address 2001:888:2000:d::a6# # #Exit code:0#************* inter-process communication fromMultiprocessingImportProcess, QueueImportOS, time, Random#code to write the data Process execution:defWrite (q):Print('Process to write:%s'%os.getpid ()) forValueinch['A','B','C']: Print('Put%s to queue ...'%value) q.put (value) time.sleep (Random.random ())#read the code that the data process executes:defRead (q):#Incoming queue () queues through Q so you can save the data. Print('Process to read:%s'%os.getpid ()) whileTrue:value= Q.get (True)#the True here is actually a parameter (block=true), which means that it is blocked when there is no data in the queue Print('Get%s from queue.'%value)if __name__=='__main__': #The parent process creates a queue and passes it to each child 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, can not wait for its end, can only forcibly terminate:Pr.terminate ()

Python learns day14 processes and threads

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.