天天看點

python 多程序與子程序

點選(此處)折疊或打開

  1. #!/usr/bin/env python3
  2. #-*- coding:utf-8 -*-
  3. '''
  4. #多程序,pool
  5. from multiprocessing import Process
  6. from multiprocessing import Pool
  7. import os
  8. import time
  9. import random
  10. def f(name):
  11.     print('hello, %s,pid=%s' % (name, os.getpid()))
  12. if __name__ == '__main__':
  13.     print('Parent process %s ' % os.getpid())
  14.     p=Process(target=f, args=('talen',))
  15.     print('Child process will start.')
  16.     p.start()
  17.     p.join()
  18.     print('Child process end')
  19. def long_time_task(name):
  20.     print('Run task %s (%s)...' % (name,os.getpid()))
  21.     start=time.time()
  22.     time.sleep(random.random() * 3)
  23.     end=time.time()
  24.     print('Task %s runs %0.2f seconds' % (name,(end - start )))
  25.     pp=Pool(4)
  26.     for i in range(6):
  27.         pp.apply_async(long_time_task,args=(i,))
  28.     pp.close()
  29.     pp.join()
  30. #子程序
  31. import subprocess
  32. print('$ nslookup htfchina.blog.chinaunix.net')
  33. r = subprocess.call(['nslookup','htfchina.blog.chinaunix.net'])
  34. print('Exit code :',r)
  35. #輸入網址
  36. print('$ nslookup')
  37. subp=subprocess.Popen(['nslookup '], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  38. output, err = subp.communicate(b'set q=mx\nwww.baidu.com\nexit\n')
  39. print(output.decode('utf-8'))
  40. print('Exit code:',subp.returncode)
  1. /usr/bin/python3 /home/t/PycharmProjects/untitled/mutliprocessing_t.py
  2. Parent process 14001
  3. Child process will start.
  4. hello, talen,pid=14002
  5. Child process end
  6. Run task 0 (14003)...
  7. Run task 1 (14004)...
  8. Run task 2 (14005)...
  9. Run task 3 (14006)...
  10. Task 3 runs 0.02 seconds
  11. Run task 4 (14006)...
  12. Task 0 runs 2.07 seconds
  13. Run task 5 (14003)...
  14. Task 1 runs 2.46 seconds
  15. Task 4 runs 2.58 seconds
  16. Task 2 runs 2.97 seconds
  17. Task 5 runs 2.33 seconds
  18. $ nslookup htfchina.blog.chinaunix.net
  19. Server:        10.10.106.201
  20. Address:    10.10.106.201#53
  21. Non-authoritative answer:
  22. Name:    htfchina.blog.chinaunix.net
  23. Address: 61.55.167.140
  24. Exit code : 0
  25. $ nslookup
  26. www.baidu.com    canonical name = www.a.shifen.com.
  27. Authoritative answers can be found from:
  28. a.shifen.com
  29.     origin = ns1.a.shifen.com
  30.     mail addr = baidu_dns_master.baidu.com
  31.     serial = 1605030003
  32.     refresh = 5
  33.     retry = 5
  34.     expire = 86400
  35.     minimum = 3600
  36. Exit code: 0
  37. Process finished with exit code 0