index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
64,845
canopen.profiles.p402
homing
Execute the configured Homing method on the node. :param int timeout: Timeout value (default: 30, zero to disable). :param bool restore_op_mode: Switch back to the previous operation mode after homing (default: no). :return: If the homing was complete with success. :rtype: bool
def homing(self, timeout=None, restore_op_mode=False): """Execute the configured Homing method on the node. :param int timeout: Timeout value (default: 30, zero to disable). :param bool restore_op_mode: Switch back to the previous operation mode after homing (default: no). :return: If the homing was complete with success. :rtype: bool """ if timeout is None: timeout = self.TIMEOUT_HOMING_DEFAULT if restore_op_mode: previous_op_mode = self.op_mode self.op_mode = 'HOMING' # The homing process will initialize at operation enabled self.state = 'OPERATION ENABLED' homingstatus = 'UNKNOWN' self.controlword = State402.CW_OPERATION_ENABLED | Homing.CW_START # does not block # Wait for one extra cycle, to make sure the controlword was received self.check_statusword() t = time.monotonic() + timeout try: while homingstatus not in ('TARGET REACHED', 'ATTAINED'): homingstatus = self._homing_status() if homingstatus in ('INTERRUPTED', 'ERROR VELOCITY IS NOT ZERO', 'ERROR VELOCITY IS ZERO'): raise RuntimeError('Unable to home. Reason: {0}'.format(homingstatus)) if timeout and time.monotonic() > t: raise RuntimeError('Unable to home, timeout reached') logger.info('Homing mode carried out successfully.') return True except RuntimeError as e: logger.info(str(e)) finally: if restore_op_mode: self.op_mode = previous_op_mode return False
(self, timeout=None, restore_op_mode=False)
64,846
canopen.profiles.p402
is_faulted
null
def is_faulted(self): bitmask, bits = State402.SW_MASK['FAULT'] return self.statusword & bitmask == bits
(self)
64,847
canopen.profiles.p402
is_homed
Switch to homing mode and determine its status. :param bool restore_op_mode: Switch back to the previous operation mode when done. :return: If the status indicates successful homing. :rtype: bool
def is_homed(self, restore_op_mode=False): """Switch to homing mode and determine its status. :param bool restore_op_mode: Switch back to the previous operation mode when done. :return: If the status indicates successful homing. :rtype: bool """ previous_op_mode = self.op_mode if previous_op_mode != 'HOMING': logger.info('Switch to HOMING from %s', previous_op_mode) self.op_mode = 'HOMING' # blocks until confirmed homingstatus = self._homing_status() if restore_op_mode: self.op_mode = previous_op_mode return homingstatus in ('TARGET REACHED', 'ATTAINED')
(self, restore_op_mode=False)
64,848
canopen.profiles.p402
is_op_mode_supported
Check if the operation mode is supported by the node. The object listing the supported modes is retrieved once using SDO, then cached for later checks. :param str mode: Same format as the :attr:`op_mode` property. :return: If the operation mode is supported. :rtype: bool
def is_op_mode_supported(self, mode): """Check if the operation mode is supported by the node. The object listing the supported modes is retrieved once using SDO, then cached for later checks. :param str mode: Same format as the :attr:`op_mode` property. :return: If the operation mode is supported. :rtype: bool """ if not hasattr(self, '_op_mode_support'): # Cache value only on first lookup, this object should never change. self._op_mode_support = self.sdo[0x6502].raw logger.info('Caching node {n} supported operation modes 0x{m:04X}'.format( n=self.id, m=self._op_mode_support)) bits = OperationMode.SUPPORTED[mode] return self._op_mode_support & bits == bits
(self, mode)
64,849
canopen.node.remote
load_configuration
Load the configuration of the node from the object dictionary.
def load_configuration(self): ''' Load the configuration of the node from the object dictionary.''' for obj in self.object_dictionary.values(): if isinstance(obj, ODRecord) or isinstance(obj, ODArray): for subobj in obj.values(): if isinstance(subobj, ODVariable) and subobj.writable and (subobj.value is not None): self.__load_configuration_helper(subobj.index, subobj.subindex, subobj.name, subobj.value) elif isinstance(obj, ODVariable) and obj.writable and (obj.value is not None): self.__load_configuration_helper(obj.index, None, obj.name, obj.value) self.pdo.read() # reads the new configuration from the driver
(self)
64,850
canopen.profiles.p402
on_TPDOs_update_callback
Cache updated values from a TPDO received from this node. :param mapobject: The received PDO message. :type mapobject: canopen.pdo.Map
def on_TPDOs_update_callback(self, mapobject): """Cache updated values from a TPDO received from this node. :param mapobject: The received PDO message. :type mapobject: canopen.pdo.Map """ for obj in mapobject: self.tpdo_values[obj.index] = obj.raw
(self, mapobject)
64,851
canopen.node.remote
remove_network
null
def remove_network(self): for sdo in self.sdo_channels: self.network.unsubscribe(sdo.tx_cobid, sdo.on_response) self.network.unsubscribe(0x700 + self.id, self.nmt.on_heartbeat) self.network.unsubscribe(0x80 + self.id, self.emcy.on_emcy) self.network.unsubscribe(0, self.nmt.on_command) self.network = None self.sdo.network = None self.pdo.network = None self.tpdo.network = None self.rpdo.network = None self.nmt.network = None
(self)
64,852
canopen.profiles.p402
reset_from_fault
Reset node from fault and set it to Operation Enable state.
def reset_from_fault(self): """Reset node from fault and set it to Operation Enable state.""" if self.state == 'FAULT': # Resets the Fault Reset bit (rising edge 0 -> 1) self.controlword = State402.CW_DISABLE_VOLTAGE # FIXME! The rising edge happens with the transitions toward OPERATION # ENABLED below, but until then the loop will always reach the timeout! timeout = time.monotonic() + self.TIMEOUT_RESET_FAULT while self.is_faulted(): if time.monotonic() > timeout: break self.check_statusword() self.state = 'OPERATION ENABLED'
(self)
64,853
canopen.node.remote
restore
Restore default parameters. :param int subindex: 1 = All parameters 2 = Communication related parameters 3 = Application related parameters 4 - 127 = Manufacturer specific
def restore(self, subindex=1): """Restore default parameters. :param int subindex: 1 = All parameters\n 2 = Communication related parameters\n 3 = Application related parameters\n 4 - 127 = Manufacturer specific """ self.sdo.download(0x1011, subindex, b"load")
(self, subindex=1)
64,854
canopen.profiles.p402
setup_402_state_machine
Configure the state machine by searching for a TPDO that has the StatusWord mapped. :param bool read_pdos: Upload current PDO configuration from node. :raises ValueError: If the the node can't find a Statusword configured in any of the TPDOs.
def setup_402_state_machine(self, read_pdos=True): """Configure the state machine by searching for a TPDO that has the StatusWord mapped. :param bool read_pdos: Upload current PDO configuration from node. :raises ValueError: If the the node can't find a Statusword configured in any of the TPDOs. """ self.setup_pdos(read_pdos) self._check_controlword_configured() self._check_statusword_configured() self._check_op_mode_configured()
(self, read_pdos=True)
64,855
canopen.profiles.p402
setup_pdos
Find the relevant PDO configuration to handle the state machine. :param bool upload: Retrieve up-to-date configuration via SDO. If False, the node's mappings must already be configured in the object, matching the drive's settings. :raises AssertionError: When the node's NMT state disallows SDOs for reading the PDO configuration.
def setup_pdos(self, upload=True): """Find the relevant PDO configuration to handle the state machine. :param bool upload: Retrieve up-to-date configuration via SDO. If False, the node's mappings must already be configured in the object, matching the drive's settings. :raises AssertionError: When the node's NMT state disallows SDOs for reading the PDO configuration. """ if upload: assert self.nmt.state in 'PRE-OPERATIONAL', 'OPERATIONAL' self.pdo.read() # TPDO and RPDO configurations else: self.pdo.subscribe() # Get notified on reception, usually a side-effect of read() self._init_tpdo_values() self._init_rpdo_pointers()
(self, upload=True)
64,856
canopen.node.remote
store
Store parameters in non-volatile memory. :param int subindex: 1 = All parameters 2 = Communication related parameters 3 = Application related parameters 4 - 127 = Manufacturer specific
def store(self, subindex=1): """Store parameters in non-volatile memory. :param int subindex: 1 = All parameters\n 2 = Communication related parameters\n 3 = Application related parameters\n 4 - 127 = Manufacturer specific """ self.sdo.download(0x1010, subindex, b"save")
(self, subindex=1)
64,857
canopen.node.local
LocalNode
null
class LocalNode(BaseNode): def __init__( self, node_id: int, object_dictionary: Union[ObjectDictionary, str], ): super(LocalNode, self).__init__(node_id, object_dictionary) self.data_store: Dict[int, Dict[int, bytes]] = {} self._read_callbacks = [] self._write_callbacks = [] self.sdo = SdoServer(0x600 + self.id, 0x580 + self.id, self) self.tpdo = TPDO(self) self.rpdo = RPDO(self) self.pdo = PDO(self, self.rpdo, self.tpdo) self.nmt = NmtSlave(self.id, self) # Let self.nmt handle writes for 0x1017 self.add_write_callback(self.nmt.on_write) self.emcy = EmcyProducer(0x80 + self.id) def associate_network(self, network): self.network = network self.sdo.network = network self.tpdo.network = network self.rpdo.network = network self.nmt.network = network self.emcy.network = network network.subscribe(self.sdo.rx_cobid, self.sdo.on_request) network.subscribe(0, self.nmt.on_command) def remove_network(self): self.network.unsubscribe(self.sdo.rx_cobid, self.sdo.on_request) self.network.unsubscribe(0, self.nmt.on_command) self.network = None self.sdo.network = None self.tpdo.network = None self.rpdo.network = None self.nmt.network = None self.emcy.network = None def add_read_callback(self, callback): self._read_callbacks.append(callback) def add_write_callback(self, callback): self._write_callbacks.append(callback) def get_data( self, index: int, subindex: int, check_readable: bool = False ) -> bytes: obj = self._find_object(index, subindex) if check_readable and not obj.readable: raise SdoAbortedError(0x06010001) # Try callback for callback in self._read_callbacks: result = callback(index=index, subindex=subindex, od=obj) if result is not None: return obj.encode_raw(result) # Try stored data try: return self.data_store[index][subindex] except KeyError: # Try ParameterValue in EDS if obj.value is not None: return obj.encode_raw(obj.value) # Try default value if obj.default is not None: return obj.encode_raw(obj.default) # Resource not available logger.info("Resource unavailable for 0x%X:%d", index, subindex) raise SdoAbortedError(0x060A0023) def set_data( self, index: int, subindex: int, data: bytes, check_writable: bool = False, ) -> None: obj = self._find_object(index, subindex) if check_writable and not obj.writable: raise SdoAbortedError(0x06010002) # Check length matches type (length of od variable is in bits) if obj.data_type in objectdictionary.NUMBER_TYPES and ( not 8 * len(data) == len(obj) ): raise SdoAbortedError(0x06070010) # Try callbacks for callback in self._write_callbacks: callback(index=index, subindex=subindex, od=obj, data=data) # Store data self.data_store.setdefault(index, {}) self.data_store[index][subindex] = bytes(data) def _find_object(self, index, subindex): if index not in self.object_dictionary: # Index does not exist raise SdoAbortedError(0x06020000) obj = self.object_dictionary[index] if not isinstance(obj, objectdictionary.ODVariable): # Group or array if subindex not in obj: # Subindex does not exist raise SdoAbortedError(0x06090011) obj = obj[subindex] return obj
(node_id: int, object_dictionary: Union[canopen.objectdictionary.ObjectDictionary, str])
64,858
canopen.node.local
__init__
null
def __init__( self, node_id: int, object_dictionary: Union[ObjectDictionary, str], ): super(LocalNode, self).__init__(node_id, object_dictionary) self.data_store: Dict[int, Dict[int, bytes]] = {} self._read_callbacks = [] self._write_callbacks = [] self.sdo = SdoServer(0x600 + self.id, 0x580 + self.id, self) self.tpdo = TPDO(self) self.rpdo = RPDO(self) self.pdo = PDO(self, self.rpdo, self.tpdo) self.nmt = NmtSlave(self.id, self) # Let self.nmt handle writes for 0x1017 self.add_write_callback(self.nmt.on_write) self.emcy = EmcyProducer(0x80 + self.id)
(self, node_id: int, object_dictionary: Union[canopen.objectdictionary.ObjectDictionary, str])
64,859
canopen.node.local
_find_object
null
def _find_object(self, index, subindex): if index not in self.object_dictionary: # Index does not exist raise SdoAbortedError(0x06020000) obj = self.object_dictionary[index] if not isinstance(obj, objectdictionary.ODVariable): # Group or array if subindex not in obj: # Subindex does not exist raise SdoAbortedError(0x06090011) obj = obj[subindex] return obj
(self, index, subindex)
64,860
canopen.node.local
add_read_callback
null
def add_read_callback(self, callback): self._read_callbacks.append(callback)
(self, callback)
64,861
canopen.node.local
add_write_callback
null
def add_write_callback(self, callback): self._write_callbacks.append(callback)
(self, callback)
64,862
canopen.node.local
associate_network
null
def associate_network(self, network): self.network = network self.sdo.network = network self.tpdo.network = network self.rpdo.network = network self.nmt.network = network self.emcy.network = network network.subscribe(self.sdo.rx_cobid, self.sdo.on_request) network.subscribe(0, self.nmt.on_command)
(self, network)
64,863
canopen.node.local
get_data
null
def get_data( self, index: int, subindex: int, check_readable: bool = False ) -> bytes: obj = self._find_object(index, subindex) if check_readable and not obj.readable: raise SdoAbortedError(0x06010001) # Try callback for callback in self._read_callbacks: result = callback(index=index, subindex=subindex, od=obj) if result is not None: return obj.encode_raw(result) # Try stored data try: return self.data_store[index][subindex] except KeyError: # Try ParameterValue in EDS if obj.value is not None: return obj.encode_raw(obj.value) # Try default value if obj.default is not None: return obj.encode_raw(obj.default) # Resource not available logger.info("Resource unavailable for 0x%X:%d", index, subindex) raise SdoAbortedError(0x060A0023)
(self, index: int, subindex: int, check_readable: bool = False) -> bytes
64,864
canopen.node.local
remove_network
null
def remove_network(self): self.network.unsubscribe(self.sdo.rx_cobid, self.sdo.on_request) self.network.unsubscribe(0, self.nmt.on_command) self.network = None self.sdo.network = None self.tpdo.network = None self.rpdo.network = None self.nmt.network = None self.emcy.network = None
(self)
64,865
canopen.node.local
set_data
null
def set_data( self, index: int, subindex: int, data: bytes, check_writable: bool = False, ) -> None: obj = self._find_object(index, subindex) if check_writable and not obj.writable: raise SdoAbortedError(0x06010002) # Check length matches type (length of od variable is in bits) if obj.data_type in objectdictionary.NUMBER_TYPES and ( not 8 * len(data) == len(obj) ): raise SdoAbortedError(0x06070010) # Try callbacks for callback in self._write_callbacks: callback(index=index, subindex=subindex, od=obj, data=data) # Store data self.data_store.setdefault(index, {}) self.data_store[index][subindex] = bytes(data)
(self, index: int, subindex: int, data: bytes, check_writable: bool = False) -> NoneType
64,866
canopen.network
Network
Representation of one CAN bus containing one or more nodes.
class Network(MutableMapping): """Representation of one CAN bus containing one or more nodes.""" def __init__(self, bus=None): """ :param can.BusABC bus: A python-can bus instance to re-use. """ #: A python-can :class:`can.BusABC` instance which is set after #: :meth:`canopen.Network.connect` is called self.bus = bus #: A :class:`~canopen.network.NodeScanner` for detecting nodes self.scanner = NodeScanner(self) #: List of :class:`can.Listener` objects. #: Includes at least MessageListener. self.listeners = [MessageListener(self)] self.notifier = None self.nodes: Dict[int, Union[RemoteNode, LocalNode]] = {} self.subscribers: Dict[int, List[Callback]] = {} self.send_lock = threading.Lock() self.sync = SyncProducer(self) self.time = TimeProducer(self) self.nmt = NmtMaster(0) self.nmt.network = self self.lss = LssMaster() self.lss.network = self self.subscribe(self.lss.LSS_RX_COBID, self.lss.on_message_received) def subscribe(self, can_id: int, callback: Callback) -> None: """Listen for messages with a specific CAN ID. :param can_id: The CAN ID to listen for. :param callback: Function to call when message is received. """ self.subscribers.setdefault(can_id, list()) if callback not in self.subscribers[can_id]: self.subscribers[can_id].append(callback) def unsubscribe(self, can_id, callback=None) -> None: """Stop listening for message. :param int can_id: The CAN ID from which to unsubscribe. :param callback: If given, remove only this callback. Otherwise all callbacks for the CAN ID. """ if callback is None: del self.subscribers[can_id] else: self.subscribers[can_id].remove(callback) def connect(self, *args, **kwargs) -> "Network": """Connect to CAN bus using python-can. Arguments are passed directly to :class:`can.BusABC`. Typically these may include: :param channel: Backend specific channel for the CAN interface. :param str bustype: Name of the interface. See `python-can manual <https://python-can.readthedocs.io/en/stable/configuration.html#interface-names>`__ for full list of supported interfaces. :param int bitrate: Bitrate in bit/s. :raises can.CanError: When connection fails. """ # If bitrate has not been specified, try to find one node where bitrate # has been specified if "bitrate" not in kwargs: for node in self.nodes.values(): if node.object_dictionary.bitrate: kwargs["bitrate"] = node.object_dictionary.bitrate break self.bus = can.interface.Bus(*args, **kwargs) logger.info("Connected to '%s'", self.bus.channel_info) self.notifier = can.Notifier(self.bus, self.listeners, 1) return self def disconnect(self) -> None: """Disconnect from the CAN bus. Must be overridden in a subclass if a custom interface is used. """ for node in self.nodes.values(): if hasattr(node, "pdo"): node.pdo.stop() if self.notifier is not None: self.notifier.stop() if self.bus is not None: self.bus.shutdown() self.bus = None self.check() def __enter__(self): return self def __exit__(self, type, value, traceback): self.disconnect() def add_node( self, node: Union[int, RemoteNode, LocalNode], object_dictionary: Union[str, ObjectDictionary, None] = None, upload_eds: bool = False, ) -> RemoteNode: """Add a remote node to the network. :param node: Can be either an integer representing the node ID, a :class:`canopen.RemoteNode` or :class:`canopen.LocalNode` object. :param object_dictionary: Can be either a string for specifying the path to an Object Dictionary file or a :class:`canopen.ObjectDictionary` object. :param upload_eds: Set ``True`` if EDS file should be uploaded from 0x1021. :return: The Node object that was added. """ if isinstance(node, int): if upload_eds: logger.info("Trying to read EDS from node %d", node) object_dictionary = import_from_node(node, self) node = RemoteNode(node, object_dictionary) self[node.id] = node return node def create_node( self, node: int, object_dictionary: Union[str, ObjectDictionary, None] = None, ) -> LocalNode: """Create a local node in the network. :param node: An integer representing the node ID. :param object_dictionary: Can be either a string for specifying the path to an Object Dictionary file or a :class:`canopen.ObjectDictionary` object. :return: The Node object that was added. """ if isinstance(node, int): node = LocalNode(node, object_dictionary) self[node.id] = node return node def send_message(self, can_id: int, data: bytes, remote: bool = False) -> None: """Send a raw CAN message to the network. This method may be overridden in a subclass if you need to integrate this library with a custom backend. It is safe to call this from multiple threads. :param int can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param bool remote: Set to True to send remote frame :raises can.CanError: When the message fails to be transmitted """ if not self.bus: raise RuntimeError("Not connected to CAN bus") msg = can.Message(is_extended_id=can_id > 0x7FF, arbitration_id=can_id, data=data, is_remote_frame=remote) with self.send_lock: self.bus.send(msg) self.check() def send_periodic( self, can_id: int, data: bytes, period: float, remote: bool = False ) -> "PeriodicMessageTask": """Start sending a message periodically. :param can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param period: Seconds between each message :param remote: indicates if the message frame is a remote request to the slave node :return: An task object with a ``.stop()`` method to stop the transmission """ return PeriodicMessageTask(can_id, data, period, self.bus, remote) def notify(self, can_id: int, data: bytearray, timestamp: float) -> None: """Feed incoming message to this library. If a custom interface is used, this function must be called for each message read from the CAN bus. :param can_id: CAN-ID of the message :param data: Data part of the message (0 - 8 bytes) :param timestamp: Timestamp of the message, preferably as a Unix timestamp """ if can_id in self.subscribers: callbacks = self.subscribers[can_id] for callback in callbacks: callback(can_id, data, timestamp) self.scanner.on_message_received(can_id) def check(self) -> None: """Check that no fatal error has occurred in the receiving thread. If an exception caused the thread to terminate, that exception will be raised. """ if self.notifier is not None: exc = self.notifier.exception if exc is not None: logger.error("An error has caused receiving of messages to stop") raise exc def __getitem__(self, node_id: int) -> Union[RemoteNode, LocalNode]: return self.nodes[node_id] def __setitem__(self, node_id: int, node: Union[RemoteNode, LocalNode]): assert node_id == node.id if node_id in self.nodes: # Remove old callbacks self.nodes[node_id].remove_network() self.nodes[node_id] = node node.associate_network(self) def __delitem__(self, node_id: int): self.nodes[node_id].remove_network() del self.nodes[node_id] def __iter__(self) -> Iterable[int]: return iter(self.nodes) def __len__(self) -> int: return len(self.nodes)
(bus=None)
64,868
canopen.network
__delitem__
null
def __delitem__(self, node_id: int): self.nodes[node_id].remove_network() del self.nodes[node_id]
(self, node_id: int)
64,871
canopen.network
__exit__
null
def __exit__(self, type, value, traceback): self.disconnect()
(self, type, value, traceback)
64,872
canopen.network
__getitem__
null
def __getitem__(self, node_id: int) -> Union[RemoteNode, LocalNode]: return self.nodes[node_id]
(self, node_id: int) -> Union[canopen.node.remote.RemoteNode, canopen.node.local.LocalNode]
64,873
canopen.network
__init__
:param can.BusABC bus: A python-can bus instance to re-use.
def __init__(self, bus=None): """ :param can.BusABC bus: A python-can bus instance to re-use. """ #: A python-can :class:`can.BusABC` instance which is set after #: :meth:`canopen.Network.connect` is called self.bus = bus #: A :class:`~canopen.network.NodeScanner` for detecting nodes self.scanner = NodeScanner(self) #: List of :class:`can.Listener` objects. #: Includes at least MessageListener. self.listeners = [MessageListener(self)] self.notifier = None self.nodes: Dict[int, Union[RemoteNode, LocalNode]] = {} self.subscribers: Dict[int, List[Callback]] = {} self.send_lock = threading.Lock() self.sync = SyncProducer(self) self.time = TimeProducer(self) self.nmt = NmtMaster(0) self.nmt.network = self self.lss = LssMaster() self.lss.network = self self.subscribe(self.lss.LSS_RX_COBID, self.lss.on_message_received)
(self, bus=None)
64,874
canopen.network
__iter__
null
def __iter__(self) -> Iterable[int]: return iter(self.nodes)
(self) -> Iterable[int]
64,875
canopen.network
__len__
null
def __len__(self) -> int: return len(self.nodes)
(self) -> int
64,876
canopen.network
__setitem__
null
def __setitem__(self, node_id: int, node: Union[RemoteNode, LocalNode]): assert node_id == node.id if node_id in self.nodes: # Remove old callbacks self.nodes[node_id].remove_network() self.nodes[node_id] = node node.associate_network(self)
(self, node_id: int, node: Union[canopen.node.remote.RemoteNode, canopen.node.local.LocalNode])
64,877
canopen.network
add_node
Add a remote node to the network. :param node: Can be either an integer representing the node ID, a :class:`canopen.RemoteNode` or :class:`canopen.LocalNode` object. :param object_dictionary: Can be either a string for specifying the path to an Object Dictionary file or a :class:`canopen.ObjectDictionary` object. :param upload_eds: Set ``True`` if EDS file should be uploaded from 0x1021. :return: The Node object that was added.
def add_node( self, node: Union[int, RemoteNode, LocalNode], object_dictionary: Union[str, ObjectDictionary, None] = None, upload_eds: bool = False, ) -> RemoteNode: """Add a remote node to the network. :param node: Can be either an integer representing the node ID, a :class:`canopen.RemoteNode` or :class:`canopen.LocalNode` object. :param object_dictionary: Can be either a string for specifying the path to an Object Dictionary file or a :class:`canopen.ObjectDictionary` object. :param upload_eds: Set ``True`` if EDS file should be uploaded from 0x1021. :return: The Node object that was added. """ if isinstance(node, int): if upload_eds: logger.info("Trying to read EDS from node %d", node) object_dictionary = import_from_node(node, self) node = RemoteNode(node, object_dictionary) self[node.id] = node return node
(self, node: Union[int, canopen.node.remote.RemoteNode, canopen.node.local.LocalNode], object_dictionary: Union[str, canopen.objectdictionary.ObjectDictionary, NoneType] = None, upload_eds: bool = False) -> canopen.node.remote.RemoteNode
64,878
canopen.network
check
Check that no fatal error has occurred in the receiving thread. If an exception caused the thread to terminate, that exception will be raised.
def check(self) -> None: """Check that no fatal error has occurred in the receiving thread. If an exception caused the thread to terminate, that exception will be raised. """ if self.notifier is not None: exc = self.notifier.exception if exc is not None: logger.error("An error has caused receiving of messages to stop") raise exc
(self) -> NoneType
64,880
canopen.network
connect
Connect to CAN bus using python-can. Arguments are passed directly to :class:`can.BusABC`. Typically these may include: :param channel: Backend specific channel for the CAN interface. :param str bustype: Name of the interface. See `python-can manual <https://python-can.readthedocs.io/en/stable/configuration.html#interface-names>`__ for full list of supported interfaces. :param int bitrate: Bitrate in bit/s. :raises can.CanError: When connection fails.
def connect(self, *args, **kwargs) -> "Network": """Connect to CAN bus using python-can. Arguments are passed directly to :class:`can.BusABC`. Typically these may include: :param channel: Backend specific channel for the CAN interface. :param str bustype: Name of the interface. See `python-can manual <https://python-can.readthedocs.io/en/stable/configuration.html#interface-names>`__ for full list of supported interfaces. :param int bitrate: Bitrate in bit/s. :raises can.CanError: When connection fails. """ # If bitrate has not been specified, try to find one node where bitrate # has been specified if "bitrate" not in kwargs: for node in self.nodes.values(): if node.object_dictionary.bitrate: kwargs["bitrate"] = node.object_dictionary.bitrate break self.bus = can.interface.Bus(*args, **kwargs) logger.info("Connected to '%s'", self.bus.channel_info) self.notifier = can.Notifier(self.bus, self.listeners, 1) return self
(self, *args, **kwargs) -> canopen.network.Network
64,881
canopen.network
create_node
Create a local node in the network. :param node: An integer representing the node ID. :param object_dictionary: Can be either a string for specifying the path to an Object Dictionary file or a :class:`canopen.ObjectDictionary` object. :return: The Node object that was added.
def create_node( self, node: int, object_dictionary: Union[str, ObjectDictionary, None] = None, ) -> LocalNode: """Create a local node in the network. :param node: An integer representing the node ID. :param object_dictionary: Can be either a string for specifying the path to an Object Dictionary file or a :class:`canopen.ObjectDictionary` object. :return: The Node object that was added. """ if isinstance(node, int): node = LocalNode(node, object_dictionary) self[node.id] = node return node
(self, node: int, object_dictionary: Union[str, canopen.objectdictionary.ObjectDictionary, NoneType] = None) -> canopen.node.local.LocalNode
64,882
canopen.network
disconnect
Disconnect from the CAN bus. Must be overridden in a subclass if a custom interface is used.
def disconnect(self) -> None: """Disconnect from the CAN bus. Must be overridden in a subclass if a custom interface is used. """ for node in self.nodes.values(): if hasattr(node, "pdo"): node.pdo.stop() if self.notifier is not None: self.notifier.stop() if self.bus is not None: self.bus.shutdown() self.bus = None self.check()
(self) -> NoneType
64,886
canopen.network
notify
Feed incoming message to this library. If a custom interface is used, this function must be called for each message read from the CAN bus. :param can_id: CAN-ID of the message :param data: Data part of the message (0 - 8 bytes) :param timestamp: Timestamp of the message, preferably as a Unix timestamp
def notify(self, can_id: int, data: bytearray, timestamp: float) -> None: """Feed incoming message to this library. If a custom interface is used, this function must be called for each message read from the CAN bus. :param can_id: CAN-ID of the message :param data: Data part of the message (0 - 8 bytes) :param timestamp: Timestamp of the message, preferably as a Unix timestamp """ if can_id in self.subscribers: callbacks = self.subscribers[can_id] for callback in callbacks: callback(can_id, data, timestamp) self.scanner.on_message_received(can_id)
(self, can_id: int, data: bytearray, timestamp: float) -> NoneType
64,889
canopen.network
send_message
Send a raw CAN message to the network. This method may be overridden in a subclass if you need to integrate this library with a custom backend. It is safe to call this from multiple threads. :param int can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param bool remote: Set to True to send remote frame :raises can.CanError: When the message fails to be transmitted
def send_message(self, can_id: int, data: bytes, remote: bool = False) -> None: """Send a raw CAN message to the network. This method may be overridden in a subclass if you need to integrate this library with a custom backend. It is safe to call this from multiple threads. :param int can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param bool remote: Set to True to send remote frame :raises can.CanError: When the message fails to be transmitted """ if not self.bus: raise RuntimeError("Not connected to CAN bus") msg = can.Message(is_extended_id=can_id > 0x7FF, arbitration_id=can_id, data=data, is_remote_frame=remote) with self.send_lock: self.bus.send(msg) self.check()
(self, can_id: int, data: bytes, remote: bool = False) -> NoneType
64,890
canopen.network
send_periodic
Start sending a message periodically. :param can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param period: Seconds between each message :param remote: indicates if the message frame is a remote request to the slave node :return: An task object with a ``.stop()`` method to stop the transmission
def send_periodic( self, can_id: int, data: bytes, period: float, remote: bool = False ) -> "PeriodicMessageTask": """Start sending a message periodically. :param can_id: CAN-ID of the message :param data: Data to be transmitted (anything that can be converted to bytes) :param period: Seconds between each message :param remote: indicates if the message frame is a remote request to the slave node :return: An task object with a ``.stop()`` method to stop the transmission """ return PeriodicMessageTask(can_id, data, period, self.bus, remote)
(self, can_id: int, data: bytes, period: float, remote: bool = False) -> canopen.network.PeriodicMessageTask
64,892
canopen.network
subscribe
Listen for messages with a specific CAN ID. :param can_id: The CAN ID to listen for. :param callback: Function to call when message is received.
def subscribe(self, can_id: int, callback: Callback) -> None: """Listen for messages with a specific CAN ID. :param can_id: The CAN ID to listen for. :param callback: Function to call when message is received. """ self.subscribers.setdefault(can_id, list()) if callback not in self.subscribers[can_id]: self.subscribers[can_id].append(callback)
(self, can_id: int, callback: Callable[[int, bytearray, float], NoneType]) -> NoneType
64,893
canopen.network
unsubscribe
Stop listening for message. :param int can_id: The CAN ID from which to unsubscribe. :param callback: If given, remove only this callback. Otherwise all callbacks for the CAN ID.
def unsubscribe(self, can_id, callback=None) -> None: """Stop listening for message. :param int can_id: The CAN ID from which to unsubscribe. :param callback: If given, remove only this callback. Otherwise all callbacks for the CAN ID. """ if callback is None: del self.subscribers[can_id] else: self.subscribers[can_id].remove(callback)
(self, can_id, callback=None) -> NoneType
64,896
canopen.node.remote
RemoteNode
A CANopen remote node. :param node_id: Node ID (set to None or 0 if specified by object dictionary) :param object_dictionary: Object dictionary as either a path to a file, an ``ObjectDictionary`` or a file like object. :param load_od: Enable the Object Dictionary to be sent through SDO's to the remote node at startup.
class RemoteNode(BaseNode): """A CANopen remote node. :param node_id: Node ID (set to None or 0 if specified by object dictionary) :param object_dictionary: Object dictionary as either a path to a file, an ``ObjectDictionary`` or a file like object. :param load_od: Enable the Object Dictionary to be sent through SDO's to the remote node at startup. """ def __init__( self, node_id: int, object_dictionary: Union[ObjectDictionary, str, TextIO], load_od: bool = False, ): super(RemoteNode, self).__init__(node_id, object_dictionary) #: Enable WORKAROUND for reversed PDO mapping entries self.curtis_hack = False self.sdo_channels = [] self.sdo = self.add_sdo(0x600 + self.id, 0x580 + self.id) self.tpdo = TPDO(self) self.rpdo = RPDO(self) self.pdo = PDO(self, self.rpdo, self.tpdo) self.nmt = NmtMaster(self.id) self.emcy = EmcyConsumer() if load_od: self.load_configuration() def associate_network(self, network): self.network = network self.sdo.network = network self.pdo.network = network self.tpdo.network = network self.rpdo.network = network self.nmt.network = network for sdo in self.sdo_channels: network.subscribe(sdo.tx_cobid, sdo.on_response) network.subscribe(0x700 + self.id, self.nmt.on_heartbeat) network.subscribe(0x80 + self.id, self.emcy.on_emcy) network.subscribe(0, self.nmt.on_command) def remove_network(self): for sdo in self.sdo_channels: self.network.unsubscribe(sdo.tx_cobid, sdo.on_response) self.network.unsubscribe(0x700 + self.id, self.nmt.on_heartbeat) self.network.unsubscribe(0x80 + self.id, self.emcy.on_emcy) self.network.unsubscribe(0, self.nmt.on_command) self.network = None self.sdo.network = None self.pdo.network = None self.tpdo.network = None self.rpdo.network = None self.nmt.network = None def add_sdo(self, rx_cobid, tx_cobid): """Add an additional SDO channel. The SDO client will be added to :attr:`sdo_channels`. :param int rx_cobid: COB-ID that the server receives on :param int tx_cobid: COB-ID that the server responds with :return: The SDO client created :rtype: canopen.sdo.SdoClient """ client = SdoClient(rx_cobid, tx_cobid, self.object_dictionary) self.sdo_channels.append(client) if self.network is not None: self.network.subscribe(client.tx_cobid, client.on_response) return client def store(self, subindex=1): """Store parameters in non-volatile memory. :param int subindex: 1 = All parameters\n 2 = Communication related parameters\n 3 = Application related parameters\n 4 - 127 = Manufacturer specific """ self.sdo.download(0x1010, subindex, b"save") def restore(self, subindex=1): """Restore default parameters. :param int subindex: 1 = All parameters\n 2 = Communication related parameters\n 3 = Application related parameters\n 4 - 127 = Manufacturer specific """ self.sdo.download(0x1011, subindex, b"load") def __load_configuration_helper(self, index, subindex, name, value): """Helper function to send SDOs to the remote node :param index: Object index :param subindex: Object sub-index (if it does not exist e should be None) :param name: Object name :param value: Value to set in the object """ try: if subindex is not None: logger.info(str('SDO [{index:#06x}][{subindex:#06x}]: {name}: {value:#06x}'.format( index=index, subindex=subindex, name=name, value=value))) self.sdo[index][subindex].raw = value else: self.sdo[index].raw = value logger.info(str('SDO [{index:#06x}]: {name}: {value:#06x}'.format( index=index, name=name, value=value))) except SdoCommunicationError as e: logger.warning(str(e)) except SdoAbortedError as e: # WORKAROUND for broken implementations: the SDO is set but the error # "Attempt to write a read-only object" is raised any way. if e.code != 0x06010002: # Abort codes other than "Attempt to write a read-only object" # should still be reported. logger.warning('[ERROR SETTING object {0:#06x}:{1:#06x}] {2}'.format(index, subindex, str(e))) raise def load_configuration(self): ''' Load the configuration of the node from the object dictionary.''' for obj in self.object_dictionary.values(): if isinstance(obj, ODRecord) or isinstance(obj, ODArray): for subobj in obj.values(): if isinstance(subobj, ODVariable) and subobj.writable and (subobj.value is not None): self.__load_configuration_helper(subobj.index, subobj.subindex, subobj.name, subobj.value) elif isinstance(obj, ODVariable) and obj.writable and (obj.value is not None): self.__load_configuration_helper(obj.index, None, obj.name, obj.value) self.pdo.read() # reads the new configuration from the driver
(node_id: int, object_dictionary: Union[canopen.objectdictionary.ObjectDictionary, str, TextIO], load_od: bool = False)
64,898
canopen.node.remote
__init__
null
def __init__( self, node_id: int, object_dictionary: Union[ObjectDictionary, str, TextIO], load_od: bool = False, ): super(RemoteNode, self).__init__(node_id, object_dictionary) #: Enable WORKAROUND for reversed PDO mapping entries self.curtis_hack = False self.sdo_channels = [] self.sdo = self.add_sdo(0x600 + self.id, 0x580 + self.id) self.tpdo = TPDO(self) self.rpdo = RPDO(self) self.pdo = PDO(self, self.rpdo, self.tpdo) self.nmt = NmtMaster(self.id) self.emcy = EmcyConsumer() if load_od: self.load_configuration()
(self, node_id: int, object_dictionary: Union[canopen.objectdictionary.ObjectDictionary, str, TextIO], load_od: bool = False)
64,905
canopen.network
NodeScanner
Observes which nodes are present on the bus. Listens for the following messages: - Heartbeat (0x700) - SDO response (0x580) - TxPDO (0x180, 0x280, 0x380, 0x480) - EMCY (0x80) :param canopen.Network network: The network to use when doing active searching.
class NodeScanner: """Observes which nodes are present on the bus. Listens for the following messages: - Heartbeat (0x700) - SDO response (0x580) - TxPDO (0x180, 0x280, 0x380, 0x480) - EMCY (0x80) :param canopen.Network network: The network to use when doing active searching. """ #: Activate or deactivate scanning active = True SERVICES = (0x700, 0x580, 0x180, 0x280, 0x380, 0x480, 0x80) def __init__(self, network: Optional[Network] = None): self.network = network #: A :class:`list` of nodes discovered self.nodes: List[int] = [] def on_message_received(self, can_id: int): service = can_id & 0x780 node_id = can_id & 0x7F if node_id not in self.nodes and node_id != 0 and service in self.SERVICES: self.nodes.append(node_id) def reset(self): """Clear list of found nodes.""" self.nodes = [] def search(self, limit: int = 127) -> None: """Search for nodes by sending SDO requests to all node IDs.""" if self.network is None: raise RuntimeError("A Network is required to do active scanning") sdo_req = b"\x40\x00\x10\x00\x00\x00\x00\x00" for node_id in range(1, limit + 1): self.network.send_message(0x600 + node_id, sdo_req)
(network: Optional[canopen.network.Network] = None)
64,906
canopen.network
__init__
null
def __init__(self, network: Optional[Network] = None): self.network = network #: A :class:`list` of nodes discovered self.nodes: List[int] = []
(self, network: Optional[canopen.network.Network] = None)
64,907
canopen.network
on_message_received
null
def on_message_received(self, can_id: int): service = can_id & 0x780 node_id = can_id & 0x7F if node_id not in self.nodes and node_id != 0 and service in self.SERVICES: self.nodes.append(node_id)
(self, can_id: int)
64,908
canopen.network
reset
Clear list of found nodes.
def reset(self): """Clear list of found nodes.""" self.nodes = []
(self)
64,909
canopen.network
search
Search for nodes by sending SDO requests to all node IDs.
def search(self, limit: int = 127) -> None: """Search for nodes by sending SDO requests to all node IDs.""" if self.network is None: raise RuntimeError("A Network is required to do active scanning") sdo_req = b"\x40\x00\x10\x00\x00\x00\x00\x00" for node_id in range(1, limit + 1): self.network.send_message(0x600 + node_id, sdo_req)
(self, limit: int = 127) -> NoneType
64,910
canopen.objectdictionary
ObjectDictionary
Representation of the object dictionary as a Python dictionary.
class ObjectDictionary(MutableMapping): """Representation of the object dictionary as a Python dictionary.""" def __init__(self): self.indices = {} self.names = {} self.comments = "" #: Default bitrate if specified by file self.bitrate: Optional[int] = None #: Node ID if specified by file self.node_id: Optional[int] = None #: Some information about the device self.device_information = DeviceInformation() def __getitem__( self, index: Union[int, str] ) -> Union["ODArray", "ODRecord", "ODVariable"]: """Get object from object dictionary by name or index.""" item = self.names.get(index) or self.indices.get(index) if item is None: name = "0x%X" % index if isinstance(index, int) else index raise KeyError("%s was not found in Object Dictionary" % name) return item def __setitem__( self, index: Union[int, str], obj: Union["ODArray", "ODRecord", "ODVariable"] ): assert index == obj.index or index == obj.name self.add_object(obj) def __delitem__(self, index: Union[int, str]): obj = self[index] del self.indices[obj.index] del self.names[obj.name] def __iter__(self) -> Iterable[int]: return iter(sorted(self.indices)) def __len__(self) -> int: return len(self.indices) def __contains__(self, index: Union[int, str]): return index in self.names or index in self.indices def add_object(self, obj: Union["ODArray", "ODRecord", "ODVariable"]) -> None: """Add object to the object dictionary. :param obj: Should be either one of :class:`~canopen.objectdictionary.ODVariable`, :class:`~canopen.objectdictionary.ODRecord`, or :class:`~canopen.objectdictionary.ODArray`. """ obj.parent = self self.indices[obj.index] = obj self.names[obj.name] = obj def get_variable( self, index: Union[int, str], subindex: int = 0 ) -> Optional["ODVariable"]: """Get the variable object at specified index (and subindex if applicable). :return: ODVariable if found, else `None` """ obj = self.get(index) if isinstance(obj, ODVariable): return obj elif isinstance(obj, (ODRecord, ODArray)): return obj.get(subindex)
()
64,911
canopen.objectdictionary
__contains__
null
def __contains__(self, index: Union[int, str]): return index in self.names or index in self.indices
(self, index: Union[int, str])
64,912
canopen.objectdictionary
__delitem__
null
def __delitem__(self, index: Union[int, str]): obj = self[index] del self.indices[obj.index] del self.names[obj.name]
(self, index: Union[int, str])
64,914
canopen.objectdictionary
__getitem__
Get object from object dictionary by name or index.
def __getitem__( self, index: Union[int, str] ) -> Union["ODArray", "ODRecord", "ODVariable"]: """Get object from object dictionary by name or index.""" item = self.names.get(index) or self.indices.get(index) if item is None: name = "0x%X" % index if isinstance(index, int) else index raise KeyError("%s was not found in Object Dictionary" % name) return item
(self, index: Union[int, str]) -> Union[canopen.objectdictionary.ODArray, canopen.objectdictionary.ODRecord, canopen.objectdictionary.ODVariable]
64,915
canopen.objectdictionary
__init__
null
def __init__(self): self.indices = {} self.names = {} self.comments = "" #: Default bitrate if specified by file self.bitrate: Optional[int] = None #: Node ID if specified by file self.node_id: Optional[int] = None #: Some information about the device self.device_information = DeviceInformation()
(self)
64,916
canopen.objectdictionary
__iter__
null
def __iter__(self) -> Iterable[int]: return iter(sorted(self.indices))
(self) -> Iterable[int]
64,917
canopen.objectdictionary
__len__
null
def __len__(self) -> int: return len(self.indices)
(self) -> int
64,918
canopen.objectdictionary
__setitem__
null
def __setitem__( self, index: Union[int, str], obj: Union["ODArray", "ODRecord", "ODVariable"] ): assert index == obj.index or index == obj.name self.add_object(obj)
(self, index: Union[int, str], obj: Union[canopen.objectdictionary.ODArray, canopen.objectdictionary.ODRecord, canopen.objectdictionary.ODVariable])
64,919
canopen.objectdictionary
add_object
Add object to the object dictionary. :param obj: Should be either one of :class:`~canopen.objectdictionary.ODVariable`, :class:`~canopen.objectdictionary.ODRecord`, or :class:`~canopen.objectdictionary.ODArray`.
def add_object(self, obj: Union["ODArray", "ODRecord", "ODVariable"]) -> None: """Add object to the object dictionary. :param obj: Should be either one of :class:`~canopen.objectdictionary.ODVariable`, :class:`~canopen.objectdictionary.ODRecord`, or :class:`~canopen.objectdictionary.ODArray`. """ obj.parent = self self.indices[obj.index] = obj self.names[obj.name] = obj
(self, obj: Union[canopen.objectdictionary.ODArray, canopen.objectdictionary.ODRecord, canopen.objectdictionary.ODVariable]) -> NoneType
64,922
canopen.objectdictionary
get_variable
Get the variable object at specified index (and subindex if applicable). :return: ODVariable if found, else `None`
def get_variable( self, index: Union[int, str], subindex: int = 0 ) -> Optional["ODVariable"]: """Get the variable object at specified index (and subindex if applicable). :return: ODVariable if found, else `None` """ obj = self.get(index) if isinstance(obj, ODVariable): return obj elif isinstance(obj, (ODRecord, ODArray)): return obj.get(subindex)
(self, index: Union[int, str], subindex: int = 0) -> Optional[canopen.objectdictionary.ODVariable]
64,930
canopen.objectdictionary
ObjectDictionaryError
Unsupported operation with the current Object Dictionary.
class ObjectDictionaryError(Exception): """Unsupported operation with the current Object Dictionary."""
null
64,940
canopen.sdo.exceptions
SdoAbortedError
SDO abort exception.
class SdoAbortedError(SdoError): """SDO abort exception.""" CODES = { 0x05030000: "SDO toggle bit error", 0x05040000: "Timeout of transfer communication detected", 0x05040001: "Unknown SDO command specified", 0x05040002: "Invalid block size", 0x05040003: "Invalid sequence number", 0x05040004: "CRC error", 0x05040005: "Out of memory", 0x06010000: "Unsupported access to an object", 0x06010001: "Attempt to read a write only object", 0x06010002: "Attempt to write a read only object", 0x06020000: "Object does not exist", 0x06040041: "Object cannot be mapped to the PDO", 0x06040042: "PDO length exceeded", 0x06040043: "General parameter incompatibility reason", 0x06040047: "General internal incompatibility in the device", 0x06060000: "Access failed due to a hardware error", 0x06070010: "Data type and length code do not match", 0x06070012: "Data type does not match, length of service parameter too high", 0x06070013: "Data type does not match, length of service parameter too low", 0x06090011: "Subindex does not exist", 0x06090030: "Value range of parameter exceeded", 0x06090031: "Value of parameter written too high", 0x06090032: "Value of parameter written too low", 0x06090036: "Maximum value is less than minimum value", 0x060A0023: "Resource not available", 0x08000000: "General error", 0x08000020: "Data cannot be transferred or stored to the application", 0x08000021: ("Data can not be transferred or stored to the application " "because of local control"), 0x08000022: ("Data can not be transferred or stored to the application " "because of the present device state"), 0x08000023: ("Object dictionary dynamic generation fails or no object " "dictionary is present"), 0x08000024: "No data available", } def __init__(self, code: int): #: Abort code self.code = code def __str__(self): text = "Code 0x{:08X}".format(self.code) if self.code in self.CODES: text = text + ", " + self.CODES[self.code] return text
(code: int)
64,941
canopen.sdo.exceptions
__init__
null
def __init__(self, code: int): #: Abort code self.code = code
(self, code: int)
64,942
canopen.sdo.exceptions
__str__
null
def __str__(self): text = "Code 0x{:08X}".format(self.code) if self.code in self.CODES: text = text + ", " + self.CODES[self.code] return text
(self)
64,943
canopen.sdo.exceptions
SdoCommunicationError
No or unexpected response from slave.
class SdoCommunicationError(SdoError): """No or unexpected response from slave."""
null
64,946
canopen.objectdictionary
export_od
Export :class: ObjectDictionary to a file. :param od: :class: ObjectDictionary object to be exported :param dest: export destination. filename, or file-like object or None. if None, the document is returned as string :param doc_type: type of document to export. If a filename is given for dest, this default to the file extension. Otherwise, this defaults to "eds" :rtype: str or None
def export_od(od, dest:Union[str,TextIO,None]=None, doc_type:Optional[str]=None): """ Export :class: ObjectDictionary to a file. :param od: :class: ObjectDictionary object to be exported :param dest: export destination. filename, or file-like object or None. if None, the document is returned as string :param doc_type: type of document to export. If a filename is given for dest, this default to the file extension. Otherwise, this defaults to "eds" :rtype: str or None """ doctypes = {"eds", "dcf"} if isinstance(dest, str): if doc_type is None: for t in doctypes: if dest.endswith(f".{t}"): doc_type = t break if doc_type is None: doc_type = "eds" dest = open(dest, 'w') assert doc_type in doctypes if doc_type == "eds": from canopen.objectdictionary import eds return eds.export_eds(od, dest) elif doc_type == "dcf": from canopen.objectdictionary import eds return eds.export_dcf(od, dest) # If dest is opened in this fn, it should be closed if type(dest) is str: dest.close()
(od, dest: Union[str, TextIO, NoneType] = None, doc_type: Optional[str] = None)
64,947
canopen.objectdictionary
import_od
Parse an EDS, DCF, or EPF file. :param source: Path to object dictionary file or a file like object or an EPF XML tree. :return: An Object Dictionary instance.
def import_od( source: Union[str, TextIO, None], node_id: Optional[int] = None, ) -> "ObjectDictionary": """Parse an EDS, DCF, or EPF file. :param source: Path to object dictionary file or a file like object or an EPF XML tree. :return: An Object Dictionary instance. """ if source is None: return ObjectDictionary() if hasattr(source, "read"): # File like object filename = source.name elif hasattr(source, "tag"): # XML tree, probably from an EPF file filename = "od.epf" else: # Path to file filename = source suffix = filename[filename.rfind("."):].lower() if suffix in (".eds", ".dcf"): from canopen.objectdictionary import eds return eds.import_eds(source, node_id) elif suffix == ".epf": from canopen.objectdictionary import epf return epf.import_epf(source) else: raise NotImplementedError("No support for this format")
(source: Union[str, TextIO, NoneType], node_id: Optional[int] = None) -> canopen.objectdictionary.ObjectDictionary
64,959
alibaba_sms
APIError
接口返回结果,但是状态异常 :param code: 阿里云错误码 :param message: 原因
class APIError(SMSError): """接口返回结果,但是状态异常 :param code: 阿里云错误码 :param message: 原因 """ def __init__(self, code, message): self.code = code self.message = message
(code, message)
64,960
alibaba_sms
__init__
null
def __init__(self, code, message): self.code = code self.message = message
(self, code, message)
64,961
alibaba_sms
AliSMS
null
class AliSMS: def __init__(self, access_key_id, access_key_secret, url=ALIYUN_SMS_URL, *, sign_name=None, template_code=None, timestamp=None, timeout=None, message_translate=MESSAGE_TRANSLATE): """ 初始化传入一些能够复用的参数 :param access_key_id: 阿里云 AccessKey ID,此用户必须拥有短信管理权限 :param access_key_secret: 阿里云 AccessKey Secret,此用户必须拥有短信管理权限 :param url: 阿里云短信API地址 :param sign_name: 短信签名名称,此参数在send函数未传入签名时作为默认签名名称使用 :param template_code: 短信模板编号,此参数在send函数未传入模板时作为默认模板编号使用 :param timestamp: 允许传入时间戳,校准系统时间 :param timeout: 短信发送超时时间 :param message_translate: 将阿里云错误码翻译为自定义错误消息 """ self.id = access_key_id self.secret = access_key_secret self.url = url self.sign_name = sign_name self.template_code = template_code if timestamp is None: timestamp = get_timestamp() self.timestamp = timestamp self.initial_monotonic = time.monotonic() self.timeout = timeout self.message_translate = message_translate self.session = requests.Session() def __del__(self): self.session.close() def get_time_string(self): """获取ISO格式UTC时间字符串""" now = datetime.utcfromtimestamp( self.timestamp + time.monotonic() - self.initial_monotonic ) return now.strftime("%Y-%m-%dT%H:%M:%SZ") def sign(self, params): """为请求参数生成签名 :param params: 请求参数 :return: 签名 """ # 阿里云RPC风格接口文档注明了空格被编码为 %20 而非 + # 但是 urlencode 函数默认使用 urllib.parse.quote_plus 编码参数,空格将被编码为 + # 因而传入 quote_via=quote query = urlencode(params, quote_via=quote) string_to_sign = "POST&%2F&" + quote(query) digest_maker = hmac.new( f"{self.secret}&".encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha1 ) hash_bytes = digest_maker.digest() return base64.b64encode(hash_bytes).decode("utf-8") def send(self, phone_number, code, sign_name=None, template_code=None): """发送短信验证码 以下实现均基于官方API文档: 1. 阿里云短信发送文档 https://help.aliyun.com/document_detail/419273.html?spm=a2c4g.419298.0.0.59852b01bH26fl 2. 阿里云RPC风格接口 https://help.aliyun.com/zh/sdk/product-overview/rpc-mechanism?spm=a2c4g.419298.0.0.7f4130dckTHCGX#sectiondiv-two-7vy-u3i """ sign_name = sign_name or self.sign_name assert sign_name, "必须传入短信签名名称" template_code = template_code or self.template_code assert template_code, "必须传入短信模板编号" # Python3.6 之后,字典都为有序字典,手动按照字典序排序参数,可免去排序步骤 params = { "AccessKeyId": self.id, "Action": "SendSms", "Format": "JSON", "PhoneNumbers": phone_number, "SignName": sign_name, "SignatureMethod": "HMAC-SHA1", "SignatureNonce": get_random_string(32), "SignatureVersion": "1.0", "TemplateCode": template_code, "TemplateParam": json.dumps({"code": code}, separators=(",", ":")), "Timestamp": self.get_time_string(), "Version": "2017-05-25", } params["Signature"] = self.sign(params) try: result = self.session.post(self.url, data=params, timeout=self.timeout).json() except requests.RequestException as e: logger.exception(f"短信请求失败") raise RequestError from e try: code, message = result["Code"], result["Message"] except (TypeError, KeyError): logger.info("请求结果: %s", result) raise APIError("", "接口返回数据格式错误") if code != "OK": logger.info("短信发送结果:%s", result) msg = self.message_translate.get(code, message) raise APIError(code, msg)
(access_key_id, access_key_secret, url='https://dysmsapi.aliyuncs.com/', *, sign_name=None, template_code=None, timestamp=None, timeout=None, message_translate={'isv.BUSINESS_LIMIT_CONTROL': '验证码发送超过限制,请稍后再试'})
64,962
alibaba_sms
__del__
null
def __del__(self): self.session.close()
(self)
64,963
alibaba_sms
__init__
初始化传入一些能够复用的参数 :param access_key_id: 阿里云 AccessKey ID,此用户必须拥有短信管理权限 :param access_key_secret: 阿里云 AccessKey Secret,此用户必须拥有短信管理权限 :param url: 阿里云短信API地址 :param sign_name: 短信签名名称,此参数在send函数未传入签名时作为默认签名名称使用 :param template_code: 短信模板编号,此参数在send函数未传入模板时作为默认模板编号使用 :param timestamp: 允许传入时间戳,校准系统时间 :param timeout: 短信发送超时时间 :param message_translate: 将阿里云错误码翻译为自定义错误消息
def __init__(self, access_key_id, access_key_secret, url=ALIYUN_SMS_URL, *, sign_name=None, template_code=None, timestamp=None, timeout=None, message_translate=MESSAGE_TRANSLATE): """ 初始化传入一些能够复用的参数 :param access_key_id: 阿里云 AccessKey ID,此用户必须拥有短信管理权限 :param access_key_secret: 阿里云 AccessKey Secret,此用户必须拥有短信管理权限 :param url: 阿里云短信API地址 :param sign_name: 短信签名名称,此参数在send函数未传入签名时作为默认签名名称使用 :param template_code: 短信模板编号,此参数在send函数未传入模板时作为默认模板编号使用 :param timestamp: 允许传入时间戳,校准系统时间 :param timeout: 短信发送超时时间 :param message_translate: 将阿里云错误码翻译为自定义错误消息 """ self.id = access_key_id self.secret = access_key_secret self.url = url self.sign_name = sign_name self.template_code = template_code if timestamp is None: timestamp = get_timestamp() self.timestamp = timestamp self.initial_monotonic = time.monotonic() self.timeout = timeout self.message_translate = message_translate self.session = requests.Session()
(self, access_key_id, access_key_secret, url='https://dysmsapi.aliyuncs.com/', *, sign_name=None, template_code=None, timestamp=None, timeout=None, message_translate={'isv.BUSINESS_LIMIT_CONTROL': '验证码发送超过限制,请稍后再试'})
64,964
alibaba_sms
get_time_string
获取ISO格式UTC时间字符串
def get_time_string(self): """获取ISO格式UTC时间字符串""" now = datetime.utcfromtimestamp( self.timestamp + time.monotonic() - self.initial_monotonic ) return now.strftime("%Y-%m-%dT%H:%M:%SZ")
(self)
64,965
alibaba_sms
send
发送短信验证码 以下实现均基于官方API文档: 1. 阿里云短信发送文档 https://help.aliyun.com/document_detail/419273.html?spm=a2c4g.419298.0.0.59852b01bH26fl 2. 阿里云RPC风格接口 https://help.aliyun.com/zh/sdk/product-overview/rpc-mechanism?spm=a2c4g.419298.0.0.7f4130dckTHCGX#sectiondiv-two-7vy-u3i
def send(self, phone_number, code, sign_name=None, template_code=None): """发送短信验证码 以下实现均基于官方API文档: 1. 阿里云短信发送文档 https://help.aliyun.com/document_detail/419273.html?spm=a2c4g.419298.0.0.59852b01bH26fl 2. 阿里云RPC风格接口 https://help.aliyun.com/zh/sdk/product-overview/rpc-mechanism?spm=a2c4g.419298.0.0.7f4130dckTHCGX#sectiondiv-two-7vy-u3i """ sign_name = sign_name or self.sign_name assert sign_name, "必须传入短信签名名称" template_code = template_code or self.template_code assert template_code, "必须传入短信模板编号" # Python3.6 之后,字典都为有序字典,手动按照字典序排序参数,可免去排序步骤 params = { "AccessKeyId": self.id, "Action": "SendSms", "Format": "JSON", "PhoneNumbers": phone_number, "SignName": sign_name, "SignatureMethod": "HMAC-SHA1", "SignatureNonce": get_random_string(32), "SignatureVersion": "1.0", "TemplateCode": template_code, "TemplateParam": json.dumps({"code": code}, separators=(",", ":")), "Timestamp": self.get_time_string(), "Version": "2017-05-25", } params["Signature"] = self.sign(params) try: result = self.session.post(self.url, data=params, timeout=self.timeout).json() except requests.RequestException as e: logger.exception(f"短信请求失败") raise RequestError from e try: code, message = result["Code"], result["Message"] except (TypeError, KeyError): logger.info("请求结果: %s", result) raise APIError("", "接口返回数据格式错误") if code != "OK": logger.info("短信发送结果:%s", result) msg = self.message_translate.get(code, message) raise APIError(code, msg)
(self, phone_number, code, sign_name=None, template_code=None)
64,966
alibaba_sms
sign
为请求参数生成签名 :param params: 请求参数 :return: 签名
def sign(self, params): """为请求参数生成签名 :param params: 请求参数 :return: 签名 """ # 阿里云RPC风格接口文档注明了空格被编码为 %20 而非 + # 但是 urlencode 函数默认使用 urllib.parse.quote_plus 编码参数,空格将被编码为 + # 因而传入 quote_via=quote query = urlencode(params, quote_via=quote) string_to_sign = "POST&%2F&" + quote(query) digest_maker = hmac.new( f"{self.secret}&".encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha1 ) hash_bytes = digest_maker.digest() return base64.b64encode(hash_bytes).decode("utf-8")
(self, params)
64,967
alibaba_sms
RequestError
请求错误,未能返回结果
class RequestError(SMSError): """请求错误,未能返回结果""" pass
null
64,968
alibaba_sms
SMSError
API错误基类
class SMSError(Exception): """API错误基类""" pass
null
64,971
alibaba_sms
get_random_string
生成随机字符串
def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS): """生成随机字符串""" return "".join(secrets.choice(allowed_chars) for _ in range(length))
(length, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
64,972
alibaba_sms
get_timestamp
获取当前时间戳 为避免本地时钟不准确,首先尝试从淘宝获取时间戳
def get_timestamp(): """获取当前时间戳 为避免本地时钟不准确,首先尝试从淘宝获取时间戳 """ try: return int(requests.get(TAOBAO_TIMESTAMP_URL).json()["data"]["t"]) / 1000 except Exception: logger.exception("get ts from taobao failed") return time.time()
()
64,983
mdutils.tools.Html
Html
null
class Html: @staticmethod def paragraph(text: str, align: str = None) -> str: """ :param text: :param align: ``center`` or ``right``. :type align: str :return: ``"<p align=\"{}\">\\n {}\\n</p>".format(align, text)``. :rtype: str """ if align is None: return "<p>\n {}\n</p>".format(text) if align is not None: if align not in ["left", "center", "right"]: raise KeyError return '<p align="{}">\n {}\n</p>'.format(align, text) @classmethod def image(cls, path: str, size: str = None, align: str = None) -> str: """ :param path: :type path: str :param size: (In px) for width write ``'<int>'``, for height write ``'x<int>'`` or \ width and height ``'<int>x<int>``. :type size: str :param align: can be ``'left'``, ``'center'`` or ``'right'``. :type align: str :return: html format :rtype: str :Example: >>> Html.image(path='../image.jpg', size='200', align='center') >>> Html.image(path='../image.jpg', size='x200', align='left') >>> Html.image(path='../image.jpg', size='300x400') """ if align: return cls.paragraph( text=cls.__html_image(path=path, size=size), align=align ) return cls.__html_image(path=path, size=size) @classmethod def __html_image(cls, path: str, size: str = None): if size: return '<img src="{}" {}/>'.format( path, HtmlSize.size_to_width_and_height(size=size) ) return '<img src="{}" />'.format(path)
()
64,984
mdutils.tools.Html
paragraph
:param text: :param align: ``center`` or ``right``. :type align: str :return: ``"<p align="{}">\n {}\n</p>".format(align, text)``. :rtype: str
@staticmethod def paragraph(text: str, align: str = None) -> str: """ :param text: :param align: ``center`` or ``right``. :type align: str :return: ``"<p align=\"{}\">\\n {}\\n</p>".format(align, text)``. :rtype: str """ if align is None: return "<p>\n {}\n</p>".format(text) if align is not None: if align not in ["left", "center", "right"]: raise KeyError return '<p align="{}">\n {}\n</p>'.format(align, text)
(text: str, align: Optional[str] = None) -> str
64,987
mdutils.tools.MDList
MDList
This class allows to create unordered or ordered MarkDown list.
class MDList(MDListHelper): """This class allows to create unordered or ordered MarkDown list.""" def __init__(self, items, marked_with: str = "-"): """ :param items: Array of items for generating the list. :type items: [str] :param marked_with: By default has the value of ``'-'``, can be ``'+'``, ``'*'``. If you want to generate an ordered list then set to ``'1'``. :type marked_with: str """ super().__init__() self.md_list = ( self._get_ordered_markdown_list(items) if marked_with == "1" else self._get_unordered_markdown_list(items, marked_with) ) def get_md(self) -> str: """Get the list in markdown format. :return: :rtype: str """ return self.md_list
(items, marked_with: str = '-')
64,988
mdutils.tools.MDList
__init__
:param items: Array of items for generating the list. :type items: [str] :param marked_with: By default has the value of ``'-'``, can be ``'+'``, ``'*'``. If you want to generate an ordered list then set to ``'1'``. :type marked_with: str
def __init__(self, items, marked_with: str = "-"): """ :param items: Array of items for generating the list. :type items: [str] :param marked_with: By default has the value of ``'-'``, can be ``'+'``, ``'*'``. If you want to generate an ordered list then set to ``'1'``. :type marked_with: str """ super().__init__() self.md_list = ( self._get_ordered_markdown_list(items) if marked_with == "1" else self._get_unordered_markdown_list(items, marked_with) )
(self, items, marked_with: str = '-')
64,989
mdutils.tools.MDList
_add_new_item
null
def _add_new_item(self, item: str, marker: str): item_with_hyphen = ( item if self._is_there_marker_in_item(item) else self._add_hyphen(item, marker) ) return self._n_spaces(4 * self.n_tabs) + item_with_hyphen + "\n"
(self, item: str, marker: str)
64,990
mdutils.tools.MDList
_get_ordered_markdown_list
null
def _get_ordered_markdown_list(self, items) -> str: md_list = "" n_marker = 1 for item in items: if isinstance(item, list): self.n_tabs += 1 md_list += self._get_ordered_markdown_list(items=item) self.n_tabs -= 1 else: md_list += self._add_new_item(item, f"{n_marker}.") n_marker += 1 return md_list
(self, items) -> str
64,991
mdutils.tools.MDList
_get_unordered_markdown_list
null
def _get_unordered_markdown_list(self, items, marker: str) -> str: md_list = "" for item in items: if isinstance(item, list): self.n_tabs += 1 md_list += self._get_unordered_markdown_list(item, marker) self.n_tabs -= 1 else: md_list += self._add_new_item(item, marker) return md_list
(self, items, marker: str) -> str
64,992
mdutils.tools.MDList
get_md
Get the list in markdown format. :return: :rtype: str
def get_md(self) -> str: """Get the list in markdown format. :return: :rtype: str """ return self.md_list
(self) -> str
64,993
mdutils.mdutils
MdUtils
This class give some basic methods that helps the creation of Markdown files while you are executing a python code. The ``__init__`` variables are: - **file_name:** it is the name of the Markdown file. - **author:** it is the author fo the Markdown file. - **header:** it is an instance of Header Class. - **textUtils:** it is an instance of TextUtils Class. - **title:** it is the title of the Markdown file. It is written with Setext-style. - **table_of_contents:** it is the table of contents, it can be optionally created. - **file_data_text:** contains all the file data that will be written on the markdown file.
class MdUtils: """This class give some basic methods that helps the creation of Markdown files while you are executing a python code. The ``__init__`` variables are: - **file_name:** it is the name of the Markdown file. - **author:** it is the author fo the Markdown file. - **header:** it is an instance of Header Class. - **textUtils:** it is an instance of TextUtils Class. - **title:** it is the title of the Markdown file. It is written with Setext-style. - **table_of_contents:** it is the table of contents, it can be optionally created. - **file_data_text:** contains all the file data that will be written on the markdown file. """ def __init__(self, file_name: str, title: str = "", author: str = ""): """ :param file_name: it is the name of the Markdown file. :type file_name: str :param title: it is the title of the Markdown file. It is written with Setext-style. :type title: str :param author: it is the author fo the Markdown file. :type author: str """ self.file_name = file_name self.author = author self.header = Header() self.textUtils = TextUtils self.title = self.header.choose_header(level=1, title=title, style="setext") self.table_of_contents = "" self.file_data_text = "" self._table_titles = [] self.reference = Reference() self.image = Image(reference=self.reference) def create_md_file(self) -> MarkDownFile: """It creates a new Markdown file. :return: return an instance of a MarkDownFile.""" md_file = MarkDownFile(self.file_name) md_file.rewrite_all_file( data=self.title + self.table_of_contents + self.file_data_text + self.reference.get_references_as_markdown() ) return md_file def get_md_text(self) -> str: """Instead of writing the markdown text into a file it returns it as a string. :return: return a string with the markdown text.""" return ( self.title + self.table_of_contents + self.file_data_text + self.reference.get_references_as_markdown() ) def read_md_file(self, file_name: str) -> str: """Reads a Markdown file and save it to global class `file_data_text`. :param file_name: Markdown file's name that has to be read. :type file_name: str :return: optionally returns the file data content. :rtype: str """ file_data = MarkDownFile().read_file(file_name) self.___update_file_data(file_data) return file_data def new_header( self, level: int, title: str, style: str = "atx", add_table_of_contents: str = "y", header_id: str = "", ) -> str: """Add a new header to the Markdown file. :param level: Header level. *atx* style can take values 1 til 6 and *setext* style take values 1 and 2. :type level: int :param title: Header title. :type title: str :param style: Header style, can be ``'atx'`` or ``'setext'``. By default ``'atx'`` style is chosen. :type style: str :param add_table_of_contents: by default the atx and setext headers of level 1 and 2 are added to the \ table of contents, setting this parameter to 'n'. :type add_table_of_contents: str :param header_id: ID of the header for extended Markdown syntax :type header_id: str :Example: >>> from mdutils import MdUtils >>> mdfile = MdUtils("Header_Example") >>> print(mdfile.new_header(level=2, title='Header Level 2 Title', style='atx', add_table_of_contents='y')) '\\n## Header Level 2 Title\\n' >>> print(mdfile.new_header(level=2, title='Header Title', style='setext')) '\\nHeader Title\\n-------------\\n' """ if add_table_of_contents == "y": self.__add_new_item_table_of_content(level, title) self.___update_file_data( self.header.choose_header(level, title, style, header_id) ) return self.header.choose_header(level, title, style, header_id) def __add_new_item_table_of_content(self, level: int, item: Union[List[str], str]): """Automatically add new atx headers to the table of contents. :param level: add levels up to 6. :type level: int :param item: items to add. :type item: list or str """ curr = self._table_titles for i in range(level - 1): curr = curr[-1] curr.append(item) if level < 6: curr.append([]) def new_table_of_contents( self, table_title: str = "Table of contents", depth: int = 1, marker: str = "" ) -> str: """Table of contents can be created if Headers of 'atx' style have been defined. This method allows to create a table of contents and define a title for it. Moreover, `depth` allows user to define how many levels of headers will be placed in the table of contents. If no marker is defined, the table of contents will be placed automatically after the file's title. :param table_title: The table content's title, by default "Table of contents" :type table_title: str :param depth: allows to include atx headers 1 through 6. Possible values: 1, 2, 3, 4, 5, or 6. :type depth: int :param marker: allows to place the table of contents using a marker. :type marker: str :return: a string with the data is returned. :rtype: str """ if marker: self.table_of_contents = "" marker_table_of_contents = self.header.choose_header( level=1, title=table_title, style="setext" ) marker_table_of_contents += mdutils.tools.TableOfContents.TableOfContents().create_table_of_contents( self._table_titles, depth ) self.file_data_text = self.place_text_using_marker( marker_table_of_contents, marker ) else: marker_table_of_contents = "" self.table_of_contents += self.header.choose_header( level=1, title=table_title, style="setext" ) self.table_of_contents += mdutils.tools.TableOfContents.TableOfContents().create_table_of_contents( self._table_titles, depth ) return self.table_of_contents + marker_table_of_contents def new_table( self, columns: int, rows: int, text: List[str], text_align: str = "center", marker: str = "", ) -> str: """This method takes a list of strings and creates a table. Using arguments ``columns`` and ``rows`` allows to create a table of *n* columns and *m* rows. The ``columns * rows`` operations has to correspond to the number of elements of ``text`` list argument. Moreover, ``argument`` allows to place the table wherever you want from the file. :param columns: this variable defines how many columns will have the table. :type columns: int :param rows: this variable defines how many rows will have the table. :type rows: int :param text: it is a list containing all the strings which will be placed in the table. :type text: list :param text_align: allows to align all the cells to the ``'right'``, ``'left'`` or ``'center'``. By default: ``'center'``. :type text_align: str :param marker: using ``create_marker`` method can place the table anywhere of the markdown file. :type marker: str :return: can return the table created as a string. :rtype: str :Example: >>> from mdutils import MdUtils >>> md = MdUtils(file_name='Example') >>> text_list = ['List of Items', 'Description', 'Result', 'Item 1', 'Description of item 1', '10', 'Item 2', 'Description of item 2', '0'] >>> table = md.new_table(columns=3, rows=3, text=text_list, text_align='center') >>> print(repr(table)) '\\n|List of Items|Description|Result|\\n| :---: | :---: | :---: |\\n|Item 1|Description of item 1|10|\\n|Item 2|Description of item 2|0|\\n' .. csv-table:: **Table result on Markdown** :header: "List of Items", "Description", "Results" "Item 1", "Description of Item 1", 10 "Item 2", "Description of Item 2", 0 """ new_table = mdutils.tools.Table.Table() text_table = new_table.create_table(columns, rows, text, text_align) if marker: self.file_data_text = self.place_text_using_marker(text_table, marker) else: self.___update_file_data(text_table) return text_table def new_paragraph( self, text: str = "", bold_italics_code: str = "", color: str = "black", align: str = "", wrap_width: int = 0, ) -> str: """Add a new paragraph to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``. :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: ``'\\n\\n' + text``. Not necessary to take it, if only has to be written to the file. :rtype: str """ if wrap_width > 0: text = fill( text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False, ) if bold_italics_code or color != "black" or align: self.___update_file_data( "\n\n" + self.textUtils.text_format(text, bold_italics_code, color, align) ) else: self.___update_file_data("\n\n" + text) return self.file_data_text def new_line( self, text: str = "", bold_italics_code: str = "", color: str = "black", align: str = "", wrap_width: int = 0, ) -> str: """Add a new line to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: return a string ``'\\n' + text``. Not necessary to take it, if only has to be written to the file. :rtype: str """ if wrap_width > 0: text = fill( text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False, ) if bold_italics_code or color != "black" or align: self.___update_file_data( " \n" + self.textUtils.text_format(text, bold_italics_code, color, align) ) else: self.___update_file_data(" \n" + text) return self.file_data_text def write( self, text: str = "", bold_italics_code: str = "", color: str = "black", align: str = "", marker: str = "", wrap_width: int = 0, ) -> str: """Write text in ``file_Data_text`` string. :param text: a text a string. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :param marker: allows to replace a marker on some point of the file by the text. :type marker: str """ if wrap_width > 0: text = fill( text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False, ) if bold_italics_code or color or align: new_text = self.textUtils.text_format(text, bold_italics_code, color, align) else: new_text = text if marker: self.file_data_text = self.place_text_using_marker(new_text, marker) else: self.___update_file_data(new_text) return new_text def insert_code(self, code: str, language: str = "") -> str: """This method allows to insert a peace of code on a markdown file. :param code: code string. :type code: str :param language: code language: python, c++, c#... :type language: str :return: :rtype: str """ md_code = "\n\n" + self.textUtils.insert_code(code, language) self.___update_file_data(md_code) return md_code def create_marker(self, text_marker: str) -> str: """This will add a marker to ``file_data_text`` and returns the marker result in order to be used whenever you need. Markers allows to place them to the string data text and they can be replaced by a peace of text using ``place_text_using_marker`` method. :param text_marker: marker name. :type text_marker: str :return: return a marker of the following form: ``'##--[' + text_marker + ']--##'`` :rtype: str """ new_marker = "##--[" + text_marker + "]--##" self.___update_file_data(new_marker) return new_marker def place_text_using_marker(self, text: str, marker: str) -> str: """It replace a previous marker created with ``create_marker`` with a text string. This method is going to search for the ``marker`` argument, which has been created previously using ``create_marker`` method, in ``file_data_text`` string. :param text: the new string that will replace the marker. :type text: str :param marker: the marker that has to be replaced. :type marker: str :return: return a new file_data_text with the replace marker. :rtype: str """ return self.file_data_text.replace(marker, text) def ___update_file_data(self, file_data): self.file_data_text += file_data def new_inline_link( self, link: str, text: Optional[str] = None, bold_italics_code: str = "", align: str = "", ) -> str: """Creates a inline link in markdown format. :param link: :type link: str :param text: Text that is going to be displayed in the markdown file as a link. :type text: str :param bold_italics_code: Using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :return: returns the link in markdown format ``'[ + text + '](' + link + ')'``. If text is not defined returns \ ``'<' + link + '>'``. :rtype: str .. note:: If param text is not provided, link param will be used instead. """ if text is None: n_text = link else: n_text = text if bold_italics_code or align: n_text = self.textUtils.text_format( text=n_text, bold_italics_code=bold_italics_code, align=align ) return Inline.new_link(link=link, text=n_text) def new_reference_link( self, link: str, text: str, reference_tag: Optional[str] = None, bold_italics_code: str = "", align: str = "", ) -> str: """Creates a reference link in markdown format. All references will be stored at the end of the markdown file. :param link: :type link: str :param text: Text that is going to be displayed in the markdown file as a link. :type text: str :param reference_tag: Tag that will be placed at the end of the markdown file jointly with the link. :type reference_tag: str :param bold_italics_code: Using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :return: returns the link in markdown format ``'[ + text + '][' + link + ]'``. :rtype: str .. note:: If param reference_tag is not provided, text param will be used instead. :Example: >>> from mdutils import MdUtils >>> md = MdUtils("Reference link") >>> link = md.new_reference_link(link='https://github.com', text='github', reference_tag='git') >>> md.new_link(link) >>> print(repr(link)) '[github][git]' >>> link = md.new_reference_link(link='https://github.com/didix21/mdutils', text='mdutils') >>> md.new_link(link) >>> print(repr(link)) '[mdutils]' >>> link = md.new_line(md.new_reference_link(link='https://github.com/didix21/mdutils', text='mdutils', reference_tag='md', bold_italics_code='b')) >>> md.new_link(link) >>> print(repr(link)) '[**mdutils**][md]' >>> md.create_md_file() """ if reference_tag is None: if bold_italics_code != "": raise TypeError( "For using bold_italics_code param, reference_tag must be defined" ) if align != "": raise TypeError("For using align, reference_tag must be defined") n_text = text if bold_italics_code or align: n_text = self.textUtils.text_format( text=n_text, bold_italics_code=bold_italics_code, align=align ) return self.reference.new_link( link=link, text=n_text, reference_tag=reference_tag ) @staticmethod def new_inline_image(text: str, path: str) -> str: """Add inline images in a markdown file. For example ``[MyImage](../MyImage.jpg)``. :param text: Text that is going to be displayed in the markdown file as a iamge. :type text: str :param path: Image's path / link. :type path: str :return: return the image in markdown format ``'![ + text + '](' + path + ')'``. :rtype: str """ return Image.new_inline_image(text=text, path=path) def new_reference_image( self, text: str, path: str, reference_tag: Optional[str] = None ) -> str: """Add reference images in a markdown file. For example ``[MyImage][my_image]``. All references will be stored at the end of the markdown file. :param text: Text that is going to be displayed in the markdown file as a image. :type text: str :param path: Image's path / link. :type path: str :param reference_tag: Tag that will be placed at the end of the markdown file jointly with the image's path. :type reference_tag: str :return: return the image in markdown format ``'![ + text + '][' + reference_tag + ']'``. :rtype: str .. note:: If param reference_tag is not provided, text param will be used instead. """ return self.image.new_reference_image( text=text, path=path, reference_tag=reference_tag ) def new_list(self, items: List[str], marked_with: str = "-"): """Add unordered or ordered list in MarkDown file. :param items: Array of items for generating the list. :type items: [str] :param marked_with: By default has the value of ``'-'``, can be ``'+'``, ``'*'``. If you want to generate an ordered list then set to ``'1'``. :type marked_with: str :return: """ mdlist = MDList(items, marked_with) self.___update_file_data("\n" + mdlist.get_md()) def new_checkbox_list(self, items: List[str], checked: bool = False): """Add checkbox list in MarkDown file. :param items: Array of items for generating the checkbox list. :type items: [str] :param checked: if you set this to ``True``. All checkbox will be checked. By default is ``False``. :type checked: bool :return: """ mdcheckbox = MDCheckbox(items=items, checked=checked) self.___update_file_data("\n" + mdcheckbox.get_md())
(file_name: str, title: str = '', author: str = '')
64,994
mdutils.mdutils
___update_file_data
null
def ___update_file_data(self, file_data): self.file_data_text += file_data
(self, file_data)
64,995
mdutils.mdutils
__add_new_item_table_of_content
Automatically add new atx headers to the table of contents. :param level: add levels up to 6. :type level: int :param item: items to add. :type item: list or str
def __add_new_item_table_of_content(self, level: int, item: Union[List[str], str]): """Automatically add new atx headers to the table of contents. :param level: add levels up to 6. :type level: int :param item: items to add. :type item: list or str """ curr = self._table_titles for i in range(level - 1): curr = curr[-1] curr.append(item) if level < 6: curr.append([])
(self, level: int, item: Union[List[str], str])
64,996
mdutils.mdutils
__init__
:param file_name: it is the name of the Markdown file. :type file_name: str :param title: it is the title of the Markdown file. It is written with Setext-style. :type title: str :param author: it is the author fo the Markdown file. :type author: str
def __init__(self, file_name: str, title: str = "", author: str = ""): """ :param file_name: it is the name of the Markdown file. :type file_name: str :param title: it is the title of the Markdown file. It is written with Setext-style. :type title: str :param author: it is the author fo the Markdown file. :type author: str """ self.file_name = file_name self.author = author self.header = Header() self.textUtils = TextUtils self.title = self.header.choose_header(level=1, title=title, style="setext") self.table_of_contents = "" self.file_data_text = "" self._table_titles = [] self.reference = Reference() self.image = Image(reference=self.reference)
(self, file_name: str, title: str = '', author: str = '')
64,997
mdutils.mdutils
create_marker
This will add a marker to ``file_data_text`` and returns the marker result in order to be used whenever you need. Markers allows to place them to the string data text and they can be replaced by a peace of text using ``place_text_using_marker`` method. :param text_marker: marker name. :type text_marker: str :return: return a marker of the following form: ``'##--[' + text_marker + ']--##'`` :rtype: str
def create_marker(self, text_marker: str) -> str: """This will add a marker to ``file_data_text`` and returns the marker result in order to be used whenever you need. Markers allows to place them to the string data text and they can be replaced by a peace of text using ``place_text_using_marker`` method. :param text_marker: marker name. :type text_marker: str :return: return a marker of the following form: ``'##--[' + text_marker + ']--##'`` :rtype: str """ new_marker = "##--[" + text_marker + "]--##" self.___update_file_data(new_marker) return new_marker
(self, text_marker: str) -> str
64,998
mdutils.mdutils
create_md_file
It creates a new Markdown file. :return: return an instance of a MarkDownFile.
def create_md_file(self) -> MarkDownFile: """It creates a new Markdown file. :return: return an instance of a MarkDownFile.""" md_file = MarkDownFile(self.file_name) md_file.rewrite_all_file( data=self.title + self.table_of_contents + self.file_data_text + self.reference.get_references_as_markdown() ) return md_file
(self) -> mdutils.fileutils.fileutils.MarkDownFile
64,999
mdutils.mdutils
get_md_text
Instead of writing the markdown text into a file it returns it as a string. :return: return a string with the markdown text.
def get_md_text(self) -> str: """Instead of writing the markdown text into a file it returns it as a string. :return: return a string with the markdown text.""" return ( self.title + self.table_of_contents + self.file_data_text + self.reference.get_references_as_markdown() )
(self) -> str
65,000
mdutils.mdutils
insert_code
This method allows to insert a peace of code on a markdown file. :param code: code string. :type code: str :param language: code language: python, c++, c#... :type language: str :return: :rtype: str
def insert_code(self, code: str, language: str = "") -> str: """This method allows to insert a peace of code on a markdown file. :param code: code string. :type code: str :param language: code language: python, c++, c#... :type language: str :return: :rtype: str """ md_code = "\n\n" + self.textUtils.insert_code(code, language) self.___update_file_data(md_code) return md_code
(self, code: str, language: str = '') -> str
65,001
mdutils.mdutils
new_checkbox_list
Add checkbox list in MarkDown file. :param items: Array of items for generating the checkbox list. :type items: [str] :param checked: if you set this to ``True``. All checkbox will be checked. By default is ``False``. :type checked: bool :return:
def new_checkbox_list(self, items: List[str], checked: bool = False): """Add checkbox list in MarkDown file. :param items: Array of items for generating the checkbox list. :type items: [str] :param checked: if you set this to ``True``. All checkbox will be checked. By default is ``False``. :type checked: bool :return: """ mdcheckbox = MDCheckbox(items=items, checked=checked) self.___update_file_data("\n" + mdcheckbox.get_md())
(self, items: List[str], checked: bool = False)
65,002
mdutils.mdutils
new_header
Add a new header to the Markdown file. :param level: Header level. *atx* style can take values 1 til 6 and *setext* style take values 1 and 2. :type level: int :param title: Header title. :type title: str :param style: Header style, can be ``'atx'`` or ``'setext'``. By default ``'atx'`` style is chosen. :type style: str :param add_table_of_contents: by default the atx and setext headers of level 1 and 2 are added to the table of contents, setting this parameter to 'n'. :type add_table_of_contents: str :param header_id: ID of the header for extended Markdown syntax :type header_id: str :Example: >>> from mdutils import MdUtils >>> mdfile = MdUtils("Header_Example") >>> print(mdfile.new_header(level=2, title='Header Level 2 Title', style='atx', add_table_of_contents='y')) '\n## Header Level 2 Title\n' >>> print(mdfile.new_header(level=2, title='Header Title', style='setext')) '\nHeader Title\n-------------\n'
def new_header( self, level: int, title: str, style: str = "atx", add_table_of_contents: str = "y", header_id: str = "", ) -> str: """Add a new header to the Markdown file. :param level: Header level. *atx* style can take values 1 til 6 and *setext* style take values 1 and 2. :type level: int :param title: Header title. :type title: str :param style: Header style, can be ``'atx'`` or ``'setext'``. By default ``'atx'`` style is chosen. :type style: str :param add_table_of_contents: by default the atx and setext headers of level 1 and 2 are added to the \ table of contents, setting this parameter to 'n'. :type add_table_of_contents: str :param header_id: ID of the header for extended Markdown syntax :type header_id: str :Example: >>> from mdutils import MdUtils >>> mdfile = MdUtils("Header_Example") >>> print(mdfile.new_header(level=2, title='Header Level 2 Title', style='atx', add_table_of_contents='y')) '\\n## Header Level 2 Title\\n' >>> print(mdfile.new_header(level=2, title='Header Title', style='setext')) '\\nHeader Title\\n-------------\\n' """ if add_table_of_contents == "y": self.__add_new_item_table_of_content(level, title) self.___update_file_data( self.header.choose_header(level, title, style, header_id) ) return self.header.choose_header(level, title, style, header_id)
(self, level: int, title: str, style: str = 'atx', add_table_of_contents: str = 'y', header_id: str = '') -> str
65,003
mdutils.mdutils
new_inline_image
Add inline images in a markdown file. For example ``[MyImage](../MyImage.jpg)``. :param text: Text that is going to be displayed in the markdown file as a iamge. :type text: str :param path: Image's path / link. :type path: str :return: return the image in markdown format ``'![ + text + '](' + path + ')'``. :rtype: str
@staticmethod def new_inline_image(text: str, path: str) -> str: """Add inline images in a markdown file. For example ``[MyImage](../MyImage.jpg)``. :param text: Text that is going to be displayed in the markdown file as a iamge. :type text: str :param path: Image's path / link. :type path: str :return: return the image in markdown format ``'![ + text + '](' + path + ')'``. :rtype: str """ return Image.new_inline_image(text=text, path=path)
(text: str, path: str) -> str
65,004
mdutils.mdutils
new_inline_link
Creates a inline link in markdown format. :param link: :type link: str :param text: Text that is going to be displayed in the markdown file as a link. :type text: str :param bold_italics_code: Using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :return: returns the link in markdown format ``'[ + text + '](' + link + ')'``. If text is not defined returns ``'<' + link + '>'``. :rtype: str .. note:: If param text is not provided, link param will be used instead.
def new_inline_link( self, link: str, text: Optional[str] = None, bold_italics_code: str = "", align: str = "", ) -> str: """Creates a inline link in markdown format. :param link: :type link: str :param text: Text that is going to be displayed in the markdown file as a link. :type text: str :param bold_italics_code: Using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :return: returns the link in markdown format ``'[ + text + '](' + link + ')'``. If text is not defined returns \ ``'<' + link + '>'``. :rtype: str .. note:: If param text is not provided, link param will be used instead. """ if text is None: n_text = link else: n_text = text if bold_italics_code or align: n_text = self.textUtils.text_format( text=n_text, bold_italics_code=bold_italics_code, align=align ) return Inline.new_link(link=link, text=n_text)
(self, link: str, text: Optional[str] = None, bold_italics_code: str = '', align: str = '') -> str
65,005
mdutils.mdutils
new_line
Add a new line to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: return a string ``'\n' + text``. Not necessary to take it, if only has to be written to the file. :rtype: str
def new_line( self, text: str = "", bold_italics_code: str = "", color: str = "black", align: str = "", wrap_width: int = 0, ) -> str: """Add a new line to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: return a string ``'\\n' + text``. Not necessary to take it, if only has to be written to the file. :rtype: str """ if wrap_width > 0: text = fill( text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False, ) if bold_italics_code or color != "black" or align: self.___update_file_data( " \n" + self.textUtils.text_format(text, bold_italics_code, color, align) ) else: self.___update_file_data(" \n" + text) return self.file_data_text
(self, text: str = '', bold_italics_code: str = '', color: str = 'black', align: str = '', wrap_width: int = 0) -> str
65,006
mdutils.mdutils
new_list
Add unordered or ordered list in MarkDown file. :param items: Array of items for generating the list. :type items: [str] :param marked_with: By default has the value of ``'-'``, can be ``'+'``, ``'*'``. If you want to generate an ordered list then set to ``'1'``. :type marked_with: str :return:
def new_list(self, items: List[str], marked_with: str = "-"): """Add unordered or ordered list in MarkDown file. :param items: Array of items for generating the list. :type items: [str] :param marked_with: By default has the value of ``'-'``, can be ``'+'``, ``'*'``. If you want to generate an ordered list then set to ``'1'``. :type marked_with: str :return: """ mdlist = MDList(items, marked_with) self.___update_file_data("\n" + mdlist.get_md())
(self, items: List[str], marked_with: str = '-')
65,007
mdutils.mdutils
new_paragraph
Add a new paragraph to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``. :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: ``'\n\n' + text``. Not necessary to take it, if only has to be written to the file. :rtype: str
def new_paragraph( self, text: str = "", bold_italics_code: str = "", color: str = "black", align: str = "", wrap_width: int = 0, ) -> str: """Add a new paragraph to Markdown file. The text is saved to the global variable file_data_text. :param text: is a string containing the paragraph text. Optionally, the paragraph text is returned. :type text: str :param bold_italics_code: using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``. :type bold_italics_code: str :param color: Can change text color. For example: ``'red'``, ``'green'``, ``'orange'``... :type color: str :param align: Using this parameter you can align text. :type align: str :param wrap_width: wraps text with designated width by number of characters. By default, long words are not broken. Use width of 0 to disable wrapping. :type wrap_width: int :return: ``'\\n\\n' + text``. Not necessary to take it, if only has to be written to the file. :rtype: str """ if wrap_width > 0: text = fill( text, wrap_width, break_long_words=False, replace_whitespace=False, drop_whitespace=False, ) if bold_italics_code or color != "black" or align: self.___update_file_data( "\n\n" + self.textUtils.text_format(text, bold_italics_code, color, align) ) else: self.___update_file_data("\n\n" + text) return self.file_data_text
(self, text: str = '', bold_italics_code: str = '', color: str = 'black', align: str = '', wrap_width: int = 0) -> str
65,008
mdutils.mdutils
new_reference_image
Add reference images in a markdown file. For example ``[MyImage][my_image]``. All references will be stored at the end of the markdown file. :param text: Text that is going to be displayed in the markdown file as a image. :type text: str :param path: Image's path / link. :type path: str :param reference_tag: Tag that will be placed at the end of the markdown file jointly with the image's path. :type reference_tag: str :return: return the image in markdown format ``'![ + text + '][' + reference_tag + ']'``. :rtype: str .. note:: If param reference_tag is not provided, text param will be used instead.
def new_reference_image( self, text: str, path: str, reference_tag: Optional[str] = None ) -> str: """Add reference images in a markdown file. For example ``[MyImage][my_image]``. All references will be stored at the end of the markdown file. :param text: Text that is going to be displayed in the markdown file as a image. :type text: str :param path: Image's path / link. :type path: str :param reference_tag: Tag that will be placed at the end of the markdown file jointly with the image's path. :type reference_tag: str :return: return the image in markdown format ``'![ + text + '][' + reference_tag + ']'``. :rtype: str .. note:: If param reference_tag is not provided, text param will be used instead. """ return self.image.new_reference_image( text=text, path=path, reference_tag=reference_tag )
(self, text: str, path: str, reference_tag: Optional[str] = None) -> str
65,009
mdutils.mdutils
new_reference_link
Creates a reference link in markdown format. All references will be stored at the end of the markdown file. :param link: :type link: str :param text: Text that is going to be displayed in the markdown file as a link. :type text: str :param reference_tag: Tag that will be placed at the end of the markdown file jointly with the link. :type reference_tag: str :param bold_italics_code: Using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :return: returns the link in markdown format ``'[ + text + '][' + link + ]'``. :rtype: str .. note:: If param reference_tag is not provided, text param will be used instead. :Example: >>> from mdutils import MdUtils >>> md = MdUtils("Reference link") >>> link = md.new_reference_link(link='https://github.com', text='github', reference_tag='git') >>> md.new_link(link) >>> print(repr(link)) '[github][git]' >>> link = md.new_reference_link(link='https://github.com/didix21/mdutils', text='mdutils') >>> md.new_link(link) >>> print(repr(link)) '[mdutils]' >>> link = md.new_line(md.new_reference_link(link='https://github.com/didix21/mdutils', text='mdutils', reference_tag='md', bold_italics_code='b')) >>> md.new_link(link) >>> print(repr(link)) '[**mdutils**][md]' >>> md.create_md_file()
def new_reference_link( self, link: str, text: str, reference_tag: Optional[str] = None, bold_italics_code: str = "", align: str = "", ) -> str: """Creates a reference link in markdown format. All references will be stored at the end of the markdown file. :param link: :type link: str :param text: Text that is going to be displayed in the markdown file as a link. :type text: str :param reference_tag: Tag that will be placed at the end of the markdown file jointly with the link. :type reference_tag: str :param bold_italics_code: Using ``'b'``: **bold**, ``'i'``: *italics* and ``'c'``: ``inline_code``... :type bold_italics_code: str :param align: Using this parameter you can align text. For example ``'right'``, ``'left'`` or ``'center'``. :type align: str :return: returns the link in markdown format ``'[ + text + '][' + link + ]'``. :rtype: str .. note:: If param reference_tag is not provided, text param will be used instead. :Example: >>> from mdutils import MdUtils >>> md = MdUtils("Reference link") >>> link = md.new_reference_link(link='https://github.com', text='github', reference_tag='git') >>> md.new_link(link) >>> print(repr(link)) '[github][git]' >>> link = md.new_reference_link(link='https://github.com/didix21/mdutils', text='mdutils') >>> md.new_link(link) >>> print(repr(link)) '[mdutils]' >>> link = md.new_line(md.new_reference_link(link='https://github.com/didix21/mdutils', text='mdutils', reference_tag='md', bold_italics_code='b')) >>> md.new_link(link) >>> print(repr(link)) '[**mdutils**][md]' >>> md.create_md_file() """ if reference_tag is None: if bold_italics_code != "": raise TypeError( "For using bold_italics_code param, reference_tag must be defined" ) if align != "": raise TypeError("For using align, reference_tag must be defined") n_text = text if bold_italics_code or align: n_text = self.textUtils.text_format( text=n_text, bold_italics_code=bold_italics_code, align=align ) return self.reference.new_link( link=link, text=n_text, reference_tag=reference_tag )
(self, link: str, text: str, reference_tag: Optional[str] = None, bold_italics_code: str = '', align: str = '') -> str