How to use _site_packages_path method in autotest

Best Python code snippet using autotest_python

grpcLibrary.py

Source:grpcLibrary.py Github

copy

Full Screen

...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):...

Full Screen

Full Screen

conanfile.py

Source:conanfile.py Github

copy

Full Screen

...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")...

Full Screen

Full Screen

pyenv_tool.py

Source:pyenv_tool.py Github

copy

Full Screen

...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!')

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 autotest 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