Stockfish Python Wrapper

4.0.8 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `Stockfish` class, set a FEN position, retrieve the best move, make a move, and get the engine's evaluation. Remember to replace `STOCKFISH_EXECUTABLE_PATH` with the actual path to your downloaded Stockfish engine binary. It's recommended to manage the Stockfish executable's path via an environment variable for easier deployment.

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()

view raw JSON →