How to use out_to_console method in grail

Best Python code snippet using grail_python

utils.py

Source:utils.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: utf-8 -*-3"""4 Common utilities in python. Can be useful in different cases.5 Created: Gusev Dmitrii, 04.04.20176 Modified: Gusev Dmitrii, 04.03.20197"""8import os9import errno10import sys11import csv12import yaml13import xlrd14import codecs15# import logging16import logging.config17from os import walk18from subprocess import Popen19# configure logger on module level. it isn't a good practice, but it's convenient.20# don't forget to set disable_existing_loggers=False, otherwise logger won't get its config!21log = logging.getLogger(__name__)22# to avoid errors like 'no handlers' for libraries it's necessary/convenient to add NullHandler.23log.addHandler(logging.NullHandler())24# some useful common constants25DEFAULT_ENCODING = "utf-8"26def count_lines(filename):27 """28 Count lines in any given file.29 :return: count of lines30 """31 counter = 032 # open file, received as first cmd line argument, mode - read+Unicode33 with open(filename, mode='rU') as infile:34 # skip initial space - don't work without it35 reader = csv.reader(infile, delimiter=b',', skipinitialspace=True, quoting=csv.QUOTE_MINIMAL, quotechar=b'"',36 lineterminator="\n")37 # counting rows in a cycle38 for _ in reader:39 # print row # <- just a debug output40 counter += 141 # debug - print count to console42 print("Lines count: {}".format(counter))43 return counter44def _list_files(path, files_buffer, out_to_console=False):45 """46 Internal function for listing (recursively) all files in specified directory.47 Don't use it directly, use list_files()48 :param path: path to iterate through49 :param files_buffer: buffer list for collection files50 :param out_to_console: out to console processing file51 """52 # print "STDOUT encoding ->", sys.stdout.encoding # <- just a debug output53 # todo: line for python 2 -> for (dirpath, dirnames, filenames) in walk(unicode(path)):54 for (dirpath, dirnames, filenames) in walk(path):55 for filename in filenames:56 abs_path = dirpath + '/' + filename57 if out_to_console: # debug output58 if sys.stdout.encoding is not None: # sometimes encoding may be null!59 print(abs_path.encode(sys.stdout.encoding, errors='replace'))60 else:61 print(abs_path)62 files_buffer.append(abs_path)63def list_files(path, out_to_console=False):64 """65 List all files in a specified path and return list of found files.66 :param path: path to directory67 :param out_to_console: do or don't output to system console68 :return: list of files69 """70 log.debug("list_files() is working. Path [{}].".format(path))71 if not path or not path.strip(): # fail-fast #172 raise IOError("Can't list files in empty path!")73 if not os.path.exists(path) or not os.path.isdir(path): # fail-fast #274 raise IOError("Path [{}] doesn't exist or not a directory!".format(path))75 files = []76 _list_files(path, files, out_to_console)77 return files78def parse_yaml(file_path):79 """80 Parses single YAML file and return its contents as object (dictionary).81 :param file_path: path to YAML file to load settings from82 :return python object with YAML file contents83 """84 log.debug("parse_yaml() is working. Parsing YAML file [{}].".format(file_path))85 if not file_path or not file_path.strip():86 raise IOError("Empty path to YAML file!")87 with open(file_path, 'r') as cfg_file:88 cfg_file_content = cfg_file.read()89 if "\t" in cfg_file_content: # no tabs allowed in file content90 raise IOError("Config file [{}] contains 'tab' character!".format(file_path))91 return yaml.load(cfg_file_content)92def save_file_with_path(file_path, content): # todo: move it to utilities module93 log.debug('save_file_with_path(): saving content to [{}].'.format(file_path))94 if not os.path.exists(os.path.dirname(file_path)):95 try:96 os.makedirs(os.path.dirname(file_path))97 except OSError as exc: # guard against race condition98 if exc.errno != errno.EEXIST:99 raise100 # write content to a file101 with open(file_path, "w") as f:102 f.write(content)103# todo: functions (decorators) below are copied from inet :) - take a look104def benchmark(func):105 """106 Декоратор, выводящий время, которое заняло107 выполнение декорируемой функции.108 """109 import time110 def wrapper(*args, **kwargs):111 t = time.clock()112 res = func(*args, **kwargs)113 print(func.__name__, time.clock() - t)114 return res115 return wrapper116def logger(func):117 """118 Декоратор, логирующий работу кода.119 (хорошо, он просто выводит вызовы, но тут могло быть и логирование!)120 """121 def wrapper(*args, **kwargs):122 res = func(*args, **kwargs)123 print(func.__name__, args, kwargs)124 return res125 return wrapper126def call_counter(func):127 """128 Декоратор, считающий и выводящий количество вызовов129 декорируемой функции.130 """131 def wrapper(*args, **kwargs):132 wrapper.count += 1133 res = func(*args, **kwargs)134 print("{0} была вызвана: {1}x".format(func.__name__, wrapper.count))135 return res136 wrapper.count = 0137 return wrapper138def filter_str(string): # todo: fix filtering for non-cyrillic symbols too (add them)139 """140 Filter out all symbols from string except letters, numbers, spaces, commas.141 By default, decode input string in unicode (utf-8).142 :param string:143 :return:144 """145 if not string or not string.strip(): # if empty, return 'as is'146 return string147 # filter out all, except symbols, spaces, or comma148 return ''.join(char for char in string if char.isalnum() or char.isspace() or149 char in 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ.,/-№')150def get_str_val(value, value_type, encoding): # todo: make filtering optional151 """Convert excel cell value into string with filtering out all unnecessary symbols.152 :param value:153 :param value_type:154 :param encoding:155 :return:156 """157 if xlrd.XL_CELL_EMPTY == value_type or xlrd.XL_CELL_BLANK == value_type:158 return ''159 elif xlrd.XL_CELL_NUMBER == value_type:160 return filter_str(str(int(value)).encode(encoding))161 elif xlrd.XL_CELL_TEXT == value_type:162 return filter_str(value.encode(encoding))163 else:164 return filter_str(str(value))165def get_int_val(value, value_type, encoding):166 """Convert excel cell value into integer.167 :param value:168 :param value_type:169 :param encoding:170 :return:171 """172 if xlrd.XL_CELL_EMPTY == value_type or xlrd.XL_CELL_BLANK == value_type:173 return 0174 elif xlrd.XL_CELL_NUMBER == value_type:175 return int(value)176 else:177 raise ValueError("Can't convert value [{}] to integer!".format(value.encode(encoding)))178def write_report_to_file(txt_report, out_file):179 """Write txt report to specified file. If file isn't specified - error is raised. If file doesn't exist -180 it will be created. If it exists - it will be overriden.181 :return:182 """183 log.debug("write_report_to_file() is working. Output file [{}].".format(out_file))184 if not out_file or not out_file.strip(): # fail fast check185 raise PyUtilitiesError("Output file wasn't specified!")186 # writing data to specified file187 with codecs.open(out_file, 'w', DEFAULT_ENCODING) as out:188 out.write(txt_report)189class PyUtilitiesError(Exception):190 """Something went wrong in utilities module..."""191if __name__ == '__main__':...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from __future__ import unicode_literals3import frappe4__version__ = '1.6.00'5def console(*data):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run grail automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful