Smartcard library for Python providing PC/SC interface for smart card communication
npx @tessl/cli install tessl/pypi-pyscard@2.3.0A 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).
pip install pyscardimport smartcardCommon high-level usage:
from smartcard import Session
from smartcard.System import readersFor monitoring and events:
from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.ReaderMonitoring import ReaderMonitor, ReaderObserverFor low-level PC/SC access:
from smartcard import scardfrom 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()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 exitsfrom 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}")pyscard provides a layered architecture for smart card access:
Session classscard moduleThe library handles platform-specific PC/SC implementations automatically (WinSCard on Windows, PCSC-Lite on Unix-like systems).
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(): ...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): ...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): ...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): ...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): ...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 *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"): ...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): ...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# 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