Smartcard library for Python providing PC/SC interface for smart card communication
—
High-level smart card communication interface that provides simple session management and APDU transmission without requiring detailed knowledge of PC/SC or card connection management.
The Session class provides the simplest way to communicate with smart cards. It automatically handles reader selection, card connection, and provides methods for APDU transmission and ATR retrieval.
class Session:
def __init__(self, readerName=None):
"""
Initialize a smart card session and connect to the card.
Args:
readerName (str, optional): Name of the reader to connect to.
If None, uses the first available reader.
Raises:
NoReadersException: No smart card readers available
InvalidReaderException: Specified reader not found or invalid
"""
def close(self):
"""
Close the smartcard session and disconnect from the card.
"""
def sendCommandAPDU(self, command):
"""
Send an APDU command to the connected smart card.
Args:
command (list[int]): APDU command as list of bytes,
e.g. [0xA0, 0xA4, 0x00, 0x00, 0x02]
Returns:
tuple[list[int], int, int]: A tuple (response, sw1, sw2) where:
- response: APDU response data as list of integers
Note: If response length > 2, sw1 and sw2 are appended to response
- sw1: First status word (0x00-0xFF)
- sw2: Second status word (0x00-0xFF)
"""
def getATR(self):
"""
Get the Answer To Reset (ATR) of the connected card.
Returns:
list[int]: ATR bytes as list of integers
"""
def __repr__(self):
"""
String representation of the session.
Returns:
str: Session description including reader name
"""Simple function for getting reader names as strings. This is maintained for backward compatibility.
def listReaders():
"""
Get list of smart card reader names.
Returns:
list[str]: List of reader names as strings
Note:
Deprecated - Use smartcard.System.readers() instead for Reader objects.
"""from smartcard import Session
# Connect to first available reader
session = Session()
# Send a command (e.g., GET RESPONSE)
GET_RESPONSE = [0x00, 0xC0, 0x00, 0x00, 0x20]
response, sw1, sw2 = session.sendCommandAPDU(GET_RESPONSE)
print(f"Response data: {response}")
print(f"Status: {sw1:02X} {sw2:02X}")
# Get card ATR
atr = session.getATR()
print(f"ATR: {' '.join(f'{b:02X}' for b in atr)}")
# Clean up
session.close()from smartcard import Session, listReaders
# List available readers
readers = listReaders()
print("Available readers:")
for i, reader in enumerate(readers):
print(f"{i}: {reader}")
# Connect to specific reader
if readers:
session = Session(readers[0])
# Your card operations here
atr = session.getATR()
print(f"Connected to {readers[0]}")
session.close()from smartcard import Session
from smartcard.Exceptions import NoReadersException, InvalidReaderException
try:
session = Session("Specific Reader Name")
# Send command
command = [0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x04, 0x10, 0x10]
response, sw1, sw2 = session.sendCommandAPDU(command)
# Check status words
if sw1 == 0x90 and sw2 == 0x00:
print("Command successful")
else:
print(f"Command failed: {sw1:02X} {sw2:02X}")
except NoReadersException:
print("No smart card readers found")
except InvalidReaderException as e:
print(f"Invalid reader: {e}")
finally:
if 'session' in locals():
session.close()from smartcard import Session
# Manual session management (no context manager support)
try:
session = Session()
atr = session.getATR()
print(f"ATR: {' '.join(f'{b:02X}' for b in atr)}")
# Send commands...
response, sw1, sw2 = session.sendCommandAPDU([0x00, 0xCA, 0x9F, 0x7F, 0x00])
# Must manually close session
session.close()
except Exception as e:
print(f"Session error: {e}")
if 'session' in locals():
session.close()# Exception types that may be raised
class NoReadersException(SmartcardException):
"""Raised when no smart card readers are available."""
class InvalidReaderException(SmartcardException):
"""Raised when specified reader is invalid or not found."""
# Type aliases for documentation
ReaderName = str
APDUCommand = list[int]
APDUResponse = list[int]
ATRBytes = list[int]
StatusWord = intInstall with Tessl CLI
npx tessl i tessl/pypi-pyscard