Best Python code snippet using autotest_python
grpcLibrary.py
Source:grpcLibrary.py
...67 if entry.is_file() & entry.name.endswith(".proto"):68 logging.info(f"Generating GRPC code of proto {entry.name}")69 os.system(70 f"python -m grpc_tools.protoc -I{service_name}/protos \71 --proto_path={_site_packages_path()} \72 --python_out={output_folder} \73 --grpc_python_out={output_folder} \74 {entry.name}"75 )76 _create_keyword_file(entry, output_folder)77 logging.info("Codes generated successfully")78service_pattern = r"^service (.*) {"79endpoint_pattern = r"^rpc\s*([a-zA-Z]+)\s*\(([a-zA-Z]+)\)\s*returns\s*\([stream ]*([a-zA-Z]+)\).*"80def _create_keyword_file(proto_path, output_folder):81 services = _read_proto(proto_path)82 file_name = proto_path.name[0:-6]83 _write_keyword_file(services, output_folder, file_name)84def _read_proto(proto_path):85 """86 Read a proto file and extract services and enpoints87 Parameters88 ----------89 proto_path : Location of proto90 Returns91 -------92 list93 a list of services and theirs endpoints94 """95 services = []96 with open(proto_path) as proto:97 for line in proto:98 fix_line = line.strip()99 if fix_line:100 if _is_service(fix_line):101 service_name = re.search(service_pattern, fix_line).group(102 1103 )104 cur_service = _GrpcServiceDef(service_name)105 services.append(cur_service)106 if _is_endpoint(fix_line):107 result = re.search(endpoint_pattern, fix_line)108 endpoint = _GrpcEndpointDef(109 name=result.group(1),110 request=result.group(2),111 response=result.group(3),112 )113 cur_service.add_endpoint(endpoint)114 return services115def _write_keyword_file(services, output_folder, file_name):116 """117 Based on list of services write a keyword file with all endpoints and services118 Parameters119 ----------120 services : list121 list of services definitions122 output_folder : str123 path of folder where the files will be stored124 file_name : str125 name of file to be used as name of *.py keyword file126 """127 with open("grpcKeywordTemplate") as file:128 endpoint_template_data = file.read()129 with open(f"{output_folder}/{file_name}.py", "w") as keyword_file:130 keyword_file.write(131 "import grpc\n"132 f"import {file_name}_pb2\n"133 f"import {file_name}_pb2_grpc\n"134 "from grpcLibrary import GrpcResponse, parse_data, parse_metadata, create_channel\n"135 )136 for service in services:137 for endpoint in service.endpoints:138 endpoint_data = (139 endpoint_template_data.replace("{file_name}", file_name)140 .replace("{service_name}", service.name)141 .replace("{endpoint}", endpoint.name)142 .replace("{request}", endpoint.request)143 )144 keyword_file.write("\n\n" + endpoint_data)145def _is_service(line):146 """returns if line is a Service line"""147 return re.match(service_pattern, line)148def _is_endpoint(line):149 """returns if line is an Endpoint line"""150 return re.match(endpoint_pattern, line)151def _site_packages_path():152 python_path = sys.exec_prefix153 python_version = sys.version_info154 return f"{python_path}/lib/python{python_version.major}.{python_version.minor}/site-packages"155class _GrpcServiceDef:156 def __init__(self, name):157 self._name = name158 self._endpoints = []159 @property160 def name(self):161 return self._name162 @property163 def endpoints(self):164 return self._endpoints165 def add_endpoint(self, endpoint):...
conanfile.py
Source:conanfile.py
...87 return str(py_venv_interp)88 @_py_venv_interp.setter89 def _py_venv_interp(self, value: str):90 self.__py_venv_interp = value91 def _site_packages_path(self, interp: str) -> str:92 buffer = StringIO()93 outer = '"' if self.settings.os == "Windows" else "'"94 inner = "'" if self.settings.os == "Windows" else '"'95 self.run(f"{interp} -c {outer}import sysconfig; print(sysconfig.get_path({inner}purelib{inner})){outer}", env = "conanrun", output = buffer)96 pythonpath = buffer.getvalue().splitlines()[-1]97 return pythonpath98 def _generate_virtual_python_env(self, *initial_reqs):99 """100 Generates a virtual Python Environment and initializes is101 TODO: Check if we aren't in an actual virtual Python environment yet. Because running a venv in a venv is asking for troubles102 :param initial_reqs: Python modules which should be installed (strings)103 """104 self.output.info("Generating virtual Python environment")105 self.run(f"{self._python_interp} -m venv {self.install_folder}", run_environment = True, env = "conanrun")106 # Make sure there executable is named the same on all three OSes this allows it to be called with `python`107 # simplifying GH Actions steps108 if self.settings.os != "Windows":109 py_venv_interp = Path(self.install_folder, self._python_venv_bin_path, "python")110 if not py_venv_interp.exists():111 py_venv_interp.hardlink_to(Path(self.install_folder, self._python_venv_bin_path, Path(sys.executable).stem + Path(sys.executable).suffix))112 else:113 py_venv_interp = Path(self.install_folder, self._python_venv_bin_path, Path(sys.executable).stem + Path(sys.executable).suffix)114 if not py_venv_interp.exists():115 raise ConanException(f"Virtual environment Python interpreter not found at: {py_venv_interp}")116 if self.settings.os == "Windows":117 py_venv_interp = Path(*[f'"{p}"' if " " in p else p for p in py_venv_interp.parts])118 # Updating the run environment119 self.runenv_info.define_path("VIRTUAL_ENV", self.install_folder)120 self.runenv_info.prepend_path("PATH", os.path.join(self.install_folder, self._python_venv_bin_path))121 self.runenv_info.prepend_path("PYTHONPATH", self._site_packages_path(py_venv_interp))122 self.runenv_info.unset("PYTHONHOME")123 # Installing the initial_reqs124 reqs = " ".join(initial_reqs)125 self.run(f"{py_venv_interp} -m pip install {reqs}", run_environment = True, env = "conanrun")126 self.output.success(f"Created a Virtual Python Environment in {self.install_folder}")127 self._py_venv_interp = str(py_venv_interp)128class Pkg(ConanFile):129 name = "umbase"130 version = "0.1.6"131 default_user = "ultimaker"132 default_channel = "stable"133 exports_sources = "StandardProjectSettings.cmake"134 def package(self):135 self.copy("StandardProjectSettings.cmake", "cmake")...
pyenv_tool.py
Source:pyenv_tool.py
...20__AUTHOR__ = u'é»æ
§å' # ä½è
21__PUBLISH__ = '2022.04.29' # åå¸æ¥æ22class PythonEnvTools(object):23 @classmethod24 def get_site_packages_path(cls) -> str:25 """26 è·åsite_packagesæå¨ç®å½27 @returns {str} - ç®å½28 """29 return site.getsitepackages()[0]30 @classmethod31 def set_local_packages(cls, name: str, path: str):32 """33 å°æå®ç®å½è®¾ç½®ä¸ºæ¬å°é¨ç½²å
34 注: æ éå®è£
æ¬æºå¯ç´æ¥ä½¿ç¨35 @param {str} name - å
å36 @param {str} path - å
æå¨è·¯å¾(å
ç®å½çä¸ä¸çº§ç®å½)37 """38 _site_packages_path = cls.get_site_packages_path()39 _content = '# .pth file for the %s extensions\n%s' % (name, path)40 _filename = '%s.pth' % name41 # åå
¥æ件42 with open(os.path.join(_site_packages_path, _filename), 'wb') as _f:43 _f.write(_content.encode('utf-8'))44 @classmethod45 def remove_local_packages(cls, name: str):46 """47 å é¤æ¬å°é¨ç½²å
é
ç½®48 @param {str} name - å
å49 """50 _site_packages_path = cls.get_site_packages_path()51 _filename = '%s.pth' % name52 os.remove(os.path.join(_site_packages_path, _filename))53 @classmethod54 def install_package(cls, package_name: str, force_reinstall: bool = False, mirror: str = None) -> tuple:55 """56 å®è£
æå®ä¾èµå
57 @param {str} package_name - è¦å®è£
çå
å58 注: å¯ä»¥å
å«çæ¬, ä¾å¦ redis==xxxx59 @param {bool} force_reinstall=False - æ¯å¦å¼ºå¶éæ°å®è£
60 @param {str} mirror=None - 使ç¨éåå°å61 @returns {tuple[int, str]} - å®è£
ç»æ62 第ä¸ä½ä¸ºè¿è¡ç»æ, 0代表ææ¬, å
¶ä»ä»£è¡¨å¤±è´¥63 第äºä½ä¸ºå½ä»¤å®è£
ç»æè¾åºå
容64 """65 _result = subprocess.getstatusoutput(66 'pip install %s%s%s' % (67 '--force-reinstall ' if force_reinstall else '',68 package_name,69 ' -i %s' % mirror if mirror is not None else ''70 )71 )72 if _result[0] == 0:73 # å®è£
æå74 print('å®è£
ä¾èµå
%s æå' % package_name)75 else:76 # å®è£
失败77 print('å®è£
ä¾èµå
%s 失败\n%s\n' % (package_name, _result))78 return _result79 @classmethod80 def install_packages(cls, package_list: list, force_reinstall: bool = False, mirror: str = None) -> bool:81 """82 å®è£
æå®ä¾èµå
æ¸
å83 @param {list} package_list - è¦å®è£
çå
åæ¸
å84 注: å¯ä»¥å
å«çæ¬, ä¾å¦ ['redis==xxxx', ...]85 @param {bool} force_reinstall=False - æ¯å¦å¼ºå¶éæ°å®è£
86 @param {str} mirror=None - 使ç¨éåå°å87 @returns {bool} - å®è£
ç»æ88 """89 _fail_list = []90 for _key in package_list.keys():91 _result = cls.install_package(92 _key, force_reinstall=force_reinstall, mirror=mirror93 )94 if _result[0] != 0:95 # å®è£
失败96 _fail_list.append(_key)97 # æå°æåç»æ98 if len(_fail_list) > 0:99 print('以ä¸ä¾èµå
å®è£
失败: %s' % ', '.join(_fail_list))100 return False101 else:102 return True103if __name__ == '__main__':104 # å½ç¨åºèªå·±ç¬ç«è¿è¡æ¶æ§è¡çæä½105 if len(sys.argv) <= 1:106 # æå°çæ¬ä¿¡æ¯107 print(('模åå: %s - %s\n'108 'ä½è
: %s\n'109 'åå¸æ¥æ: %s\n'110 'çæ¬: %s\n'111 '使ç¨æ¹æ³:\n%s'112 % (113 __MOUDLE__, __DESCRIPT__, __AUTHOR__, __PUBLISH__, __VERSION__,114 '\n'.join([115 'éè¿æ§è¡pythonæ件çæ¹å¼å¯å¨:',116 ' è·åsite_packagesæå¨ç®å½: python pyenv_tool.py -g',117 ' å°æå®ç®å½è®¾ç½®ä¸ºæ¬å°é¨ç½²å
: python pyenv_tool.py -s HiveNetCore "/users/l/path"',118 ' å é¤æ¬å°é¨ç½²å
é
ç½®: python pyenv_tool.py -r HiveNetCore',119 'ç´æ¥éè¿ç¼è¯åå½ä»¤æ¹å¼å¯å¨:',120 ' è·åsite_packagesæå¨ç®å½: pyenvtool -g',121 ' ...'122 ])123 )))124 else:125 # æå½ä»¤åæ°æ§è¡126 if '-g' in sys.argv:127 # è·åè·¯å¾128 print('site_packages: %s' % PythonEnvTools.get_site_packages_path())129 elif '-r' in sys.argv:130 _name = sys.argv[2]131 PythonEnvTools.remove_local_packages(_name)132 print('remove success!')133 elif '-s' in sys.argv:134 _name = sys.argv[2]135 _path = sys.argv[3].strip('"')136 if not os.path.exists(_path):137 print('path not exists: [%s]' % _path)138 else:139 PythonEnvTools.set_local_packages(_name, _path)140 print('set success!')141 else:142 print('run paras error!')
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!!