Best Python code snippet using autotest_python
util.py
Source:util.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4@author = 'wyx'5@time = 2017/2/4 09:056@annotation = ''7"""8import calendar9import datetime10import decimal11import json12import re13import subprocess14import sys15import time16from dateutil import tz17from base import config18def error_msg():19    import traceback20    return traceback.format_exc()21def get_round(spread):22    if spread >= 1:23        return spread24    return decimal.Decimal(str(spread)).as_tuple().exponent * -125def get_point(num):26    return decimal.Decimal(str(num)).as_tuple().exponent * -127def point2decfloat(point):28    """29    ä¿ç使°è½¬åædecimal30    2 -> 0.0131    """32    if point >= 1:33        return decimal.Decimal('0.' + '0' * (point - 1) + '1')34    return safe_decimal(point)35def safe_decimal(data):36    if not isinstance(data, str):37        data = str(data)38    return decimal.Decimal(data)39def nowdt():40    return datetime.datetime.now(config.tz_info).replace(microsecond=0)41def dt2ts(dt, tzinfo=config.tz_info):42    if dt.tzinfo is None:43        if tzinfo is None:44            return int(time.mktime(dt.timetuple()))45        dt = dt.replace(tzinfo=tzinfo)46    utc_dt = dt.astimezone(tz.tzutc()).timetuple()47    return calendar.timegm(utc_dt)48def ts2dt(timestamp):49    if not isinstance(timestamp, float):50        timestamp = float(timestamp)51    return datetime.datetime.fromtimestamp(timestamp, config.tz_info)52def str2dt(dtstr, format='%Y-%m-%d %H:%M:%S', tzinfo=config.tz_info):53    dt = datetime.datetime.strptime(dtstr, format)54    return dt.replace(tzinfo=tzinfo)55def deal_min_trade(min_trade):56    if min_trade >= 1 and isinstance(min_trade, int):57        return min_trade + 158    else:59        point = get_point(min_trade)60        return min_trade + float(point2decfloat(point))61def shell_cmd(cmd):62    return subprocess.check_output(cmd, stderr=sys.stderr, shell=True)63def android_activity(json_output=False):64    def device_name():65        cmd = 'adb devices -l'66        r = shell_cmd(cmd).decode()67        res = re.search(r'model:(.*?) device', r, re.S)68        if res:69            return {'deviceName': res.groups()[0]}70        return None71    def get_package():72        """get the current activity and packagename"""73        cmd = 'adb shell dumpsys window windows | grep -E "mCurrentFocus"'74        r = shell_cmd(cmd).decode()75        res = re.search(r'=Window{(.*?)}', r)76        if res:77            try:78                res = res.groups()[0].split(' ')[-1].split('/')79                package_name = res[0]80                activity_name = res[1]81                if package_name and activity_name:82                    return {83                        'appPackage': package_name,84                        'appActivity': activity_name,85                    }86                return None87            except Exception:88                return None89    device = device_name()90    if device is None:91        raise RuntimeError('No device or adb')92    tar_package = get_package()93    # if tar_package is None:94    #     raise RuntimeError('No current activity')95    if tar_package:96        device.update(tar_package)97        device['platformName'] = 'Android'98        device['noReset'] = True99        device['automationName'] = 'uiautomator2'100        device['newCommandTimeout'] = 0101        return device if not json_output else json.dumps(device)102def project_dir():103    import os104    file_path = os.path.abspath(__file__)...preprocess.py
Source:preprocess.py  
1def getting_data(url,path):2  data = urllib.request.urlopen(url)3  tar_package = tarfile.open(fileobj=data, mode='r:gz')4  tar_package.extractall(path)5  tar_package.close()6  return print("Data extracted and saved.")78getting_data("http://ai.stanford.edu/~jkrause/car196/car_ims.tgz","/content/carimages")910def getting_metadata(url,filename):11  '''12  Downloading a metadata file from a specific url and save it to the disc.13  '''14  labels = urllib2.urlopen(url)15  file = open(filename, 'wb')16  file.write(labels.read())17  file.close()18  return print("Metadata downloaded and saved.")19
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
