예제 #1
0
파일: Core.py 프로젝트: jacklaiu/MasterJack
 def get_html_forWencai(self, url):
     browser = None
     try:
         browser = webdriver.Chrome(
             os.path.abspath('.') + '\driver\chromedriver.exe')
         browser.get(url)
         time.sleep(4)
         browser.implicitly_wait(1)
         try:
             isClicked = False
             elem70 = browser.find_element_by_css_selector(
                 '#resultWrap #showPerpage select option[value="70"]')
             if elem70 is not None and isClicked == False:
                 elem70.click()
                 isClicked = True
             elem50 = browser.find_element_by_css_selector(
                 '#resultWrap #showPerpage select option[value="50"]')
             if elem50 is not None and isClicked == False:
                 elem50.click()
                 isClicked = True
             elem30 = browser.find_element_by_css_selector(
                 '#resultWrap #showPerpage select option[value="30"]')
             if elem30 is not None and isClicked == False:
                 elem30.click()
             time.sleep(5)
         except:
             lu.log("get_html_forWencai Execption")
         html = browser.execute_script(
             "return document.documentElement.outerHTML")
         browser.quit(
         )  # 关闭浏览器。当出现异常时记得在任务浏览器中关闭PhantomJS,因为会有多个PhantomJS在运行状态,影响电脑性能
         return html
     except Exception as e:
         browser.quit()
         return None
예제 #2
0
    def DoWorkWrapper(self, p_do_work_func: callable):

        try:
            p_do_work_func(self.request)

            if self.StatusCode == sc.HTTP_RESTFULL_STATUS_CODES.NOT_SET:
                self.StatusCode = sc.HTTP_RESTFULL_STATUS_CODES.OK
                self.StatusMsg = sc.HTTP_RESTFULL_STATUS_DESC.SHORT_DESC(
                    sc.HTTP_RESTFULL_STATUS_DESC.OK)

                temp_dict: dict = self.EventReturn
                temp_dict['lambda_name'] = self.LambdaName
                temp_dict['status_code'] = self.StatusCode
                temp_dict['status_msg'] = self.StatusMsg

                self.Logger.info('Work done successfully')

                self.Logger.debug('Data Returned From lambda:', **temp_dict)

        except AssertionError as ae:
            self.StatusMsg = sc.HTTP_RESTFULL_STATUS_CODES.SHORT_DESC(
                sc.HTTP_RESTFULL_STATUS_DESC.ASSERTION_ERROR)
            self.StatusCode = sc.HTTP_RESTFULL_STATUS_CODES.ASSERTION_ERROR
            self.Logger.critical(self.StatusMsg,
                                 error_msg=ae.args[0],
                                 formatted_exp=lu.format_exception(ae))

        except Exception as e:
            self.StatusMsg = sc.HTTP_RESTFULL_STATUS_CODES.SHORT_DESC \
                (sc.HTTP_RESTFULL_STATUS_DESC.TRAPPED_UNEXPECTED_ERROR)
            self.StatusCode = sc.HTTP_RESTFULL_STATUS_CODES.TRAPPED_UNEXPECTED_ERROR
            self.Logger.fatal(self.StatusMsg,
                              error_msg=e.args[0],
                              formatted_exp=lu.format_exception(e))
예제 #3
0
def syncQueueControl():
    startTime = datetime.datetime.now()
    sourceApkList = os.listdir(sourceApkPath)
    for apk in sourceApkList:
        if apk.find('.DS_Store') > -1:
            continue
        apkname = obtain_apk_name(apk)
        if not apkname:
            LogUtil.error('读取apks目录下apk文件出错')
            continue

        configFilePath(apkname)

        if generateDict(apkname) is not None:
            LogUtil.warning(apkname + '没有在json匹配文件中......')
            continue


        if decompile(apk):
            type = modifyapp(apkname)
            if type == Leave_Type.goon:
                continue
    endTime = datetime.datetime.now()
    print("all work is done! 总耗时/秒:", (endTime - startTime).total_seconds())
    input('请按下任意键退出控制台窗口...')
    pass
