自动化脚本多线程运行

列表解析: 可以引用操作符[]编写小的循环和判断。比for循环和其它迭代方法效率更高。

        eg: print([x for x in range(10)])


getopt模块:专门用来处理命令行参数


多线程脚本的入口:执行命令python sub_script.py  -j 4 -m

sub_script.py

# -*- coding:utf-8 -*-

import os,sys
from subprocess import Popen, PIPE, STDOUT
import getopt
from multiprocessing.pool import ThreadPool as Pool

def run_cmd(cmd):
    print(cmd)
    p = Popen(cmd)
    #(stdout,stderr)= p.communicate()

    retval = p.wait()

   return [True  if not retval else return False]

    
def call_mult_process():
    print("call_mult_process ...")
    if get_max_mem and os.name == 'posix':
        cmd = ["/usr/bin/time", "-v", "ping 127.0.0.1 -n 10"]
    else:
        cmd = ["ping 127.0.0.1 -n 10"]
    pool = Pool(processes = pjobs)
    raw_results = [pool.apply_async(run_cmd,(cmd)) for i in range(10)]
    #results = [r.get() for r in raw_results]
    pool.close()
    pool.join()
    
#self test
if __name__ == '__main__':
    pjobs = 2
    get_max_mem = None
    try:
        opts,argv = getopt.getopt(sys.argv[1:],"j:m")
    except getopt.GetoptError as err:
        print(err)

        sys.exit(0)


    for o,a in opts: #opts is dics
        if o == "-j":
            pjobs = int(a)
        elif o == "-m":
            get_max_mem = 1
    argv.insert(0,sys.argv[0])
    sys.argv = argv
    call_mult_process()
        

你可能感兴趣的:(python)