or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

atr-card-types.mdcard-connections.mdgui-components.mdindex.mdmonitoring.mdpcsc-interface.mdreader-management.mdsession-api.mdstatus-word-handling.mdutilities.md
tile.json

tessl/pypi-pyscard

Smartcard library for Python providing PC/SC interface for smart card communication

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyscard@2.3.x

To install, run

npx @tessl/cli install tessl/pypi-pyscard@2.3.0

index.mddocs/

pyscard

A comprehensive Python library for interacting with smart cards through the PC/SC (Personal Computer/Smart Card) interface. pyscard provides both high-level and low-level APIs for smart card communication, enabling developers to build applications that can read from and write to smart cards across multiple platforms (Windows, macOS, Linux).

Package Information

  • Package Name: pyscard
  • Language: Python
  • Installation: pip install pyscard
  • Python Requires: >=3.9
  • Platforms: Windows, macOS, Linux

Core Imports

import smartcard

Common high-level usage:

from smartcard import Session
from smartcard.System import readers

For monitoring and events:

from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.ReaderMonitoring import ReaderMonitor, ReaderObserver

For low-level PC/SC access:

from smartcard import scard

Basic Usage

Simple Card Communication

from smartcard import Session

# Create a session with the first available reader
session = Session()

# Send an APDU command (select telecom directory)
SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02]
DF_TELECOM = [0x7F, 0x10]
response, sw1, sw2 = session.sendCommandAPDU(SELECT + DF_TELECOM)

print(f"Response: {response}")
print(f"Status Words: {sw1:02X} {sw2:02X}")

# Clean up
session.close()

Card Detection and Monitoring

from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.util import toHexString

class MyCardObserver(CardObserver):
    def update(self, observable, actions):
        (addedcards, removedcards) = actions
        for card in addedcards:
            print(f"Card inserted: {toHexString(card.atr)}")
        for card in removedcards:
            print(f"Card removed: {toHexString(card.atr)}")

# Start monitoring
monitor = CardMonitor()
observer = MyCardObserver()
monitor.addObserver(observer)

# Monitor will continue until program exits

Reader Management

from smartcard.System import readers

# List all available readers
reader_list = readers()
for reader in reader_list:
    print(f"Reader: {reader}")

# Get reader names as strings (legacy)
reader_names = smartcard.listReaders()
for name in reader_names:
    print(f"Reader name: {name}")

Architecture

pyscard provides a layered architecture for smart card access:

  • High-level Session API: Simple APDU communication via Session class
  • Framework Layer: Card requests, connections, services, and monitoring
  • PC/SC Layer: Direct access to PC/SC functions through scard module
  • Utility Layer: Data conversion, formatting, and helper functions
  • GUI Components: wxPython-based visual components (optional)

The library handles platform-specific PC/SC implementations automatically (WinSCard on Windows, PCSC-Lite on Unix-like systems).

Capabilities

High-Level Session API

Simple card communication interface providing session management and APDU transmission without requiring detailed knowledge of PC/SC or card connection management.

class Session:
    def __init__(self, readerName=None): ...
    def close(self): ...
    def sendCommandAPDU(self, command): ...
    def getATR(self): ...

def listReaders(): ...

Session API

Card Request and Connection Management

Framework for waiting for card insertion, establishing connections, and managing card communication with fine-grained control over protocols and connection modes.

class CardRequest:
    def __init__(self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1): ...
    def waitforcard(self): ...
    def waitforcardevent(self): ...

class CardConnection:
    def connect(self, protocol=None, mode=None, disposition=None): ...
    def transmit(self, command, protocol=None): ...
    def getATR(self): ...

Card Connections

Card and Reader Monitoring

Event-driven monitoring system for detecting card insertion/removal and reader connection/disconnection with observer pattern implementation.

class CardMonitor:
    def addObserver(self, observer): ...
    def deleteObserver(self, observer): ...

class CardObserver:
    def update(self, observable, handlers): ...

class ReaderMonitor:
    def __init__(self, startOnDemand=True, readerProc=readers, period=1): ...
    def addObserver(self, observer): ...

Monitoring

ATR Processing and Card Type Detection

Tools for parsing Answer To Reset (ATR) sequences, extracting card parameters, and implementing card type detection logic.

class ATR:
    def __init__(self, atr): ...
    def getSupportedProtocols(self): ...
    def getHistoricalBytes(self): ...
    def isT0Supported(self): ...
    def isT1Supported(self): ...

class CardType:
    def matches(self, atr, reader=None): ...

class ATRCardType(CardType):
    def __init__(self, atr, mask=None): ...

ATR and Card Types

System Reader Management

Functions for discovering and managing smart card readers, including reader groups and system-level reader operations.

def readers(groups=None): ...
def readergroups(): ...

class Reader:
    def __init__(self, readername): ...
    def createConnection(self): ...

Reader Management

Low-Level PC/SC Interface

Direct access to PC/SC (Personal Computer/Smart Card) functions and constants, providing complete control over smart card operations at the system level.

# All PC/SC functions and constants available via:
from smartcard.scard import *

PC/SC Interface

Data Utilities and Formatting

Comprehensive utility functions for data conversion between different formats (hex strings, byte lists, ASCII), padding operations, and specialized encoding support.

def toHexString(data, output_format=0): ...
def toBytes(bytestring): ...
def toASCIIBytes(string): ...
def toASCIIString(bytelist): ...
def padd(bytelist, length, padding="FF"): ...

Utilities

Status Word Error Handling

Structured error checking and exception handling for smart card status words (SW1, SW2) with support for various ISO standards and custom error checking chains.

class ErrorChecker:
    def __call__(self, data, sw1, sw2): ...

class ISO7816_4ErrorChecker(ErrorChecker): ...
class ISO7816_8ErrorChecker(ErrorChecker): ...
class ISO7816_9ErrorChecker(ErrorChecker): ...

class SWException(Exception): ...
class WarningProcessingException(SWException): ...

Status Word Handling

GUI Components (Optional)

wxPython-based graphical user interface components for building smart card applications with visual elements like card/reader trees and APDU trace panels.

# GUI components available when wxPython is installed
from smartcard.wx import SimpleSCardApp, APDUTracerPanel

GUI Components

Types

# Core type aliases used throughout the API
ReaderName = str
ATRBytes = list[int]
APDUCommand = list[int]
APDUResponse = list[int]
StatusWord = int

# Protocol constants
T0_protocol = 0x00000001
T1_protocol = 0x00000002
RAW_protocol = 0x00010000
T15_protocol = 0x00000008

# Format constants for utilities
PACK = 1
HEX = 2
UPPERCASE = 4
COMMA = 8