예제 #4
0
def download_m4a(filename, vkey, save_filename):
    header = {
        'Accept':
        '*/*',
        'Accept-Encoding':
        'identity;q=1, *;q=0',
        'Accept-Language':
        'zh-CN,zh;q=0.9',
        'Connection':
        'keep-alive',
        'cache-control':
        'max-age=0',
        "Host":
        "dl.stream.qqmusic.qq.com",
        "Range":
        "bytes=0-",
        'user-agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }

    # url地址可以浏览器分析获取,主要是&w参数
    url = 'http://dl.stream.qqmusic.qq.com/%s?vkey=%s&guid=5789371178&uin=0&fromtag=66' % (
        filename, vkey)
    LogUtil.i('Downloading m4a :' + url + '\n')
    request = urllib2.Request(url, headers=header)
    try:
        html = urllib2.urlopen(request).read()
        write_file(save_filename, html)
    except Exception, e:
        print 'm4a error:', e.message, '\n'
        html = None
예제 #5
0
def replace_applicationID2(apkname):
    target_applicationid = boss2[ELEMENT_TAG_APPLICATION_ID]
    if not target_applicationid:
        return

    print('开始替换包名流程')

    current_package = current_packages[apkname]
    manifest_xml = local_config['manifest_xml']
    grammar = '//*[starts-with(@*,{package})]'.format(package=current_package)

    try:
        tree = etree.parse(manifest_xml)
        doc = tree.xpath(grammar)
        for ele in doc:
            attributes = ele.attrib
            for n in attributes.items():
                if n[1].startswith(current_package):
                    newValue = n[1].replace(current_package,
                                            target_applicationid)
                    ele.set(n[0], newValue)
        tree.write(manifest_xml,
                   pretty_print=True,
                   encoding='utf-8',
                   xml_declaration=True)
        set_current_package(apkname, target_applicationid)
        print('完成包名替换流程')
    except:
        LogUtil.error('包名替换流程异常')
        sys.exit()
    pass
예제 #6
0
def updateWeightInfo(weightInfo64, weightInfo128):
    data = weightInfo64 + weightInfo128
    print("updateWeightInfo#", len(data))
    LogUtil.d(data)

    # 有变化就更新UI
    if not shelfConfigureInfo:
        print("************* 无法获取货架配置信息 ********")
        # 请求配置信息
        shelfThread = threading.Thread(name="Shelf-Configure",
                                       target=getShelfConfigure)
        shelfThread.start()
        return
    global weightData
    global weightScene
    if not weightData:
        weightData = data

    flag, itemInfo = compareGoodsWeight(data, weightData)

    if flag:
        weightData = data
        # todo 更新UI,显示识别结果
        thread = Runthread.Runthread()
        thread.setRequest(itemInfo)
        thread._signal.connect(weightScene.updateScene)
        thread.start()
예제 #7
0
    def test_tail(self):
        with open("/tmp/testtail", "w+") as F:
            F.write(u"abcdefghijklmnopqrstu\u6211vwxyz".encode("utf-8"))
        tail = lu.tail("/tmp/testtail", 2)
        self.assertEquals("yz", tail)

        tail = lu.tail("/tmp/testtail")
        self.assertEquals("abcdefghijklmnopqrstuvwxyz", tail)
예제 #8
0
def startListenZhangting():
    threadLocal = ThreadLocal()
    if Config.Enable == True:
        thread1 = ListenZhangtingThread(1, Config.QueryWords, Config.StartTime,
                                        Config.EndTime, threadLocal)
        thread1.start()
        pm.sendListenStartEmail()
        lu.log("监听程序启动")
예제 #9
0
    def test_tail(self):
        with open("/tmp/testtail", "w+") as F:
            F.write(u"abcdefghijklmnopqrstu\u6211vwxyz".encode("utf-8"))
        tail = lu.tail("/tmp/testtail", 2)
        self.assertEquals("yz", tail)

        tail = lu.tail("/tmp/testtail")
        self.assertEquals("abcdefghijklmnopqrstuvwxyz", tail)
예제 #10
0
def loadconfig2():
    print('读取config.xml')
    try:
        tree = ET.parse(xmlConfigPath)
        return tree
    except Exception as e:
        LogUtil.error('读取config.xml异常,请检查文件')
        raise
    pass
예제 #11
0
def buyAction(code, name, price, posi):
    config_words = code + "," + name + "," + posi + "," + price + ",0"
    f_config = open('C:/auto/BuyAction.txt', 'w')
    f_config.write(config_words)
    f_config.close()
    pm.sendBuyDoneEmail(code)
    lu.log("已写入执行句子:" + config_words)
    f = open('persist.txt', 'w')
    f.write(code)
    f.close()
예제 #12
0
def loadconfig():
    print('读取match.json开始')
    try:
        with open(matchJsonFile, "r", encoding='utf-8') as f:
            global founder
            founder = json.load(f)
        print('读取match.json完成')
    except Exception as e:
        LogUtil.error('读取match.json异常,请检查文件')
        LogUtil.error(e)
        return False
    pass
예제 #13
0
def generateDict(apkname):
    print('读取match.json开始')
    try:
        with open(matchJsonFile, "r", encoding='utf-8') as f:
            data = json.load(f)
            if not apkname in data:
                return False
            handleJson(data, apkname)

        print('读取match.json完成')
    except Exception as e:
        LogUtil.error('读取match.json异常,请检查文件')
        print(traceback.print_exc())
        sys.exit()
    pass
예제 #14
0
def draw_patch(x_app, folder_path, sub_in=False):
    global app
    app = x_app
    try:
        if not os.path.isfile(folder_path) and not os.path.isdir(folder_path):
            LogUtil.log_e('输入的既不是文件也不是文件夹')
            return
        if os.path.isdir(folder_path):
            for index, file_path in enumerate(batch_deal(folder_path, sub_in)):
                # print(index, file_path)
                generation(file_path)
        else:
            generation(folder_path)
    except BaseException, e:
        LogUtil.log_e(e.message)
예제 #15
0
def startDevice(scene):
    LogUtil.d("**************** 货架开始启动 ****************")
    print("startDevice#")
    global weightScene
    weightScene = scene

    # 请求配置信息
    shelfThread = threading.Thread(name="Shelf-Configure",
                                   target=getShelfConfigure)
    shelfThread.start()

    # 启动称重设备
    weightThread = threading.Thread(name="Weight-Device",
                                    target=WeightShelf.startApp)
    weightThread.start()
예제 #16
0
def connect_test(host):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  server_address = (host, 6379)
  stopwatch = StopWatch()
  message = 'success'
  try :
    sock.connect(server_address)
  except socket.error as e:
    message = str(e)
  finally :
    stopwatch.stop()
    try :
      sock.close()
    except :
      pass
  if( message != 'success') :
    LogUtil.writeLog(stopwatch.getStartTime(), stopwatch.getElapsedTime(), host, 'SOCKET', message)
예제 #17
0
def replace_real_skin(key, color_except_prefix):
    print('开始替换主题颜色')
    num = 0
    tree = ET.parse(local_config['colors_xml'])
    root = tree.getroot()
    for child in root.findall('color'):
        if child.attrib['name'] == theme[key]:
            child.text = obtain_color(color_except_prefix)
            num += 1

    if num == 1:
        tree.write(local_config['colors_xml'], "UTF-8")
        print('完成替换主题颜色')
    else:
        LogUtil.warning(
            '在colors.xml中没有定义subject_color和notification_color,导致无法替换,请检查colors.xml文件'
        )
    pass
예제 #18
0
def sellAction(code=None, name=None, price=None, posi='100'):
    if name is None:
        df = gs.getDataFrame(code)
        name = gs.getStockName(df)
        price = str(round(float(df['b1_p'][0]), 2))
        posi = '100'
    if du.getHMS() < '09:25:00':
        df = gs.getDataFrame(code)
        pre_close = str(round(float(df['pre_close'][0]), 2))
        price = round(float(pre_close) * 0.92, 2)
    config_words = code + "," + name + "," + posi + "," + str(price) + ",0"
    f_config = open('C:/auto/SellAction.txt', 'w')
    f_config.write(config_words)
    f_config.close()
    pm.sendSellDoneEmail(code)
    lu.log("SellAction: 已写入执行句子:" + config_words)
    f = open('persist.txt', 'w')
    f.write("")
    f.close()
예제 #19
0
def create_output_apk_name():
    output_apk_name = ''

    output_apk_name.join(['111'])

    print(output_apk_name)

    output_apk_name.join(['222'])

    print(output_apk_name)

    # print('333')

    print('-'.join(['aa']))

    LogUtil.error('图片资源替换完成')
    LogUtil.warning('图片资源替换完成')

    pass
예제 #20
0
def replace_theme():
    def inner(ltype):
        return ltype

    theme_dict = boss['theme']

    if check_can_skip(theme_dict) is None:
        return

    for k, v in theme_dict.items():
        if not v:
            continue
        # color_except_prefix标识除去'#'前缀的颜色值
        if re.match(COLOR_HEX_REGULAR, v) is None:
            LogUtil.error('十六进制主题颜色值不正确,请检查')
            sys.exit()

        color_except_prefix = v[1:len(v)]
        replace_real_skin(k, color_except_prefix)
    pass
예제 #21
0
def replace_real_color_skin(color_skin_file_path: str):
    try:
        tree = ET.parse(color_skin_file_path)
        root = tree.getroot()
        color_dict = {}
        for color in root.findall('color'):
            color: ET.Element
            color_dict[color.attrib['name']] = color.text

        for key, v in color_dict.items():
            if not v:
                continue
            # color_except_prefix标识除去'#'前缀的颜色值
            if re.match(COLOR_HEX_REGULAR, v) is None:
                LogUtil.error('十六进制主题颜色值不正确,请检查')
                sys.exit()

            color_except_prefix = v[1:len(v)]

            print('开始替换主题颜色')
            success = False
            tree = ET.parse(local_config['colors_xml'])
            root = tree.getroot()
            for child in root.findall('color'):
                if child.attrib['name'] == key:
                    child.text = obtain_color(color_except_prefix)
                    success = True

            if success:
                success = False
                tree.write(local_config['colors_xml'], "UTF-8")
                print('完成替换主题颜色')
            else:
                LogUtil.warning(local_config['colors_xml'] + '没有定义' +
                                color_skin_file_path +
                                '文件中的name字段,请检查colors.xml文件')

    except Exception as e:
        logging.exception(e)
        raise
    pass
예제 #22
0
def replace_umeng_channel(umeng_channel: str):
    # //title[@lang='eng']
    try:
        print('开始友盟渠道号替换流程')
        etree.register_namespace('android', NAMESPACE_MANIFEST)

        success = False
        manifest_xml = local_config['manifest_xml']
        grammar = '//meta-data[@*]'
        tree = etree.parse(manifest_xml)
        doc = tree.xpath(grammar)
        umeng_channel_ele = None
        for ele in doc:
            for n in ele.attrib.items():
                if not n[1].startswith('UMENG_CHANNEL'):
                    continue
                umeng_channel_ele = ele
                break
            if umeng_channel_ele is not None:
                break

        if umeng_channel_ele is not None:
            for m in umeng_channel_ele.attrib.items():
                if m[0].endswith('value'):
                    umeng_channel_ele.set(m[0], umeng_channel)
                    success = True
        if not success:
            raise RuntimeError('友盟渠道号替换流程异常')
        else:
            tree.write(manifest_xml,
                       pretty_print=True,
                       encoding='utf-8',
                       xml_declaration=True)
            print('完成友盟渠道号替换流程')
    except Exception as e:
        logging.exception(e)
        LogUtil.error('友盟渠道号替换流程异常')
        sys.exit()

    pass
예제 #23
0
def parseResponse(html):
    # 解析searchCallbacksong(),括号中的内容
    result = re.findall(".*searchCallbacksong\((.*)\).*", html)
    json_str = result[0]
    LogUtil.d("reponse解析的json字符串:".decode("gbk").encode("utf-8") + json_str)

    jsonObject = json.loads(json_str)  # 转化为python dict
    # print type(jsonObject)

    # print jsonObject["data"]["song"]["list"]
    for index, item in enumerate(jsonObject['data']['song']['list']):
        if ((index + 1) > TOP_DOWNLOAD_NUMBER):
            LogUtil.d("设置最大下载的数量为:".decode("gbk").encode("utf-8") +
                      str(TOP_DOWNLOAD_NUMBER))
            break
        elif (TOP_DOWNLOAD_NUMBER >= 1):
            media_mid = item["file"]["media_mid"]
            mid = item["mid"]
            if TOP_DOWNLOAD_NUMBER == 1:
                save_filename = item["name"] + ".m4a"
            else:
                save_filename = item["name"] + "-" + str(index + 1) + ".m4a"
            LogUtil.d(
                str(index) + " media_mid: " + media_mid + "; mid:" + mid +
                "; name:" + save_filename)
            get_vkey(mid, media_mid, save_filename)
예제 #24
0
def getShelfConfigure(code):
    url = SERVIER_URL + "/scale?shelf_code={0}".format(code)
    LogUtil.d(url)
    print(url)
    """
    id 秤id
    shelf_id 货架id
    x 秤所在列
    y 秤所在行
    max_weight 秤最大称重
    item_id 商品id
    item_weight 单个商品重量
    quantity 商品数量
    status 秤状态。1启用,0不启用
    :return:
    """
    try:
        response = requests.get(url)
        if response.status_code == 200:
            # print(response.content)
            LogUtil.d(response.content)
            data = json.loads(response.content)
            print("响应结果", data)
    except Exception as e:
        print(e)
        LogUtil.e(e)

    return data
예제 #25
0
def search_music(song_name):
    # print "搜索的歌名:" + song_name.encode("utf-8")
    header = {
        "authority":
        "c.y.qq.com",
        "method":
        "GET",
        "path":
        "/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song"
        "&searchid=62072551069125820&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=20&w=%s"
        "&g_tk=5381&jsonpCallback=searchCallbacksong2143&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8"
        "&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0" % song_name,
        "scheme":
        'https',
        'accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'accept-language':
        'zh-CN,zh;q=0.9',
        'cache-control':
        'max-age=0',
        'user-agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }

    # url地址可以浏览器分析获取,主要是&w参数
    url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song' \
          '&searchid=62072551069125820&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=20&w=%s' \
          '&g_tk=5381&jsonpCallback=searchCallbacksong&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8' \
          '&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0' % song_name
    LogUtil.i('Searching:' + url + '\n')
    request = urllib.request.Request(url, headers=header)
    try:
        html = urllib.request.urlopen(request).read()
    except Exception as e:
        print('Download error:', e, '\n')
        html = None
    return html
예제 #26
0
def recompile2(is_recovery: bool, appname, appicon, apkname, splash_pic_name,
               umeng_channel):
    try:
        apkList = os.listdir(apkPath)
        print('开始重新编译回包')
        for apk in apkList:
            if apk.find('.DS_Store') > -1:
                continue
            if not apkname == apk:
                continue
            eachapkPath = os.path.join(apkPath, apk)
            output_apk_name = wrapper.Name_family.Builder().appname(
                appname).splash_picname(splash_pic_name).app_icon(
                    appicon).umeng_channel(umeng_channel).build().append()
            apkOutPath = recompileApkPath + apkname + os.sep + boss2[
                ELEMENT_TAG_APPLICATION_ID] + os.sep + output_apk_name + '.apk'
            sys = platform.system()
            if sys.find('Windows') > -1:
                cmd = "apktool b -f -o {0} {1} <nul".format(
                    apkOutPath, eachapkPath)
            else:
                cmd = "apktool b -f -o {0} {1}".format(apkOutPath, eachapkPath)

            os.system(cmd)
            if is_recovery:
                set_current_package(apkname)
                sourcecache.recovery(apkname)
            print('完成重新编译回包')
    except Exception as e:
        LogUtil.error('重新编译回包失败')
        logging.exception(e)
        cmd = "echo {0}>>{1}".format(apkOutPath, "重新编译回包失败")
        os.system(cmd)
        raise

    pass
예제 #27
0
def get_vkey(mid, media_mid, save_filename):
    header = {
        "authority":
        "c.y.qq.com",
        "method":
        "GET",
        "path":
        "/base/fcgi-bin/fcg_music_express_mobile3.fcg?g_tk=5381&jsonpCallback=MusicJsonCallback"
        "&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq"
        "&needNewCode=0&cid=205361747&callback=MusicJsonCallback2346403861098214&uin=0&songmid=%s"
        "&filename=C400%s.m4a&guid=5789371178" % (mid, media_mid),
        "scheme":
        'https',
        'accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'accept-language':
        'zh-CN,zh;q=0.9',
        'cache-control':
        'max-age=0',
        "referer":
        "https://y.qq.com/portal/player.html",
        'user-agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }

    # url地址可以浏览器分析获取,主要是&w参数
    url = 'https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?g_tk=5381&jsonpCallback=MusicJsonCallback' \
          '&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0' \
          '&cid=205361747&callback=MusicJsonCallback&uin=0&songmid=%s&filename=C400%s.m4a' \
          '&guid=5789371178' % (mid, media_mid)

    LogUtil.i('get vkey :' + url + '\n')
    request = urllib.request.Request(url, headers=header)
    try:
        html = urllib.request.urlopen(request).read()
        result = re.findall(".*MusicJsonCallback\((.*)\).*", str(html))
        json_str = result[0]
        LogUtil.d("get_vkey解析的字符串为:" + json_str)

        jsonObject = json.loads(json_str)  # 转化为python dict
        filename = jsonObject["data"]["items"][0]["filename"]
        songmid = jsonObject["data"]["items"][0]["songmid"]
        vkey = jsonObject["data"]["items"][0]["vkey"]
        LogUtil.d("filename=" + filename + "  ;songmid:" + songmid +
                  "   ;vkey:" + vkey)

        download_m4a(filename, vkey, save_filename)
    except Exception as e:
        print('vkey error:', e, '\n')
        html = None
    return html
예제 #28
0
def requestItemInfo(itemCode):
    url = SERVIER_URL + "/item/{0}".format(itemCode)
    LogUtil.d(url)
    print(url)
    try:
        response = requests.get(url)
        if response.status_code == 200:
            # print(response.content)
            LogUtil.d(response.content)
            data = json.loads(response.content)
            print("响应结果", data)
    except Exception as e:
        print(e)
        LogUtil.e(e)
예제 #29
0
def updateMotion(weightInfo):
    """
    item_id 商品id
    scale_id 秤id
    member_id 会员id
    picture 摄像头拍摄的照片路径
    motion 0拿起商品 1放下商品
    quantity 拿起或放下商品的数量
    :return:
    """
    url = SERVIER_URL + "/motion"
    data = {
        "item_id": weightInfo["item_id"],
        "scale_id": weightInfo["id"],
        "shelf_id": weightInfo["shelf_id"],
        "member_id": 1,
        "age": 22,
        "gender": 0,
        "picture": "abc.jpg",
        "motion": weightInfo["motion"],
        "quantity": weightInfo["quantity"]
    }
    print(url)
    print("请求参数:", data)
    LogUtil.d(url)
    LogUtil.d(data)
    try:
        response = requests.post(url, json=data)
        if response.status_code == 200:
            # print(response.content)
            LogUtil.d(response.content)
            data = json.loads(response.content)
            print("响应结果", data)
    except Exception as e:
        print(e)
        LogUtil.e(e)

    return data
예제 #30
0
def generation(image_path):
    try:
        if not check_file_type(image_path):
            LogUtil.log_e('file format error !')
            return
        last_path = get_last_file_name(image_path)
        # print last_path
        org_image = Image.open(image_path)  # 打开原图
        # print org_image.size, org_image.format, org_image.info  # 基本信息输出
        dst_size = map(add_2, org_image.size)  # 新的图尺寸,上下左右向外扩1个像素
        dst_image = Image.new("RGBA", dst_size, (255, 255, 255, 0))  # 生成一张透明图
        dst_image.paste(org_image, (1, 1, dst_size[0] - 1, dst_size[1] - 1))  # 将原图画在透明图上面(居中)
        draw = ImageDraw.Draw(dst_image, "RGBA")  # 构建一张可以画的图
        draw.point([0, 1, 0, dst_size[1] - 2, 1, 0, dst_size[0] - 2, 0], fill=(0, 0, 0, 255))  # 在上面画1像素点
        dst_image.save(last_path)  # 保存.9图片
        LogUtil.log_d(app, last_path + ' save success !')
    except BaseException, e:
        LogUtil.log_e(e.message)
예제 #31
0
def control_package():
    startTime = datetime.datetime.now()
    sourceApkList = os.listdir(sourceApkPath)
    try:
        element_tree = loadconfig2()
        if element_tree is None:
            raise RuntimeError('config配置文件为空')

        first_floor_child: ET.Element
        for first_floor_child in element_tree.getroot().findall('decompile'):
            boss2.clear()
            target_attrib_value = first_floor_child.attrib['target']
            if not target_attrib_value:
                LogUtil.error('target属性不能为空,用来标识要反编译的apk,请检查config.xml')
                sys.exit()
            configFilePath(target_attrib_value)
            decompiled_folders: List[str] = os.listdir(apkPath)
            is_exist_in_apkOut = decompiled_folders.__contains__(
                target_attrib_value)
            # if not is_exist_in_apkOut:
            is_exist_in_apks = sourceApkList.__contains__(target_attrib_value +
                                                          '.apk')
            if not is_exist_in_apks:
                LogUtil.error('apks文件夹下没有' + target_attrib_value +
                              '这个apk文件,请检查')
                sys.exit()
            if not decompile(target_attrib_value):
                LogUtil.error(target_attrib_value + '反编译失败')
                sys.exit()
            execute(first_floor_child, target_attrib_value)
            # else:
            #     execute(first_floor_child, target_attrib_value)

        endTime = datetime.datetime.now()
        print("all work is done! 总耗时/秒:",
              (endTime - startTime).total_seconds())
    except Exception as e:
        logging.exception(e)
    finally:
        # 删除tmp缓存文件夹
        sourcecache.clear_tmp()
        input('请按下任意键退出控制台窗口...')

    pass
예제 #32
0
파일: Main.py 프로젝트: fcvane/MTransform
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/10/30 16:22
# @Author  : Fcvane
# @Param   :
# @File    : Main.py

import os
import VariableUtil
import LogUtil

name = os.path.basename(__file__)
log = LogUtil.Logger(name)
'''
海南电信
10.45.59.184:1521/resdb
USER_JZJK:USER_JZJK

大榕产品库
10.45.59.246:9999/orcl 
FICUS_R9:FICUS_R9
'''

# 数据库表对象生产器 sqlacodegen
log.info('Start execute sqlacodegen')
os.system(
    "sqlacodegen oracle://USER_JZJK:[email protected]:1521/resdb --outfile  %s/SourceDB_Model.py --tables bfm_event_code,global_bo_temp,global_object "
    % VariableUtil.TMP_PATH)
log.info('Execute sqlacodegen success')
# Model.py文件替换成目标库类
log.info('Start replace sourcedb model with targetdb model')
예제 #33
0
import cv2 as cv
import numpy as np
from sklearn.cluster import MiniBatchKMeans
import math
from scipy.cluster.vq import kmeans, vq
import LogUtil
import zipapp

window_capture_name = 'Video Capture'
window_detection_name = 'Object Detection'

cv.namedWindow(window_capture_name)
cv.namedWindow(window_detection_name)
#IMG_0845_GT
fileName = "C:/Users/Jack/Desktop/python/Project/IMG_0849.MOV"
LogUtil.init(fileName)
cap = cv.VideoCapture(fileName)

trackingTimes = []

previous = [100000, 100000]
angles = []

drumAverage = []
drumMinMaxAverage = []

frameNumber = 0
centerLengths = []

ret, frame = cap.read()
height, width = frame.shape[:2]
def run_command(hutil, args, cwd, operation, extension_short_name, version, exit_after_run = True, interval = 30, std_out_file_name = DefaultStdoutFile, std_err_file_name = DefaultErroutFile):
    std_out_file = os.path.join(cwd, std_out_file_name)
    err_out_file = os.path.join(cwd, std_err_file_name)
    std_out = None
    err_out = None
    try:
        std_out = open(std_out_file, "w")
        err_out = open(err_out_file, "w")
        start_time = time.time()
        child = subprocess.Popen(args,
                                 cwd=cwd,
                                 stdout=std_out,
                                 stderr=err_out)
        time.sleep(1)
        while child.poll() is None:
            msg = LogUtil.get_formatted_log("Command is running...",
                                    LogUtil.tail(std_out_file), LogUtil.tail(err_out_file))
            hutil.log(msg)
            hutil.do_status_report(operation, 'transitioning', '0', msg)
            time.sleep(interval)

        exit_code = child.returncode
        if child.returncode and child.returncode != 0:
            msg = LogUtil.get_formatted_log("Command returned an error.",
                                    LogUtil.tail(std_out_file), LogUtil.tail(err_out_file))
            hutil.error(msg)
            waagent.AddExtensionEvent(name=extension_short_name,
                                      op=operation,
                                      isSuccess=False,
                                      version=version,
                                      message="(01302)"+msg)
        else:
            msg = LogUtil.get_formatted_log("Command is finished.",
                                    LogUtil.tail(std_out_file), LogUtil.tail(err_out_file))
            hutil.log(msg)
            waagent.AddExtensionEvent(name=extension_short_name,
                                      op=operation,
                                      isSuccess=True,
                                      version=version,
                                      message="(01302)"+msg)
            end_time = time.time()
            waagent.AddExtensionEvent(name=extension_short_name,
                                      op=operation,
                                      isSuccess=True,
                                      version=version,
                                      message=("(01304)Command execution time: "
                                      "{0}s").format(str(end_time-start_time)))
                                      
        log_or_exit(hutil, exit_after_run, exit_code, operation, msg)
    except Exception as e:
        error_msg = ("Failed to launch command with error: {0},"
                     "stacktrace: {1}").format(e, traceback.format_exc())
        hutil.error(error_msg)
        waagent.AddExtensionEvent(name=extension_short_name,
                                  op=operation,
                                  isSuccess=False,
                                  version=version,
                                  message="(01101)"+error_msg)
        exit_code = 1                                  
        msg = 'Lanch command failed: {0}'.format(e)
        
        log_or_exit(hutil, exit_after_run, exit_code, operation, msg)
    finally:        
        if std_out:
            std_out.close()
        if err_out:
            err_out.close()
    return exit_code