Stockfish Python Wrapper
The `stockfish` library provides a Python wrapper for the powerful open-source Stockfish chess engine, enabling easy integration into Python applications. It allows users to control the engine, set board positions, get best moves, and retrieve evaluations. Currently at version 4.0.8, the library is actively maintained with frequent patch releases, typically releasing multiple updates within a month when new features or fixes are introduced.
Warnings
- breaking The `stockfish` Python package is a wrapper; it *does not* include the Stockfish chess engine executable itself. You must download and install the Stockfish engine binary separately for your operating system.
- gotcha Providing invalid input, such as an incorrectly formatted or illegal FEN position that causes the underlying Stockfish process to crash, will result in a `StockfishException` being raised by the wrapper.
- gotcha Tuning engine parameters like `Skill Level` or `Elo` to reduce Stockfish's playing strength can be inconsistent or ineffective across different Stockfish engine versions. Some users report that these parameters do not always work as expected.
- gotcha The `__del__()` method of the `Stockfish` class, which is intended to send a 'quit' command to the engine, is not guaranteed to be called by Python when the object goes out of scope.
Install
-
pip install stockfish
Imports
- Stockfish
from stockfish import Stockfish
Quickstart
import os
from stockfish import Stockfish
# IMPORTANT: Replace with the actual path to your Stockfish engine executable
# You can download the Stockfish engine from: https://stockfishchess.org/download/
STOCKFISH_PATH = os.environ.get('STOCKFISH_EXECUTABLE_PATH', '/usr/local/bin/stockfish')
try:
# Initialize Stockfish with the path to its executable
# It's recommended to adjust 'threads' and 'hash' for performance
stockfish = Stockfish(path=STOCKFISH_PATH, depth=15, parameters={'Threads': 2, 'Hash': 2048})
# Set a starting position (e.g., standard chess opening FEN)
initial_fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
stockfish.set_fen_position(initial_fen)
print(f"Current FEN: {stockfish.get_fen_position()}")
print(f"Board visual:\n{stockfish.get_board_visual()}")
# Get the best move
best_move = stockfish.get_best_move()
print(f"Best move: {best_move}")
# Make a move
stockfish.make_moves_from_current_position([best_move])
print(f"New FEN after move {best_move}: {stockfish.get_fen_position()}")
print(f"Board visual after move:\n{stockfish.get_board_visual()}")
# Get evaluation
evaluation = stockfish.get_evaluation()
print(f"Evaluation: {evaluation}")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure the Stockfish engine is installed and its path is correctly set.")
finally:
# Explicitly quit the Stockfish engine process if necessary (though __del__ usually handles it)
if 'stockfish' in locals() and stockfish:
stockfish.send_quit_command()