2018-05-18 Python samples

part 1

https://blog.csdn.net/mr_evanchen/article/details/77879967

# -*- coding: UTF-8 -*-
import bottle

import json
import re
import time
import uuid
from datetime import date, datetime, timedelta
from bottle import get, post, request


config = {
    'user' : 'demo',
    'password' : '123456',
    'host' : '10.12.2.87',
    'database' : 'testdb',
    'raise_on_warnings' : True,
    }

client_tokens = {
    #token for FOXTEL sanity test, PC in Beijing
    #'Y' == enabled
    'foxtel_beijing_pc':'Y'
    }

def verify_client_token(client_tok):
    '''
    If the token is there and the token is enabled.
    '''
    ret_val = False
    
    if client_tokens.has_key(client_tok):
        if client_tokens[client_tok] == 'Y':
            ret_val = True
    return ret_val

@bottle.route('/task/add', method= ['GET', 'POST'])
def execution_schedule_add():
    '''
    Add a task into the queue
    1. Abstract the parameters
    2. Append a task into the queue
    '''    
    #method should not be 'get'
    '''
    if bottle.request.method == 'GET':
        return ''

    #to-do: abstract parameters
    token = bottle.request.POST.get('tok')

    if verify_client_token(token) is False:
        return ''
    '''
    print str(bottle.request.body.readlines())
    job_assigment_id = bottle.request.POST.get('job_assigment_id')
    script_name = bottle.request.POST.get('script_name')
    script_parameter = bottle.request.POST.get('script_parameter')
    slot_id = bottle.request.POST.get('slot_id')


    if job_assigment_id is None:
        #debug, error
        job_assigment_id = "123123"
        script_name = "test_tools_ft_0000_SampleScript.py"
        script_parameter = "None"
        slot_id = "1"

    print job_assigment_id, script_name, script_parameter, slot_id
    
    #create a task with time-stamp
    t_timestamp = str(int(time.time() * 100))
    f_name = "s" + t_timestamp + ".txt"
    task_file = open(".\\dart_task_q\\" + f_name,'w')
    task_file.write(job_assigment_id + '\n')
    task_file.write(script_name + '\n')
    task_file.write(script_parameter + '\n')
    task_file.write(slot_id + '\n')
    task_file.close()

    return f_name


@bottle.route('/')
def index():
    return 'hello'

if __name__ == '__main__':
    #bottle.run(host = '127.0.0.1', port = 9996)
    bottle.run(host = '10.12.2.147', port = 9091)

part 2

# -*- coding: UTF-8 -*-
import datetime
import glob
import os
import re
import shutil
import stat
import subprocess
import time

def clear_folder(target_path):
    for item in os.listdir(target_path):
        path_file = os.path.join(target_path, item)
        if os.path.isfile(path_file):
            pass
        else:
            shutil.rmtree(path_file)
    return

def abstract_script_result_from_log_line(the_line):    
    if "Result = Pass" in the_line:
        return "Pass"
    if "Result = Fail" in the_line:
        return "Fail"
    else:
        return "Error"

def convert_script_result_to_code(the_result):
    if the_result == "Pass":
        return '111'
    if the_result == "Fail":
        return '100'
    if the_result == "Block":
        return '101'
    else:
        return '000'
    
def abstract_time_tick_from_log_line(the_line):
    the_tick = ""
    the_tick = the_line.split(':')[0]
    
    the_tick = time.strptime(the_tick, '%Y-%m-%d %H-%M-%S')
    the_tick = time.mktime(the_tick)
    return the_tick

