docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Returns a list of the indices for the CPU registers. The returned indices can be used to read the register content or grab the register name. Args: self (JLink): the ``JLink`` instance Returns: List of registers.
def register_list(self): num_items = self.MAX_NUM_CPU_REGISTERS buf = (ctypes.c_uint32 * num_items)() num_regs = self._dll.JLINKARM_GetRegisterList(buf, num_items) return buf[:num_regs]
250,031
Retrives and returns the name of an ARM CPU register. Args: self (JLink): the ``JLink`` instance register_index (int): index of the register whose name to retrieve Returns: Name of the register.
def register_name(self, register_index): result = self._dll.JLINKARM_GetRegisterName(register_index) return ctypes.cast(result, ctypes.c_char_p).value.decode()
250,032
Retrives the reasons that the CPU was halted. Args: self (JLink): the ``JLink`` instance Returns: A list of ``JLInkMOEInfo`` instances specifying the reasons for which the CPU was halted. This list may be empty in the case that the CPU is not halted. Raises: JLinkException: on hardware error.
def cpu_halt_reasons(self): buf_size = self.MAX_NUM_MOES buf = (structs.JLinkMOEInfo * buf_size)() num_reasons = self._dll.JLINKARM_GetMOEs(buf, buf_size) if num_reasons < 0: raise errors.JLinkException(num_reasons) return list(buf)[:num_reasons]
250,034
Gets a unit of ``8`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer.
def swd_read8(self, offset): value = self._dll.JLINK_SWD_GetU8(offset) return ctypes.c_uint8(value).value
250,036
Gets a unit of ``16`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer.
def swd_read16(self, offset): value = self._dll.JLINK_SWD_GetU16(offset) return ctypes.c_uint16(value).value
250,037
Gets a unit of ``32`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer.
def swd_read32(self, offset): value = self._dll.JLINK_SWD_GetU32(offset) return ctypes.c_uint32(value).value
250,038
Writes bytes over SWD (Serial Wire Debug). Args: self (JLink): the ``JLink`` instance output (int): the output buffer offset to write to value (int): the value to write to the output buffer nbits (int): the number of bits needed to represent the ``output`` and ``value`` Returns: The bit position of the response in the input buffer.
def swd_write(self, output, value, nbits): pDir = binpacker.pack(output, nbits) pIn = binpacker.pack(value, nbits) bitpos = self._dll.JLINK_SWD_StoreRaw(pDir, pIn, nbits) if bitpos < 0: raise errors.JLinkException(bitpos) return bitpos
250,039
Causes a flush to write all data remaining in output buffers to SWD device. Args: self (JLink): the ``JLink`` instance pad (bool): ``True`` if should pad the data to full byte size Returns: ``None``
def swd_sync(self, pad=False): if pad: self._dll.JLINK_SWD_SyncBytes() else: self._dll.JLINK_SWD_SyncBits() return None
250,040
Writes data to the flash region of a device. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. Args: self (JLink): the ``JLink`` instance addr (int): starting flash address to write to data (list): list of data units to write nbits (int): number of bits to use for each unit Returns: Number of bytes written to flash.
def flash_write(self, addr, data, nbits=None, flags=0): # This indicates that all data written from this point on will go into # the buffer of the flashloader of the DLL. self._dll.JLINKARM_BeginDownload(flags) self.memory_write(addr, data, nbits=nbits) # Start downloading the data into the flash memory. bytes_flashed = self._dll.JLINKARM_EndDownload() if bytes_flashed < 0: raise errors.JLinkFlashException(bytes_flashed) return bytes_flashed
250,041
Returns the number of memory zones supported by the target. Args: self (JLink): the ``JLink`` instance Returns: An integer count of the number of memory zones supported by the target. Raises: JLinkException: on error.
def num_memory_zones(self): count = self._dll.JLINK_GetMemZones(0, 0) if count < 0: raise errors.JLinkException(count) return count
250,043
Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLink): the ``JLink`` instance Returns: A list of all the memory zones as ``JLinkMemoryZone`` structures. Raises: JLinkException: on hardware errors.
def memory_zones(self): count = self.num_memory_zones() if count == 0: return list() buf = (structs.JLinkMemoryZone * count)() res = self._dll.JLINK_GetMemZones(buf, count) if res < 0: raise errors.JLinkException(res) return list(buf)
250,044
Reads memory from the target system in units of bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_bytes (int): number of bytes to read zone (str): memory zone to read from Returns: List of bytes read from the target system. Raises: JLinkException: if memory could not be read.
def memory_read8(self, addr, num_bytes, zone=None): return self.memory_read(addr, num_bytes, zone=zone, nbits=8)
250,046
Reads memory from the target system in units of 16-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_halfwords (int): number of half words to read zone (str): memory zone to read from Returns: List of halfwords read from the target system. Raises: JLinkException: if memory could not be read
def memory_read16(self, addr, num_halfwords, zone=None): return self.memory_read(addr, num_halfwords, zone=zone, nbits=16)
250,047
Reads memory from the target system in units of 32-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_words (int): number of words to read zone (str): memory zone to read from Returns: List of words read from the target system. Raises: JLinkException: if memory could not be read
def memory_read32(self, addr, num_words, zone=None): return self.memory_read(addr, num_words, zone=zone, nbits=32)
250,048
Reads memory from the target system in units of 64-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_long_words (int): number of long words to read Returns: List of long words read from the target system. Raises: JLinkException: if memory could not be read
def memory_read64(self, addr, num_long_words): buf_size = num_long_words buf = (ctypes.c_ulonglong * buf_size)() units_read = self._dll.JLINKARM_ReadMemU64(addr, buf_size, buf, 0) if units_read < 0: raise errors.JLinkException(units_read) return buf[:units_read]
250,049
Writes bytes to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of bytes to write zone (str): optional memory zone to access Returns: Number of bytes written to target. Raises: JLinkException: on memory access error.
def memory_write8(self, addr, data, zone=None): return self.memory_write(addr, data, zone, 8)
250,051
Writes half-words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of half-words to write zone (str): optional memory zone to access Returns: Number of half-words written to target. Raises: JLinkException: on memory access error.
def memory_write16(self, addr, data, zone=None): return self.memory_write(addr, data, zone, 16)
250,052
Writes words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of words to write zone (str): optional memory zone to access Returns: Number of words written to target. Raises: JLinkException: on memory access error.
def memory_write32(self, addr, data, zone=None): return self.memory_write(addr, data, zone, 32)
250,053
Writes long words to memory of a target system. Note: This is little-endian. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of long words to write zone (str): optional memory zone to access Returns: Number of long words written to target. Raises: JLinkException: on memory access error.
def memory_write64(self, addr, data, zone=None): words = [] bitmask = 0xFFFFFFFF for long_word in data: words.append(long_word & bitmask) # Last 32-bits words.append((long_word >> 32) & bitmask) # First 32-bits return self.memory_write32(addr, words, zone=zone)
250,054
Retrieves the values from the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to read Returns: A list of values corresponding one-to-one for each of the given register indices. The returned list of values are the values in order of which the indices were specified. Raises: JLinkException: if a given register is invalid or an error occurs.
def register_read_multiple(self, register_indices): num_regs = len(register_indices) buf = (ctypes.c_uint32 * num_regs)(*register_indices) data = (ctypes.c_uint32 * num_regs)(0) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = (ctypes.c_uint8 * num_regs)(0) res = self._dll.JLINKARM_ReadRegs(buf, data, statuses, num_regs) if res < 0: raise errors.JLinkException(res) return list(data)
250,055
Writes into an ARM register. Note: The data is not immediately written, but is cached before being transferred to the CPU on CPU start. Args: self (JLink): the ``JLink`` instance reg_index (int): the ARM register to write to value (int): the value to write to the register Returns: The value written to the ARM register. Raises: JLinkException: on write error.
def register_write(self, reg_index, value): res = self._dll.JLINKARM_WriteReg(reg_index, value) if res != 0: raise errors.JLinkException('Error writing to register %d' % reg_index) return value
250,056
Writes a value to an ARM ICE register. Args: self (JLink): the ``JLink`` instance register_index (int): the ICE register to write to value (int): the value to write to the ICE register delay (bool): boolean specifying if the write should be delayed Returns: ``None``
def ice_register_write(self, register_index, value, delay=False): self._dll.JLINKARM_WriteICEReg(register_index, int(value), int(delay)) return None
250,058
Returns if the CPU core supports ETM. Args: self (JLink): the ``JLink`` instance. Returns: ``True`` if the CPU has the ETM unit, otherwise ``False``.
def etm_supported(self): res = self._dll.JLINKARM_ETM_IsPresent() if (res == 1): return True # JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices. This # fallback checks if ETM is present by checking the Cortex ROM table # for debugging information for ETM. info = ctypes.c_uint32(0) index = enums.JLinkROMTable.ETM res = self._dll.JLINKARM_GetDebugInfo(index, ctypes.byref(info)) if (res == 1): return False return True
250,059
Writes a value to an ETM register. Args: self (JLink): the ``JLink`` instance. register_index (int): the register to write to. value (int): the value to write to the register. delay (bool): boolean specifying if the write should be buffered. Returns: ``None``
def etm_register_write(self, register_index, value, delay=False): self._dll.JLINKARM_ETM_WriteReg(int(register_index), int(value), int(delay)) return None
250,060
Sets vector catch bits of the processor. The CPU will jump to a vector if the given vector catch is active, and will enter a debug state. This has the effect of halting the CPU as well, meaning the CPU must be explicitly restarted. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error.
def set_vector_catch(self, flags): res = self._dll.JLINKARM_WriteVectorCatch(flags) if res < 0: raise errors.JLinkException(res) return None
250,063
Executes a single step. Steps even if there is a breakpoint. Args: self (JLink): the ``JLink`` instance thumb (bool): boolean indicating if to step in thumb mode Returns: ``None`` Raises: JLinkException: on error
def step(self, thumb=False): method = self._dll.JLINKARM_Step if thumb: method = self._dll.JLINKARM_StepComposite res = method() if res != 0: raise errors.JLinkException("Failed to step over instruction.") return None
250,064
Disassembles and returns the assembly instruction string. Args: self (JLink): the ``JLink`` instance. instruction (int): the instruction address. Returns: A string corresponding to the assembly instruction string at the given instruction address. Raises: JLinkException: on error. TypeError: if ``instruction`` is not a number.
def disassemble_instruction(self, instruction): if not util.is_integer(instruction): raise TypeError('Expected instruction to be an integer.') buf_size = self.MAX_BUF_SIZE buf = (ctypes.c_char * buf_size)() res = self._dll.JLINKARM_DisassembleInst(ctypes.byref(buf), buf_size, instruction) if res < 0: raise errors.JLinkException('Failed to disassemble instruction.') return ctypes.string_at(buf).decode()
250,071
Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error.
def strace_configure(self, port_width): if port_width not in [1, 2, 4]: raise ValueError('Invalid port width: %s' % str(port_width)) config_string = 'PortWidth=%d' % port_width res = self._dll.JLINK_STRACE_Config(config_string.encode()) if res < 0: raise errors.JLinkException('Failed to configure STRACE port') return None
250,072
Clears the trace event specified by the given handle. Args: self (JLink): the ``JLink`` instance. handle (int): handle of the trace event. Returns: ``None`` Raises: JLinkException: on error.
def strace_clear(self, handle): data = ctypes.c_int(handle) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR, ctypes.byref(data)) if res < 0: raise errors.JLinkException('Failed to clear STRACE event.') return None
250,076
Clears all STRACE events. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error.
def strace_clear_all(self): data = 0 res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR_ALL, data) if res < 0: raise errors.JLinkException('Failed to clear all STRACE events.') return None
250,077
Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error.
def strace_set_buffer_size(self, size): size = ctypes.c_uint32(size) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.SET_BUFFER_SIZE, size) if res < 0: raise errors.JLinkException('Failed to set the STRACE buffer size.') return None
250,078
Starts collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
def trace_start(self): cmd = enums.JLinkTraceCommand.START res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to start trace.') return None
250,079
Stops collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
def trace_stop(self): cmd = enums.JLinkTraceCommand.STOP res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to stop trace.') return None
250,080
Flushes the trace buffer. After this method is called, the trace buffer is empty. This method is best called when the device is reset. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
def trace_flush(self): cmd = enums.JLinkTraceCommand.FLUSH res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to flush the trace buffer.') return None
250,081
Retrieves the trace buffer's current capacity. Args: self (JLink): the ``JLink`` instance. Returns: The current capacity of the trace buffer. This is not necessarily the maximum possible size the buffer could be configured with.
def trace_buffer_capacity(self): cmd = enums.JLinkTraceCommand.GET_CONF_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace buffer size.') return data.value
250,082
Sets the capacity for the trace buffer. Args: self (JLink): the ``JLink`` instance. size (int): the new capacity for the trace buffer. Returns: ``None``
def trace_set_buffer_capacity(self, size): cmd = enums.JLinkTraceCommand.SET_CAPACITY data = ctypes.c_uint32(size) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace buffer size.') return None
250,083
Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer.
def trace_min_buffer_capacity(self): cmd = enums.JLinkTraceCommand.GET_MIN_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get min trace buffer size.') return data.value
250,084
Retrieves the maximum size the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The maximum configurable capacity for the trace buffer.
def trace_max_buffer_capacity(self): cmd = enums.JLinkTraceCommand.GET_MAX_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get max trace buffer size.') return data.value
250,085
Sets the format for the trace buffer to use. Args: self (JLink): the ``JLink`` instance. fmt (int): format for the trace buffer; this is one of the attributes of ``JLinkTraceFormat``. Returns: ``None``
def trace_set_format(self, fmt): cmd = enums.JLinkTraceCommand.SET_FORMAT data = ctypes.c_uint32(fmt) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace format.') return None
250,086
Retrieves the current format the trace buffer is using. Args: self (JLink): the ``JLink`` instance. Returns: The current format the trace buffer is using. This is one of the attributes of ``JLinkTraceFormat``.
def trace_format(self): cmd = enums.JLinkTraceCommand.GET_FORMAT data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace format.') return data.value
250,087
Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions.
def trace_region_count(self): cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace region count.') return data.value
250,088
Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region.
def trace_region(self, region_index): cmd = enums.JLinkTraceCommand.GET_REGION_PROPS_EX region = structs.JLinkTraceRegion() region.RegionIndex = int(region_index) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(region)) if (res == 1): raise errors.JLinkException('Failed to get trace region.') return region
250,089
Starts collecting SWO data. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance swo_speed (int): the frequency in Hz used by the target to communicate Returns: ``None`` Raises: JLinkException: on error
def swo_start(self, swo_speed=9600): if self.swo_enabled(): self.swo_stop() info = structs.JLinkSWOStartInfo() info.Speed = swo_speed res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.START, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) self._swo_enabled = True return None
250,091
Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error
def swo_stop(self): res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0) if res < 0: raise errors.JLinkException(res) return None
250,092
Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error
def swo_disable(self, port_mask): res = self._dll.JLINKARM_SWO_DisableTarget(port_mask) if res != 0: raise errors.JLinkException(res) return None
250,094
Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. Args: self (JLink): the ``JLink`` instance num_bytes (int): the number of bytes to flush Returns: ``None`` Raises: JLinkException: on error
def swo_flush(self, num_bytes=None): if num_bytes is None: num_bytes = self.swo_num_bytes() buf = ctypes.c_uint32(num_bytes) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.FLUSH, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
250,095
Retrieves information about the supported SWO speeds. Args: self (JLink): the ``JLink`` instance Returns: A ``JLinkSWOSpeedInfo`` instance describing the target's supported SWO speeds. Raises: JLinkException: on error
def swo_speed_info(self): info = structs.JLinkSWOSpeedInfo() res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) return info
250,096
Retrives the number of bytes in the SWO buffer. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes in the SWO buffer. Raises: JLinkException: on error
def swo_num_bytes(self): res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_NUM_BYTES, 0) if res < 0: raise errors.JLinkException(res) return res
250,097
Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error
def swo_set_host_buffer_size(self, buf_size): buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
250,098
Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error
def swo_set_emu_buffer_size(self, buf_size): buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_EMU, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
250,099
Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the number of compatible speeds to return Returns: A list of compatible SWO speeds in Hz in order from highest to lowest.
def swo_supported_speeds(self, cpu_speed, num_speeds=3): buf_size = num_speeds buf = (ctypes.c_uint32 * buf_size)() res = self._dll.JLINKARM_SWO_GetCompatibleSpeeds(cpu_speed, 0, buf, buf_size) if res < 0: raise errors.JLinkException(res) return list(buf)[:res]
250,100
After starting RTT, get the current number of up buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured up buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails.
def rtt_get_num_up_buffers(self): cmd = enums.JLinkRTTCommand.GETNUMBUF dir = ctypes.c_int(enums.JLinkRTTDirection.UP) return self.rtt_control(cmd, dir)
250,103
After starting RTT, get the current number of down buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured down buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails.
def rtt_get_num_down_buffers(self): cmd = enums.JLinkRTTCommand.GETNUMBUF dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN) return self.rtt_control(cmd, dir)
250,104
Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laid-out configuration structures. Args: self (JLink): the ``JLink`` instance command (int): the command to issue (see enums.JLinkRTTCommand) config (ctypes type): the configuration to pass by reference. Returns: An integer containing the result of the command.
def rtt_control(self, command, config): config_byref = ctypes.byref(config) if config is not None else None res = self._dll.JLINK_RTTERMINAL_Control(command, config_byref) if res < 0: raise errors.JLinkRTTException(res) return res
250,107
Writes kayboard input to JLink RTT buffer #0. This method is a loop that blocks waiting on stdin. When enter is pressed, LF and NUL bytes are added to the input and transmitted as a byte list. If the JLink is disconnected, it will exit gracefully. If any other exceptions are raised, they will be caught and re-raised after interrupting the main thread. Args: jlink (pylink.JLink): The JLink to write to. Raises: Exception on error.
def write_rtt(jlink): try: while jlink.connected(): bytes = list(bytearray(input(), "utf-8") + b"\x0A\x00") bytes_written = jlink.rtt_write(0, bytes) except Exception: print("IO write thread exception, exiting...") thread.interrupt_main() raise
250,109
Initializes the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance daemon (bool): if the thread should be spawned as a daemon args: optional list of arguments kwargs: optional key-word arguments Returns: ``None``
def __init__(self, daemon=False, *args, **kwargs): super(ThreadReturn, self).__init__(*args, **kwargs) self.daemon = daemon self._return = None
250,111
Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None``
def run(self): target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', None)) kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None)) if target is not None: self._return = target(*args, **kwargs) return None
250,112
Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread.
def join(self, *args, **kwargs): super(ThreadReturn, self).join(*args, **kwargs) return self._return
250,113
Generates an exception by coercing the given ``code`` to an error string if is a number, otherwise assumes it is the message. Args: self (JLinkException): the 'JLinkException' instance code (object): message or error code Returns: ``None``
def __init__(self, code): message = code self.code = None if util.is_integer(code): message = self.to_string(code) self.code = code super(JLinkException, self).__init__(message) self.message = message
250,115
Main function. Args: jlink_serial (str): the J-Link serial number device (str): the target CPU Returns: ``None`` Raises: JLinkException: on error
def main(jlink_serial, device): buf = StringIO.StringIO() jlink = pylink.JLink(log=buf.write, detailed_log=buf.write) jlink.open(serial_no=jlink_serial) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(device, verbose=True) # Figure out our original endianess first. big_endian = jlink.set_little_endian() if big_endian: jlink.set_big_endian() print('Target Endian Mode: %s Endian' % ('Big' if big_endian else 'Little'))
250,116
Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Raises: AttributeError: if ``func`` is not callable
def async_decorator(func): @functools.wraps(func) def async_wrapper(*args, **kwargs): if 'callback' not in kwargs or not kwargs['callback']: return func(*args, **kwargs) callback = kwargs.pop('callback') if not callable(callback): raise TypeError('Expected \'callback\' is not callable.') def thread_func(*args, **kwargs): exception, res = None, None try: res = func(*args, **kwargs) except Exception as e: exception = e return callback(exception, res) thread = threads.ThreadReturn(target=thread_func, args=args, kwargs=kwargs) thread.daemon = True thread.start() return thread return async_wrapper
250,117
Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None``
def strace(device, trace_address, breakpoint_address): jlink = pylink.JLink() jlink.open() # Do the initial connection sequence. jlink.power_on() jlink.set_tif(pylink.JLinkInterfaces.SWD) jlink.connect(device) jlink.reset() # Clear any breakpoints that may exist as of now. jlink.breakpoint_clear_all() # Start the simple trace. op = pylink.JLinkStraceOperation.TRACE_START jlink.strace_clear_all() jlink.strace_start() # Set the breakpoint and trace events, then restart the CPU so that it # will execute. bphandle = jlink.breakpoint_set(breakpoint_address, thumb=True) trhandle = jlink.strace_code_fetch_event(op, address=trace_address) jlink.restart() time.sleep(1) # Run until the CPU halts due to the breakpoint being hit. while True: if jlink.halted(): break # Print out all instructions that were captured by the trace. while True: instructions = jlink.strace_read(1) if len(instructions) == 0: break instruction = instructions[0] print(jlink.disassemble_instruction(instruction)) jlink.power_off() jlink.close()
250,118
Main command-line interface entrypoint. Runs the given subcommand or argument that were specified. If not given a ``args`` parameter, assumes the arguments are passed on the command-line. Args: args (list): list of command-line arguments Returns: Zero on success, non-zero otherwise.
def main(args=None): if args is None: args = sys.argv[1:] parser = create_parser() args = parser.parse_args(args) if args.verbose >= 2: level = logging.DEBUG elif args.verbose >= 1: level = logging.INFO else: level = logging.WARNING logging.basicConfig(level=level) try: args.command(args) except pylink.JLinkException as e: sys.stderr.write('Error: %s%s' % (str(e), os.linesep)) return 1 return 0
250,120
Creates a new Command class and validates it. Args: cls (Class): the class object being created name (name): the name of the class being created parents (list): list of parent classes dct (dictionary): class attributes Returns: ``Class``
def __new__(cls, name, parents, dct): newClass = super(CommandMeta, cls).__new__(cls, name, parents, dct) if name != 'Command': for attribute in ['name', 'description', 'help']: if attribute not in dct or dct[attribute] is None: raise ValueError('%s cannot be None.' % attribute) CommandMeta.registry[name] = newClass return newClass
250,121
Creates an instance of a J-Link from the given arguments. Args: self (Command): the ``Command`` instance args (Namespace): arguments to construct the ``JLink`` instance from Returns: An instance of a ``JLink``.
def create_jlink(self, args): jlink = pylink.JLink() jlink.open(args.serial_no, args.ip_addr) if hasattr(args, 'tif') and args.tif is not None: if args.tif.lower() == 'swd': jlink.set_tif(pylink.JLinkInterfaces.SWD) else: jlink.set_tif(pylink.JLinkInterfaces.JTAG) if hasattr(args, 'device') and args.device is not None: jlink.connect(args.device) return jlink
250,122
Adds common arguments to the given parser. Common arguments for a J-Link command are the target interface, and J-Link serial number or IP address. Args: self (Command): the ``Command`` instance parser (argparse.ArgumentParser): the parser to add the arguments to has_device (bool): boolean indicating if it has the device argument Returns: ``None``
def add_common_arguments(self, parser, has_device=False): if has_device: parser.add_argument('-t', '--tif', required=True, type=str.lower, choices=['jtag', 'swd'], help='target interface (JTAG | SWD)') parser.add_argument('-d', '--device', required=True, help='specify the target device name') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-s', '--serial', dest='serial_no', help='specify the J-Link serial number') group.add_argument('-i', '--ip_addr', dest='ip_addr', help='J-Link IP address') return None
250,123
Erases the device connected to the J-Link. Args: self (EraseCommand): the ``EraseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): jlink = self.create_jlink(args) erased = jlink.erase() print('Bytes Erased: %d' % erased)
250,124
Flashes the device connected to the J-Link. Args: self (FlashCommand): the ``FlashCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): kwargs = {} kwargs['path'] = args.file[0] kwargs['addr'] = args.addr kwargs['on_progress'] = pylink.util.flash_progress_callback jlink = self.create_jlink(args) _ = jlink.flash_file(**kwargs) print('Flashed device successfully.')
250,125
Adds the unlock command arguments to the parser. Args: self (UnlockCommand): the ``UnlockCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None``
def add_arguments(self, parser): parser.add_argument('name', nargs=1, choices=['kinetis'], help='name of MCU to unlock') return self.add_common_arguments(parser, True)
250,126
Unlocks the target device. Args: self (UnlockCommand): the ``UnlockCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): jlink = self.create_jlink(args) mcu = args.name[0].lower() if pylink.unlock(jlink, mcu): print('Successfully unlocked device!') else: print('Failed to unlock device!')
250,127
Runs the license command. Args: self (LicenseCommand): the ``LicenseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): jlink = self.create_jlink(args) if args.list: print('Built-in Licenses: %s' % ', '.join(jlink.licenses.split(','))) print('Custom Licenses: %s' % ', '.join(jlink.custom_licenses.split(','))) elif args.add is not None: if jlink.add_license(args.add): print('Successfully added license.') else: print('License already exists.') elif args.erase: if jlink.erase_licenses(): print('Successfully erased all custom licenses.') else: print('Failed to erase custom licenses.')
250,128
Adds the information commands to the parser. Args: self (InfoCommand): the ``InfoCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None``
def add_arguments(self, parser): parser.add_argument('-p', '--product', action='store_true', help='print the production information') parser.add_argument('-j', '--jtag', action='store_true', help='print the JTAG pin status') return self.add_common_arguments(parser, False)
250,129
Runs the information command. Args: self (InfoCommand): the ``InfoCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): jlink = self.create_jlink(args) if args.product: print('Product: %s' % jlink.product_name) manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem print('Manufacturer: %s' % manufacturer) print('Hardware Version: %s' % jlink.hardware_version) print('Firmware: %s' % jlink.firmware_version) print('DLL Version: %s' % jlink.version) print('Features: %s' % ', '.join(jlink.features)) elif args.jtag: status = jlink.hardware_status print('TCK Pin Status: %d' % status.tck) print('TDI Pin Status: %d' % status.tdi) print('TDO Pin Status: %d' % status.tdo) print('TMS Pin Status: %d' % status.tms) print('TRES Pin Status: %d' % status.tres) print('TRST Pin Status: %d' % status.trst)
250,130
Adds the arguments for the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None``
def add_arguments(self, parser): group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', nargs='?', type=str.lower, default='_', choices=['usb', 'ip'], help='list all the connected emulators') group.add_argument('-s', '--supported', nargs=1, help='query whether a device is supported') group.add_argument('-t', '--test', action='store_true', help='perform a self-test') return None
250,131
Runs the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance args (Namespace): arguments to parse Returns: ``None``
def run(self, args): jlink = pylink.JLink() if args.test: if jlink.test(): print('Self-test succeeded.') else: print('Self-test failed.') elif args.list is None or args.list in ['usb', 'ip']: host = pylink.JLinkHost.USB_OR_IP if args.list == 'usb': host = pylink.JLinkHost.USB elif args.list == 'ip': host = pylink.JLinkHost.IP emulators = jlink.connected_emulators(host) for (index, emulator) in enumerate(emulators): if index > 0: print('') print('Product Name: %s' % emulator.acProduct.decode()) print('Serial Number: %s' % emulator.SerialNumber) usb = bool(emulator.Connection) if not usb: print('Nickname: %s' % emulator.acNickname.decode()) print('Firmware: %s' % emulator.acFWString.decode()) print('Connection: %s' % ('USB' if usb else 'IP')) if not usb: print('IP Address: %s' % emulator.aIPAddr) elif args.supported is not None: device = args.supported[0] num_supported_devices = jlink.num_supported_devices() for i in range(num_supported_devices): found_device = jlink.supported_device(i) if device.lower() == found_device.name.lower(): print('Device Name: %s' % device) print('Core ID: %s' % found_device.CoreId) print('Flash Address: %s' % found_device.FlashAddr) print('Flash Size: %s bytes' % found_device.FlashSize) print('RAM Address: %s' % found_device.RAMAddr) print('RAM Size: %s bytes' % found_device.RAMSize) print('Manufacturer: %s' % found_device.manufacturer) break else: print('%s is not supported :(' % device) return None
250,132
Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None``
def add_arguments(self, parser): group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', '--downgrade', action='store_true', help='downgrade the J-Link firmware') group.add_argument('-u', '--upgrade', action='store_true', help='upgrade the J-Link firmware') return self.add_common_arguments(parser, False)
250,133
Runs the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance args (Namespace): arguments to parse Returns: ``None``
def run(self, args): jlink = self.create_jlink(args) if args.downgrade: if not jlink.firmware_newer(): print('DLL firmware is not older than J-Link firmware.') else: jlink.invalidate_firmware() try: # Change to the firmware of the connected DLL. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Downgraded: %s' % jlink.firmware_version) elif args.upgrade: if not jlink.firmware_outdated(): print('DLL firmware is not newer than J-Link firmware.') else: try: # Upgrade the firmware. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Updated: %s' % jlink.firmware_version) return None
250,134
Returns a string representation of the connection info. Args: self (JLinkConnectInfo): the ``JLinkConnectInfo`` instance Returns: String specifying the product, its serial number, and the type of connection that it has (one of USB or IP).
def __str__(self): conn = 'USB' if self.Connection == 1 else 'IP' return '%s <Serial No. %s, Conn. %s>' % (self.acProduct.decode(), self.SerialNumber, conn)
250,135
Initializes the instance. Populates the ``.SizeofStruct`` parameter to the size of the instance. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance args: list of arguments kwargs: key-word arguments dictionary Returns: ``None``
def __init__(self, *args, **kwargs): super(JLinkDeviceInfo, self).__init__(*args, **kwargs) self.SizeofStruct = ctypes.sizeof(self)
250,136
Returns a string representation of this instance. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Returns a string specifying the device name, core, and manufacturer.
def __str__(self): manu = self.manufacturer return '%s <Core Id. %s, Manu. %s>' % (self.name, self.Core, manu)
250,137
Returns the name of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Device name.
def name(self): return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()
250,138
Returns the name of the manufacturer of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Manufacturer name.
def manufacturer(self): buf = ctypes.cast(self.sManu, ctypes.c_char_p).value return buf.decode() if buf else None
250,139
Initializes the ``JLinkSpeedInfo`` instance. Sets the size of the structure. Args: self (JLinkSpeedInfo): the ``JLinkSpeedInfo`` instance Returns: ``None``
def __init__(self): super(JLinkSpeedInfo, self).__init__() self.SizeOfStruct = ctypes.sizeof(self)
250,140
Initializes the J-Link SWO Speed Information instance. Args: self (JLinkSWOSpeedInfo): the ``JLinkSWOSpeedInfo`` instance Returns: ``None``
def __init__(self): super(JLinkSWOSpeedInfo, self).__init__() self.SizeofStruct = ctypes.sizeof(self) self.Interface = enums.JLinkSWOInterfaces.UART
250,141
Returns a string representation of the instance. Args: self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance Returns: A string representation of the instance.
def __str__(self): d = enums.JLinkHaltReasons.__dict__ s = next(k for k, v in d.items() if v == self.HaltReason) if self.dbgrq(): return s return s.replace('_', ' ').title()
250,142
Initializes the ``JLinkBreakpointInfo`` instance. Sets the size of the structure. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instnace Returns: ``None``
def __init__(self): super(JLinkBreakpointInfo, self).__init__() self.SizeOfStruct = ctypes.sizeof(self)
250,143
Returns a formatted string describing the breakpoint. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance Returns: Stirng representation of the breakpoint.
def __str__(self): name = self.__class__.__name__ return '%s(Handle %d, Address %d)' % (name, self.Handle, self.Addr)
250,144
Returns whether this is a software breakpoint. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance Returns: ``True`` if the breakpoint is a software breakpoint, otherwise ``False``.
def software_breakpoint(self): software_types = [ enums.JLinkBreakpoint.SW_RAM, enums.JLinkBreakpoint.SW_FLASH, enums.JLinkBreakpoint.SW ] return any(self.Type & stype for stype in software_types)
250,145
Initializes the ``JLinkDataEvent`` instance. Sets the size of the structure. Args: self (JLinkDataEvent): the ``JLinkDataEvent`` instance Returns: ``None``
def __init__(self): super(JLinkDataEvent, self).__init__() self.SizeOfStruct = ctypes.sizeof(self) self.Type = enums.JLinkEventTypes.BREAKPOINT
250,146
Returns a string representation of the data event. Args: self (JLinkDataEvent): the ``JLinkDataEvent`` instance Returns: A string representation of the data event.
def __str__(self): name = self.__class__.__name__ return '%s(Type %d, Address %d)' % (name, self.Type, self.Addr)
250,147
Initializes the ``JLinkWatchpointInfo`` instance. Sets the size of the structure. Args: self (JLinkWatchpointInfo): the ``JLinkWatchpointInfo`` instance Returns: ``None``
def __init__(self): super(JLinkWatchpointInfo, self).__init__() self.SizeOfStruct = ctypes.sizeof(self)
250,148
Initializes the ``JLinkStraceEventInfo`` instance. Sets the size of the structure. Args: self (JLinkStraceEventInfo): the ``JLinkStraceEventInfo`` instance Returns: ``None``
def __init__(self): super(JLinkStraceEventInfo, self).__init__() self.SizeOfStruct = ctypes.sizeof(self)
250,149
Returns a formatted string describing the event info. Args: self (JLinkStraceEventInfo): the ``JLinkStraceEventInfo`` instance Returns: String representation of the event information.
def __str__(self): name = self.__class__.__name__ return '%s(Type=%d, Op=%d)' % (name, self.Type, self.Op)
250,150
Initializes the trace region. Sets the size of the structure. Args: self (JLinkTraceRegion): the ``JLinkTraceRegion`` instance. Returns: ``None``
def __init__(self): super(JLinkTraceRegion, self).__init__() self.SizeOfStruct = ctypes.sizeof(self)
250,151
Loads the SEGGER DLL from the windows installation directory. On Windows, these are found either under: - ``C:\\Program Files\\SEGGER\\JLink`` - ``C:\\Program Files (x86)\\SEGGER\\JLink``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
def find_library_windows(cls): dll = cls.get_appropriate_windows_sdk_name() + '.dll' root = 'C:\\' for d in os.listdir(root): dir_path = os.path.join(root, d) # Have to account for the different Program Files directories. if d.startswith('Program Files') and os.path.isdir(dir_path): dir_path = os.path.join(dir_path, 'SEGGER') if not os.path.isdir(dir_path): continue # Find all the versioned J-Link directories. ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path)) for jlink_dir in ds: # The DLL always has the same name, so if it is found, just # return it. lib_path = os.path.join(dir_path, jlink_dir, dll) if os.path.isfile(lib_path): yield lib_path
250,152
Loads the SEGGER DLL from the root directory. On Linux, the SEGGER tools are installed under the ``/opt/SEGGER`` directory with versioned directories having the suffix ``_VERSION``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
def find_library_linux(cls): dll = Library.JLINK_SDK_NAME root = os.path.join('/', 'opt', 'SEGGER') for (directory_name, subdirs, files) in os.walk(root): fnames = [] x86_found = False for f in files: path = os.path.join(directory_name, f) if os.path.isfile(path) and f.startswith(dll): fnames.append(f) if '_x86' in path: x86_found = True for fname in fnames: fpath = os.path.join(directory_name, fname) if util.is_os_64bit(): if '_x86' not in fname: yield fpath elif x86_found: if '_x86' in fname: yield fpath else: yield fpath
250,153
Initializes an instance of a ``Library``. Loads the default J-Link DLL if ``dllpath`` is ``None``, otherwise loads the DLL specified by the given ``dllpath``. Args: self (Library): the ``Library`` instance dllpath (str): the DLL to load into the library Returns: ``None``
def __init__(self, dllpath=None): self._lib = None self._winlib = None self._path = None self._windows = sys.platform.startswith('win') self._cygwin = sys.platform.startswith('cygwin') self._temp = None if self._windows or self._cygwin: self._sdk = self.get_appropriate_windows_sdk_name() else: self._sdk = self.JLINK_SDK_NAME if dllpath is not None: self.load(dllpath) else: self.load_default()
250,155
Loads the default J-Link SDK DLL. The default J-Link SDK is determined by first checking if ``ctypes`` can find the DLL, then by searching the platform-specific paths. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was loaded, otherwise ``False``.
def load_default(self): path = ctypes_util.find_library(self._sdk) if path is None: # Couldn't find it the standard way. Fallback to the non-standard # way of finding the J-Link library. These methods are operating # system specific. if self._windows or self._cygwin: path = next(self.find_library_windows(), None) elif sys.platform.startswith('linux'): path = next(self.find_library_linux(), None) elif sys.platform.startswith('darwin'): path = next(self.find_library_darwin(), None) if path is not None: return self.load(path) return False
250,156
Unloads the library's DLL if it has been loaded. This additionally cleans up the temporary DLL file that was created when the library was loaded. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was unloaded, otherwise ``False``.
def unload(self): unloaded = False if self._lib is not None: if self._winlib is not None: # ctypes passes integers as 32-bit C integer types, which will # truncate the value of a 64-bit pointer in 64-bit python, so # we have to change the FreeLibrary method to take a pointer # instead of an integer handle. ctypes.windll.kernel32.FreeLibrary.argtypes = ( ctypes.c_void_p, ) # On Windows we must free both loaded libraries before the # temporary file can be cleaned up. ctypes.windll.kernel32.FreeLibrary(self._lib._handle) ctypes.windll.kernel32.FreeLibrary(self._winlib._handle) self._lib = None self._winlib = None unloaded = True else: # On OSX and Linux, just release the library; it's not safe # to close a dll that ctypes is using. del self._lib self._lib = None unloaded = True if self._temp is not None: os.remove(self._temp.name) self._temp = None return unloaded
250,158
Open a file or ``sys.stdout`` depending on the provided filename. Args: filename (str): The path to the file that should be opened. If ``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is returned depending on the desired mode. Defaults to ``None``. mode (str): The mode that should be used to open the file. Yields: A file handle.
def _open(filename=None, mode='r'): if not filename or filename == '-': if not mode or 'r' in mode: file = sys.stdin elif 'w' in mode: file = sys.stdout else: raise ValueError('Invalid mode for file: {}'.format(mode)) else: file = open(filename, mode) try: yield file finally: if file not in (sys.stdin, sys.stdout): file.close()
250,159