Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stockfish and Python

Tags:

python

chess

I'm trying to write a script using python to feed chess positions into stockfish and get evaluations.

My question is based on this, How to Communicate with a Chess engine in Python?

The issue is with subprocess.pipe.

import subprocess, time
import os

os.chdir('C:\Users\Michael\Downloads\stockfish-6-win\stockfish-6-win\Windows'


engine = subprocess.Popen('stockfish', universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

def put(command):
    print('\nyou:\n\t'+command)
    engine.stdin.write(command+'\n')

def get():
    # using the 'isready' command (eng has to answer 'readyok')
    # to indicate current last line of stdout
    engine.stdin.write('isready\n')
    print('\nengine:')
    while True:
        text = engine.stdout.readline().strip()
        if text == 'readyok':
            break
        if text !='':
            print('\t'+text)

put('go depth 15') 
get()
put('eval')
get() 
put('position fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') 
get()

I'm getting an invalid syntax error on the comma after stdin=subprocess.PIPE

Any help fixing that or trying another method is appreciated.

like image 321
Michael Gmeiner Avatar asked Feb 03 '26 19:02

Michael Gmeiner


1 Answers

The line

os.chdir('C:\Users\Michael\Downloads\stockfish-6-win\stockfish-6-win\Windows'

is missing a closing parenthesis. You probably wanted

stockfish_cmd = 'C:\\Users\\Michael\\Downloads\\stockfish-6-win\\stockfish-6-win\\Windows\\stockfish'
engine = subprocess.Popen(
    stockfish_cmd, universal_newlines=True,
    stdin=subprocess.PIPE, stdout=subprocess.PIPE)

Note the doubling of backslashes as well, although I believe it just happens to be harmless in this case.

like image 63
phihag Avatar answered Feb 05 '26 07:02

phihag