def analyze_log(target_path):
    '''
    Pre-condition:
        There is only one log inside the folder
    Post-condition:
        Return the data collected from the log
    Exception:
        If the folder is empty, still return None/Error values
    '''
    script_start_time = None
    script_end_time = None
    script_status_code = "000" #default to be Error(000)
    for item in os.listdir(target_path):
        path_file = os.path.join(target_path, item)
        if not os.path.isfile(path_file):
            stdout_path = os.path.join(path_file, "stdout.txt")
            stdout_f = open(stdout_path, 'r')
            stdout_contents = stdout_f.readlines()
            
            first_line = stdout_contents[0].strip()
            script_start_time = abstract_time_tick_from_log_line(first_line)

            last_line = stdout_contents[-1].strip()
            script_end_time = abstract_time_tick_from_log_line(last_line)

            script_execution_status = abstract_script_result_from_log_line(last_line)
            script_status_code = convert_script_result_to_code(script_execution_status)
    
    return script_start_time, script_end_time, script_status_code
        
def tick_to_string(time_tick):
    return time.strftime('%Y-%m-%dT%H:%M:%SZ',time.localtime(time_tick))


def tester():
    script_start_time, script_end_time, script_status_code = analyze_log(".\\Log_cases")
    print script_start_time, script_end_time, script_status_code
    print time.time()
    print tick_to_string(time.time())
    print datetime.datetime.strptime(tick_to_string(time.time()), "%Y-%m-%dT%H:%M:%SZ")
    exit(0)

def schedule_get_parameters(schedule_file):
    sche_f = open(schedule_file, 'r')
    sche_contents = sche_f.readlines()
    sche_f.close()

    assignment_id = None
    script_name = None

    try:
        #1st line = assignment id
        assignment_id = sche_contents[0].strip()
        #2nd line = script name
        script_name = sche_contents[1].strip()

        #3rd line = script_parameter
        script_parameter = sche_contents[2].strip()

        #4rd line = slot id
        slot_id = sche_contents[3].strip()
    except:
        return None
    

    return (assignment_id, script_name, script_parameter, slot_id)

if __name__ == '__main__':


    while True:
        f_selected = None
        arr_files = []
        #filter the task files 
        arr_files = glob.glob(".\\dart_task_q\\"+"/s*.txt")
        if len(arr_files) > 0:
            #find the 1st one in the queue
            min_val = 999999000000
            for sub_file in arr_files:
                f_name = os.path.basename(sub_file)
                v_tick = long(f_name.replace('s', '').replace('.txt','').strip())
                if v_tick < min_val:
                    min_val = v_tick

            f_selected = "s" + str(min_val) + ".txt"
            f_selected = os.path.join(".\\dart_task_q\\", f_selected)
        else:
            pass

        
        #collect the parameters
        p_tuple = None
        if f_selected is not None:
            p_tuple = schedule_get_parameters(f_selected)

        if p_tuple is not None:
            assignment_id = p_tuple[0]
            script_name = p_tuple[1]            
            slot_id = p_tuple[3]
            
            print assignment_id, script_name, slot_id
            #notify the server of the start

            #clear the log file folder
            clear_folder(".\\Log_cases")
            
            #clear the old schedule file
            if os.path.exists("execution_schedule.txt"):
                os.remove("execution_schedule.txt")

            #prepare the schedule file
            o_f = open("execution_schedule.txt", 'w')
            o_f.write(script_name)
            o_f.close()

            #run the script
            r_start_time = time.time()
            str_command = r"python O_runner.py --device {0}".format(slot_id)
            print str_command
            process = subprocess.Popen(str_command.strip(), shell=True)
            process.wait()
            r_end_time = time.time()

            #collect the data from log
            script_start_time, script_end_time, script_status_code = analyze_log(".\\Log_cases")

            if script_start_time is None:
                #script is not executed
                script_start_time = r_start_time
                script_end_time = r_end_time
                pass
            print tick_to_string(script_start_time)
            print tick_to_string(script_end_time)
            print script_status_code

            #copy the log-file to some public address
            
            #report back the data

            #delete the task file
            
            if os.path.exists(f_selected):
                os.remove(f_selected)
            
        else:
            pass
            
        #wait for next one
        time.sleep(5)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,463评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,868评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,213评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,666评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,759评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,725评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,716评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,484评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,928评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,233评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,393评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,073评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,718评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,308评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,538评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,338评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,260评论 2 352

推荐阅读更多精彩内容