自动化脚本多线程运行

# -*- 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()
    
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:
        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,自动化)