How do you create a partition in python?
❮ String Methods Show ExampleSearch for the word "bananas", and return a tuple with three elements: 1 - everything before the "match" txt = "I could eat bananas all day" x = txt.partition("bananas") print(x) Try it Yourself » Definition and UsageThe The first element contains the part before the specified string. The second element contains the specified string. The third element contains the part after the string. Note: This method searches for the first occurrence of the specified string. SyntaxParameter Values
More ExamplesExampleIf the specified value is not found, the partition() method returns a tuple containing: 1 - the whole string, 2 - an empty string, 3 - an empty string: txt = "I could eat bananas all day" x = txt.partition("apples") print(x) Try it Yourself » ❮ String Methods 42 Python code examples are found related to " create partition". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. Example 1 def create_partition(self, table_path, partition_spec, partition, ignore_if_exists): """ Create a partition. :param table_path: Path :class:`ObjectPath` of the table. :param partition_spec: Partition spec :class:`CatalogPartitionSpec` of the partition. :param partition: The partition :class:`CatalogPartition` to add. :param ignore_if_exists: Flag to specify behavior if a table with the given name already exists: if set to false, it throws a TableAlreadyExistException, if set to true, nothing happens. :raise: CatalogException in case of any runtime exception. TableNotExistException thrown if the target table does not exist. TableNotPartitionedException thrown if the target table is not partitioned. PartitionSpecInvalidException thrown if the given partition spec is invalid. PartitionAlreadyExistsException thrown if the target partition already exists. """ self._j_catalog.createPartition(table_path._j_object_path, partition_spec._j_catalog_partition_spec, partition._j_catalog_partition, ignore_if_exists) Example 2 def create_partition(self, partition_date: date): """Create a daily partition for the metric.api_history table.""" start_ts = datetime.combine(partition_date, time.min) end_ts = datetime.combine(partition_date, time.max) db_request = self._build_db_request( sql_file_name='create_api_metric_partition.sql', args=dict(start_ts=str(start_ts), end_ts=str(end_ts)), sql_vars=dict(partition=partition_date.strftime('%Y%m%d')) ) self.cursor.execute(db_request) db_request = self._build_db_request( sql_file_name='create_api_metric_partition_index.sql', sql_vars=dict(partition=partition_date.strftime('%Y%m%d')) ) self.cursor.execute(db_request) Example 3 def create_partition(device, logger): timeout = 10 cmd = "echo -e 'o\\nn\\np\\n1\\n\\n\\nw\\n' | fdisk %s" % device result = process.run(cmd, shell=True, ignore_status=True) if result.exit_status: logger.error("cmd failed: %s" % cmd) logger.error("out: %s" % result.stderr) while timeout > 0: if os.path.exists(device): cmd = "dd if=/dev/zero of=%s bs=512 count=10000; sync" % device result = process.run(cmd, shell=True, ignore_status=True) if result.exit_status: logger.error("cmd failed: %s" % cmd) logger.error("out: %s" % result.stderr) return True cmd = "partprobe %s" % device result = process.run(cmd, shell=True, ignore_status=True) if result.exit_status: logger.error("cmd failed: %s" % cmd) logger.error("out: %s" % result.stderr) time.sleep(1) timeout = timeout - 1 return False Example 4 def create_partition(self, params): """Create a partition.""" node = self._get_node_or_permission_error( params, permission=self._meta.edit_permission ) disk_obj = BlockDevice.objects.get(id=params["block_id"], node=node) form = AddPartitionForm(disk_obj, {"size": params["partition_size"]}) if not form.is_valid(): raise HandlerError(form.errors) else: partition = form.save() self._update_obj_tags(partition, params) if "fstype" in params: self.update_partition_filesystem( node, partition.id, params.get("fstype"), params.get("mount_point"), params.get("mount_options"), ) Example 5 def get_or_create_cache_set_for_partition(self, partition): """Get or create the cache set for the `partition`.""" # Circular imports. from maasserver.models.filesystem import Filesystem existing_cache_set = self.get_cache_set_for_partition(partition) if existing_cache_set is not None: return existing_cache_set else: cache_set = self.create() Filesystem.objects.create( partition=partition, fstype=FILESYSTEM_TYPE.BCACHE_CACHE, cache_set=cache_set, ) return cache_set Example 6 def create_partition_key(dataset_uuid, table, index_values, filename="data"): """ Create partition key for a kartothek partition Parameters ---------- dataset_uuid: str table: str index_values: list of tuples str:str filename: str Example: create_partition_key('my-uuid', 'testtable', [('index1', 'value1'), ('index2', 'value2')]) returns 'my-uuid/testtable/index1=value1/index2=value2/data' """ key_components = [dataset_uuid, table] index_path = quote_indices(index_values) key_components.extend(index_path) key_components.append(filename) key = "/".join(key_components) return key Example 7 def create_partition_linux(session, did, size, start, part_type=PARTITION_TYPE_PRIMARY, timeout=360): """ Create single partition on disk in linux guest. :param session: session object to guest. :param did: disk kname. e.g. sdb :param size: partition size. e.g. 200M :param start: partition beginning at start. e.g. 0M :param part_type: partition type, primary extended logical :param timeout: Timeout for cmd execution in seconds. """ size = utils_numeric.normalize_data_size(size, order_magnitude="M") + "M" start = utils_numeric.normalize_data_size(start, order_magnitude="M") + "M" end = str(float(start[:-1]) + float(size[:-1])) + size[-1] partprobe_cmd = "partprobe /dev/%s" % did mkpart_cmd = 'parted -s "%s" mkpart %s %s %s' mkpart_cmd %= ("/dev/%s" % did, part_type, start, end) session.cmd(mkpart_cmd) session.cmd(partprobe_cmd, timeout=timeout) Example 8 def create_partition_windows(session, did, size, start, part_type=PARTITION_TYPE_PRIMARY, timeout=360): """ Create single partition on disk in windows guest. :param session: session object to guest. :param did: disk index :param size: partition size. e.g. size 200M :param start: partition beginning at start. e.g. 0M :param part_type: partition type, primary extended logical :param timeout: Timeout for cmd execution in seconds. """ size = utils_numeric.normalize_data_size(size, order_magnitude="M") start = utils_numeric.normalize_data_size(start, order_magnitude="M") size = int(float(size) - float(start)) mkpart_cmd = " echo create partition %s size=%s" mkpart_cmd = _wrap_windows_cmd(mkpart_cmd) session.cmd(mkpart_cmd % (did, part_type, size), timeout=timeout) Example 9 def create_partition(self, partition): """Create a partition on this block device. :param partition: Instance of models.partition.Partition to be carved out of this block device """ if self.type == 'physical': if self.partitions is not None: partition = self.partitions.add(partition) self.partitions.refresh() return self.partitions.select(partition.resource_id) else: msg = "Error: could not access device %s partition list" % self.name self.logger.error(msg) raise errors.DriverError(msg) else: msg = "Error: cannot partition non-physical device %s." % ( self.name) self.logger.error(msg) raise errors.DriverError(msg) Example 10 def create_partition(self, partition_name: str, value: Union[str, int, bool, None], tablespace: str = None) -> None: """Create partitions. Parameters: partition_name(str): Partition name. value(Union[str, int, bool, None]): Partition key value. tablespace(str): Partition tablespace name. """ sql_sequence = [ SQL_CREATE_LIST_PARTITION % {"parent": double_quote(self.model._meta.db_table), "child": double_quote(partition_name), "value": _db_value(value)} ] if tablespace: sql_sequence[0] += SQL_APPEND_TABLESPACE % {"tablespace": tablespace} sql_sequence.extend(generate_set_indexes_tablespace_sql(partition_name, tablespace)) execute_sql(sql_sequence) Example 11 def create_partition(self, collection_name, partition_tag, timeout=30): """ create a partition for a collection. :param collection_name: Name of the collection. :type collection_name: str :param partition_name: Name of the partition. :type partition_name: str :param partition_tag: Name of the partition tag. :type partition_tag: str :param timeout: time waiting for response. :type timeout: int :return: Status: Whether the operation is successful. """ check_pass_param(collection_name=collection_name, partition_tag=partition_tag) with self._connection() as handler: return handler.create_partition(collection_name, partition_tag, timeout) Example 12 def create_partition(session, did, size, start, ostype, part_type=PARTITION_TYPE_PRIMARY, timeout=360): """ Create single partition on disk in windows or linux guest. :param session: session object to guest. :param did: disk kname or disk index :param size: partition size. e.g. size 2G :param start: partition beginning at start. e.g. 0G :param ostype: linux or windows. :param part_type: partition type, primary extended logical :param timeout: Timeout for cmd execution in seconds. """ if ostype == "windows": create_partition_windows(session, did, size, start, part_type, timeout) else: create_partition_linux(session, did, size, start, part_type, timeout) Example 13 def create_root_partition(self, mbsize): """ Create root partition Populates kiwi_RootPart(id) and kiwi_BootPart(id) if no extra boot partition is requested :param int mbsize: partition size """ self.partitioner.create('p.lxroot', mbsize, 't.linux') self._add_to_map('root') self._add_to_public_id_map('kiwi_RootPart') if 'kiwi_ROPart' in self.public_partition_id_map: self._add_to_public_id_map('kiwi_RWPart') if 'kiwi_BootPart' not in self.public_partition_id_map: self._add_to_public_id_map('kiwi_BootPart') Example 14 def create_partition(self, partition): """Create a partition on this block device. :param partition: Instance of models.partition.Partition to be carved out of this block device """ if self.type == 'physical': if self.partitions is not None: partition = self.partitions.add(partition) self.partitions.refresh() return self.partitions.select(partition.resource_id) else: msg = "Error: could not access device %s partition list" % self.name self.logger.error(msg) raise errors.DriverError(msg) else: msg = "Error: cannot partition non-physical device %s." % ( self.name) self.logger.error(msg) raise errors.DriverError(msg) Example 15 def create_root_raid_partition(self, mbsize): """ Create root partition for use with MD Raid Populates kiwi_RootPart(id) and kiwi_RaidPart(id) as well as the default raid device node at boot time which is configured to be kiwi_RaidDev(/dev/mdX) :param int mbsize: partition size """ self.partitioner.create('p.lxraid', mbsize, 't.raid') self._add_to_map('root') self._add_to_public_id_map('kiwi_RootPart') self._add_to_public_id_map('kiwi_RaidPart') Example 16 def create_boot_partition(self, mbsize): """ Create boot partition Populates kiwi_BootPart(id) :param int mbsize: partition size """ self.partitioner.create('p.lxboot', mbsize, 't.linux') self._add_to_map('boot') self._add_to_public_id_map('kiwi_BootPart') Example 17 def create_partition_if_boot_disk(self): """Creates a partition that uses the whole disk if this block device is the boot disk.""" if self.is_boot_disk(): return self.create_partition() else: return None Example 18 def doCreatePartition(argv, arglist): g_param = parse_global_arg(argv) if "help" in argv: show_help("CreatePartition", g_param[OptionsDefine.Version]) return param = { "InstanceId": argv.get("--InstanceId"), "TopicName": argv.get("--TopicName"), "PartitionNum": Utils.try_to_json(argv, "--PartitionNum"), } cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey]) http_profile = HttpProfile( reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]), reqMethod="POST", endpoint=g_param[OptionsDefine.Endpoint] ) profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256") mod = CLIENT_MAP[g_param[OptionsDefine.Version]] client = mod.CkafkaClient(cred, g_param[OptionsDefine.Region], profile) client._sdkVersion += ("_CLI_" + __version__) models = MODELS_MAP[g_param[OptionsDefine.Version]] model = models.CreatePartitionRequest() model.from_json_string(json.dumps(param)) rsp = client.CreatePartition(model) result = rsp.to_json_string() jsonobj = None try: jsonobj = json.loads(result) except TypeError as e: jsonobj = json.loads(result.decode('utf-8')) # python3.3 FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter]) Example 19 def create_efi_partition(self, mbsize): """ Create EFI partition Populates kiwi_EfiPart(id) :param int mbsize: partition size """ self.partitioner.create('p.UEFI', mbsize, 't.efi') self._add_to_map('efi') self._add_to_public_id_map('kiwi_EfiPart') Example 20 def create_spare_partition(self, mbsize): """ Create spare partition for custom use Populates kiwi_SparePart(id) :param int mbsize: partition size """ self.partitioner.create('p.spare', mbsize, 't.linux') self._add_to_map('spare') self._add_to_public_id_map('kiwi_SparePart') Example 21 def create_py_partition(self, serialized_partition): assert isinstance(serialized_partition, bytes) call = self._python_gateway_actor.createPyPartition \ .remote(serialized_partition) return deserialize(ray.get(call)) Example 22 def CreateProductPartition(client, adgroup_id): """Creates a ProductPartition tree for the given AdGroup ID. Args: client: an AdWordsClient instance. adgroup_id: a str AdGroup ID. Returns: The ProductPartition tree as a zeep.objects.ProductPartition. """ ad_group_criterion_service = client.GetService('AdGroupCriterionService', 'v201809') helper = ProductPartitionHelper(adgroup_id) root = helper.CreateSubdivision() new_product_canonical_condition = { 'xsi_type': 'ProductCanonicalCondition', 'condition': 'NEW' } used_product_canonical_condition = { 'xsi_type': 'ProductCanonicalCondition', 'condition': 'USED' } other_product_canonical_condition = { 'xsi_type': 'ProductCanonicalCondition', } helper.CreateUnit(root, new_product_canonical_condition) helper.CreateUnit(root, used_product_canonical_condition) helper.CreateUnit(root, other_product_canonical_condition) result = ad_group_criterion_service.mutate(helper.operations) return result['value'] Example 23 def create_prep_partition(self, mbsize): """ Create prep partition Populates kiwi_PrepPart(id) :param int mbsize: partition size """ self.partitioner.create('p.prep', mbsize, 't.prep') self._add_to_map('prep') self._add_to_public_id_map('kiwi_PrepPart') Example 24 def CreatePartition(self, request): """本接口用于增加主题中的分区 :param request: Request instance for CreatePartition. :type request: :class:`tencentcloud.ckafka.v20190819.models.CreatePartitionRequest` :rtype: :class:`tencentcloud.ckafka.v20190819.models.CreatePartitionResponse` """ try: params = request._serialize() body = self.call("CreatePartition", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreatePartitionResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) Example 25 def create_root_lvm_partition(self, mbsize): """ Create root partition for use with LVM Populates kiwi_RootPart(id) and kiwi_RootPartVol(LVRoot) :param int mbsize: partition size """ self.partitioner.create('p.lxlvm', mbsize, 't.lvm') self._add_to_map('root') self._add_to_public_id_map('kiwi_RootPart') self._add_to_public_id_map('kiwi_RootPartVol', 'LVRoot') Example 26 def create_efi_csm_partition(self, mbsize): """ Create EFI bios grub partition Populates kiwi_BiosGrub(id) :param int mbsize: partition size """ self.partitioner.create('p.legacy', mbsize, 't.csm') self._add_to_map('efi_csm') self._add_to_public_id_map('kiwi_BiosGrub') Example 27 def create_swap_partition(self, swap_path=None): """ Make a swap partition and active it. A cleanup_swap() should be call after use to clean up the environment changed. :param swap_path: Swap image path. """ if self.is_dead(): logging.error("Can't create swap on a dead VM.") return False if not swap_path: swap_path = os.path.join(data_dir.get_tmp_dir(), "swap_image") swap_size = self.get_used_mem() process.run("qemu-img create %s %s" % (swap_path, swap_size * 1024)) self.created_swap_path = swap_path device = self.attach_disk(swap_path, extra="--persistent") session = self.wait_for_login() try: dev_path = "/dev/" + device session.cmd_status("mkswap %s" % dev_path) session.cmd_status("swapon %s" % dev_path) self.set_kernel_param("resume", dev_path) return True finally: session.close() logging.error("Failed to create a swap partition.") return False Example 28 def create_root_readonly_partition(self, mbsize): """ Create root readonly partition for use with overlayfs Populates kiwi_ReadOnlyPart(id), the partition is meant to contain a squashfs readonly filesystem. The partition size should be the size of the squashfs filesystem in order to avoid wasting disk space :param int mbsize: partition size """ self.partitioner.create('p.lxreadonly', mbsize, 't.linux') self._add_to_map('readonly') self._add_to_public_id_map('kiwi_ROPart') Example 29 def create_partition_table(session, did, labeltype, ostype): """ Create partition table on disk in linux or windows guest. :param session: session object to guest. :param did: disk kname or disk index :param labeltype: label type for the disk. :param ostype: linux or windows. """ if ostype == "windows": create_partition_table_windows(session, did, labeltype) else: create_partition_table_linux(session, did, labeltype) Example 30 def create_partition_table_linux(session, did, labeltype): """ Create partition table on disk in linux guest. :param session: session object to guest. :param did: disk kname. e.g. sdb :param labeltype: label type for the disk. """ mklabel_cmd = 'parted -s "/dev/%s" mklabel %s' % (did, labeltype) session.cmd(mklabel_cmd) Example 31 def CreateDefaultPartition(client, ad_group_id): """Creates a default partition. Args: client: an AdWordsClient instance. ad_group_id: an integer ID for an ad group. """ ad_group_criterion_service = client.GetService('AdGroupCriterionService', version='v201809') operations = [{ 'operator': 'ADD', 'operand': { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, # Make sure that caseValue and parentCriterionId are left unspecified. # This makes this partition as generic as possible to use as a # fallback when others don't match. 'criterion': { 'xsi_type': 'ProductPartition', 'partitionType': 'UNIT' }, 'biddingStrategyConfiguration': { 'bids': [{ 'xsi_type': 'CpcBid', 'bid': { 'microAmount': 500000 } }] } } }] ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] print('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' % (ad_group_criterion['criterion']['id'], ad_group_criterion['adGroupId'])) Example 32 def create_channel_partition(self, request, context): log.info('grpc-request', request=request) try: assert isinstance(request, ChannelpartitionConfig), \ 'Instance is not of Channel Partition' assert self.validate_interface(request, context) log.debug('creating-channel-partition', name=request.name) self.root.add('/channel_partitions', request) return Empty() except AssertionError, e: context.set_details(e.message) context.set_code(StatusCode.INVALID_ARGUMENT) return Empty() Example 33 def CreatePartition(self, request, context): """* @brief This method is used to create partition @param PartitionParam, partition parameters. @return Status """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') Example 34 def create_partition(self, lsblk_entry): mountable = False mount_point = lsblk_entry.mount_point if not lsblk_entry.is_extended_partition(): if not mount_point or mount_point == self.platform_config.get_external_disk_dir(): mountable = True if lsblk_entry.is_boot_disk(): mountable = False active = False if mount_point == self.platform_config.get_external_disk_dir() \ and self.path_checker.external_disk_link_exists(): active = True return Partition(lsblk_entry.size, lsblk_entry.name, mount_point, active, lsblk_entry.get_fs_type(), mountable) Example 35 def create_partition_from_slice(self, partition_list, start, end): """Call the Glue API with the specified slice of the partition list""" # Create Glue PartitionInput objects from a slice of the values passed in partition_slice = partition_list[start:end] partition_inputs = [self._build_partition_input(vals) for vals in partition_slice] query = { "DatabaseName": self.database_name, "TableName": self.table_name, "PartitionInputList": partition_inputs } LOGGER.info("Batch adding %d partitions", len(partition_slice)) self.glue_client.batch_create_partition(**query) Example 36 def create_swap_partition(self, mbsize): """ Create swap partition Populates kiwi_SwapPart(id) :param int mbsize: partition size """ self.partitioner.create('p.swap', mbsize, 't.swap') self._add_to_map('swap') self._add_to_public_id_map('kiwi_SwapPart') Example 37 def create_partition_table_windows(session, did, labeltype): """ Create partition table on disk in windows guest. mbr is default value, do nothing. :param session: session object to guest. :param did: disk index which show in 'diskpart list disk'. :param labeltype: label type for the disk. """ if labeltype == PARTITION_TABLE_TYPE_GPT: mklabel_cmd = ' echo convert gpt' mklabel_cmd = _wrap_windows_cmd(mklabel_cmd) session.cmd(mklabel_cmd % did) Example 38 def create_partition_query(project_id, dataset_id, table_id): return "SELECT partition_id, FORMAT_UTC_USEC(creation_time*1000) AS " \ "creation_time, FORMAT_UTC_USEC(last_modified_time*1000)" \ " AS last_modified FROM [{0}:{1}.{2}$__PARTITIONS_SUMMARY__]"\ .format(project_id, dataset_id, table_id) Example 39 def create_partition_tasks(self, project_id, dataset_id, table_id, partitions): table_id_list = ["{}${}".format(table_id, partition['partitionId']) for partition in partitions] return self.create_table_tasks(project_id, dataset_id, table_id_list) Example 40 def create_slurm_partition( table_client, queue_client, config, cluster_id, partition_name, batch_service_url, pool_id, compute_node_type, max_compute_nodes, hostlist): partpool_hash = util.hash_string('{}-{}'.format( partition_name, batch_service_url, pool_id)) # insert partition entity entity = { 'PartitionKey': 'PARTITIONS${}'.format(cluster_id), 'RowKey': '{}${}'.format(partition_name, partpool_hash), 'BatchServiceUrl': batch_service_url, 'BatchPoolId': pool_id, 'ComputeNodeType': compute_node_type, 'HostList': hostlist, 'BatchShipyardSlurmVersion': 1, } logger.debug( 'inserting slurm partition {}:{} entity to table for ' 'cluster {}'.format(partition_name, pool_id, cluster_id)) try: table_client.insert_entity(_STORAGE_CONTAINERS['table_slurm'], entity) except azure.common.AzureConflictHttpError: logger.error('partition {}:{} cluster id {} already exists'.format( partition_name, pool_id, cluster_id)) if util.confirm_action( config, 'overwrite existing partition {}:{} for ' 'cluster {}; this can result in undefined behavior'.format( partition_name, pool_id, cluster_id)): table_client.insert_or_replace_entity( _STORAGE_CONTAINERS['table_slurm'], entity) else: raise # create queue qname = '{}-{}'.format(cluster_id, partpool_hash) logger.debug('creating queue: {}'.format(qname)) queue_client.create_queue(qname) Example 41 def create_Partition(self,ip,uuid,session_id): """ Args: ip:ip address of HMC uuid:ManagedSystemUUID session_id:to access the session Returns: Returns the created LogicalPartition object """ log_object.log_debug("creation of logical partition started") obj = eval(self.type)() ns = self.headers_obj.ns obj.schemaVersion = SCHEMA_VER pyxb.RequireValidWhenGenerating(True) obj.PartitionMemoryConfiguration = pyxb.BIND() obj.PartitionMemoryConfiguration.schemaVersion = SCHEMA_VER obj.PartitionMemoryConfiguration.DesiredMemory = DES_MEMORY obj.PartitionMemoryConfiguration.MaximumMemory = MAX_MEMORY obj.PartitionMemoryConfiguration.MinimumMemory = MIN_MEMORY obj.PartitionProcessorConfiguration = pyxb.BIND() obj.PartitionProcessorConfiguration.schemaVersion = SCHEMA_VER obj.PartitionProcessorConfiguration.HasDedicatedProcessors = DEDICATED_PROCESSORS obj.PartitionProcessorConfiguration.SharedProcessorConfiguration = pyxb.BIND() obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.schemaVersion = SCHEMA_VER obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.DesiredProcessingUnits = DES_PROC_UNITS obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.DesiredVirtualProcessors = DES_VIRTUAL_PROCESSORS obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MaximumProcessingUnits = MAX_PROC_UNITS obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MaximumVirtualProcessors = MAX_VIRTUAL_PROCESSORS obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MinimumProcessingUnits = MIN_PROC_UNITS obj.PartitionProcessorConfiguration.SharedProcessorConfiguration.MinimumVirtualProcessors = MIN_VIRTUAL_PROCESSORS obj.PartitionProcessorConfiguration.SharingMode = SHARING_MODE if self.type == "VirtualIOServer": obj.PartitionType = "Virtual IO Server" partition_name = PARTITION_NAME%("VIOS")+""+time.strftime("%d%m%y-%X") else: obj.PartitionType = "AIX/Linux" partition_name = PARTITION_NAME%("LPAR")+""+time.strftime("%d%m%y-%X") obj.PartitionName = partition_name xmlobject = obj.toDOM() xmlobject.documentElement.setAttribute("xmlns",ns["xmlns"]) xmlpayload = xmlobject.toxml("utf-8") request_obj = HTTPClient.HTTPClient("uom",ip,self.root,self.content_type,session_id) request_obj.HTTPPut(xmlpayload,append=str(uuid)+"/"+self.type) log_object.log_debug("response of lpar creation -- %s"%(request_obj.response)) if request_obj.response_b: root = etree.fromstring(request_obj.response.content) entry = root.findall(".//%s:%s"%(self.type,self.type), namespaces={self.type: ns["xmlns"]}) xmlstring = etree.tostring(entry[0]) xml_object = CreateFromDocument(xmlstring) log_object.log_debug("partition created successfully") return xml_object Example 42 def create_partition_volume(params): """create a volume in the disk type of pool""" global logger logger = params['logger'] poolname = params['poolname'] volname = params['volname'] volformat = params['volformat'] capacity = params['capacity'] xmlstr = params['xml'] logger.info("the poolname is %s, volname is %s, \ volfomat is %s, capacity is %s" % (poolname, volname, volformat, capacity)) conn = sharedmod.libvirtobj['conn'] storage_pool_list = conn.listStoragePools() if poolname not in storage_pool_list: logger.error("pool %s doesn't exist or not running") return 1 poolobj = conn.storagePoolLookupByName(poolname) xmlstr = xmlstr.replace('SUFFIX', capacity[-1]) xmlstr = xmlstr.replace('CAP', capacity[:-1]) logger.info("before create the new volume, \ current volume list is %s" % poolobj.listVolumes()) logger.info("and using virsh command to \ ouput the volume information in the pool %s" % poolname) virsh_vol_list(poolname) logger.debug("volume xml:\n%s" % xmlstr) try: logger.info("create %s volume" % volname) poolobj.createXML(xmlstr, 0) except libvirtError as e: logger.error("API error message: %s, error code is %s" % (e.get_error_message(), e.get_error_code())) return 1 logger.info("volume create successfully, and output the volume information") virsh_vol_list(poolname) logger.info("Now, check the validation of the created volume") check_res = partition_volume_check(poolobj, volname) if not check_res: logger.info("checking succeed") return 0 else: logger.error("checking failed") return 1 How do I partition in Python?Python String partition() Method
The partition() method searches for a specified string, and splits the string into a tuple containing three elements. The first element contains the part before the specified string. The second element contains the specified string. The third element contains the part after the string.
How do I create a list partition in Python?Following are the different ways to partition a list into equal-length chunks in Python:. Using Slicing. A simple solution is to write a generator that yields the successive chunks of specified size from the list. ... . Using List Comprehension. Alternatively, you can use list comprehension. ... . Using itertools module. ... . Using toolz.. How do I partition an array in Python?partition() in Python. numpy. partition() function is used to create a partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array.
What is the partition method?Partitioning is the process of dividing an input data set into multiple segments, or partitions. Each processing node in your system then performs an operation on an individual partition of the data set rather than on the entire data set.
|