Answers.Body: <p>I think you're talking about how to fork a process for the engine and how to use it for the UCI protocol.</p>
  
  <p>What you need to do is:</p>
  
  <ol>
  <li>Fork a new child process for the Stockfish engine</li>
  <li>Send and receive UCI commands to/from the engine</li>
  <li>Parse the UCI commands yourself</li>
  </ol>
  
  <p>Do you want to study existing source code? Look at:</p>
  
  <p><a href="http://talkchess.com/forum/viewtopic.php?t=57770" rel="nofollow">http://talkchess.com/forum/viewtopic.php?t=57770</a></p>
  
  <p>Download <strong>Chess Game Analyzer</strong>, it's a simple Python script for automatic annotation.</p>
  
  <p>When you have the source code, look at the the following:</p>
  
  <pre><code> p = subprocess.Popen(engineName, stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)
  </code></pre>
  
  <p>This line creates a new process for the engine, where <code>engineName</code> is the path of the engine executive.</p>
  
  <pre><code>p.stdin.write("uci\n")
  </code></pre>
  
  <p>This line sends the <code>uci</code> command to the engine.</p>
  
  <pre><code>for eline in iter(p.stdout.readline, '')
  </code></pre>
  
  <p>This line parses a UCI response.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-10-23T05:22:06.287Z
Answers.Text: How do you view the source code? It looks like you can only get the .rar from that download link. Is there a git repository somewhere for viewing the source code?
Answers.UserDisplayName: Dan
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-10-23T05:23:35.057Z
Answers.Text: @Dan Download the archive and extract it. You'll find a Python script file. It's not on Github.
Answers.UserDisplayName: SmallChess
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-10-23T04:46:16.903Z
Answers.LastActivityDate: 2016-10-23T04:46:16.903Z
Answers.UserDisplayName: SmallChess
Answers.Body: <p>As for the first part, I have been using Perl and the IPC::Open2 package successfully for running Stockfish programmatically. <a href="http://perldoc.perl.org/IPC/Open2.html" rel="nofollow">http://perldoc.perl.org/IPC/Open2.html</a> </p>
  
  <p>As for the UCI way to "get all possible moves", you need to set the "multiPV" parameter to some large value (99?), causing the engine to calculate and report a value for every possible move.</p>
  
  <p>As for making the engine calculate (and report), you use the "go" command.</p>
  
  <p>Try it first interactively from the console to get an idea of what the output looks like, so you can intelligently parse it with your program.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-10-24T14:03:54.373Z
Answers.LastActivityDate: 2016-10-24T14:03:54.373Z
Answers.UserDisplayName: Jeff Y
Answers.Body: <blockquote>
    <p>Can anyone supply some code snippets for these instructions? I'm really struggling to find any helpful documentation.</p>
  </blockquote>
  
  <p>Since you say you need to manipulate chess data structures programmatically, you might find the kind of specific programming guidance you want at the <a href="https://www.chessprogramming.org" rel="nofollow noreferrer"><strong><em>Chess Programming Wiki</em></strong></a>.</p>
  
  <p>It links to the <a href="https://en.wikipedia.org/wiki/Universal_Chess_Interface" rel="nofollow noreferrer"><strong><em>Universal Chess Interface standard</em></strong></a>, which Stockfish uses to interface to the chess GUI or other program you're using/writing.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2016-10-23T03:52:42.660Z
Answers.LastActivityDate: 2018-11-30T23:53:13.153Z
Answers.LastEditDate: 2018-11-30T23:53:13.153Z
Answers.UserDisplayName: jaxter
Answers.Body: <p>The easiest way is to use the <a href="https://python-chess.readthedocs.io/" rel="nofollow noreferrer">python-chess</a> library.</p>
  <p>First, download Stockfish from <a href="https://stockfishchess.org/download/" rel="nofollow noreferrer">here</a> and unzip it.</p>
  <p>Second, install the library with <code>pip install chess</code></p>
  <p>Then follow the example of the <a href="https://python-chess.readthedocs.io/en/latest/engine.html" rel="nofollow noreferrer">engine communication</a> page:</p>
  <pre><code>import chess
  import chess.engine
  
  engine = chess.engine.SimpleEngine.popen_uci(r&quot;C:\Users\xxxxx\Downloads\stockfish_14_win_x64\stockfish_14_win_x64_avx2.exe&quot;)
  
  board = chess.Board()
  while not board.is_game_over():
      result = engine.play(board, chess.engine.Limit(time=0.1))
      board.push(result.move)
  
  engine.quit()
  </code></pre>
  <p><a href="https://python-chess.readthedocs.io/en/latest/engine.html#analysing-and-evaluating-a-position" rel="nofollow noreferrer">engine.analyze()</a> will give you more information.</p>
  <pre><code>import chess
  import chess.engine
  
  engine = chess.engine.SimpleEngine.popen_uci(&quot;/usr/bin/stockfish&quot;)
  
  board = chess.Board()
  info = engine.analyse(board, chess.engine.Limit(time=0.1))
  print(&quot;Score:&quot;, info[&quot;score&quot;])
  # Score: PovScore(Cp(+20), WHITE)
  
  board = chess.Board(&quot;r1bqkbnr/p1pp1ppp/1pn5/4p3/2B1P3/5Q2/PPPP1PPP/RNB1K1NR w KQkq - 2 4&quot;)
  info = engine.analyse(board, chess.engine.Limit(depth=20))
  print(&quot;Score:&quot;, info[&quot;score&quot;])
  # Score: PovScore(Mate(+1), WHITE)
  
  engine.quit()
  </code></pre>
  <p>The <a href="https://python-chess.readthedocs.io/en/latest/core.html#chess.Board" rel="nofollow noreferrer">Board class constructor</a> accepts a fen= parameter to set a custom FEN.</p>
  <p>Use <a href="https://python-chess.readthedocs.io/en/latest/core.html#chess.Board.legal_moves" rel="nofollow noreferrer">board.legal_moves</a> to get a list of all legal moves from the current position.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-11-11T13:14:30.130Z
Answers.LastActivityDate: 2022-11-11T13:14:30.130Z
Answers.UserDisplayName: 2080
Answers.Body: <p>As of June 24, 2021 when I am drafting this answer, I can guarantee to anyone that the above accepted answer is no longer true. The above provided &quot;.zip&quot; file no longer works. Hence, I seek and I found.</p>
  <p>The optimal way is <a href="https://pypi.org/project/stockfish/" rel="nofollow noreferrer">here</a>. It is fully programmable, even your grandma can do it.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-06-24T08:25:05.857Z
Answers.LastActivityDate: 2022-11-11T16:32:29.190Z
Answers.LastEditDate: 2022-11-11T16:32:29.190Z
Answers.UserDisplayName: daparic
Body: <p>I have Stockfish compiled on my machine. Instead of just running the Stockfish program in the terminal, is it possible to interact with it in a separate program?</p>
  
  <p>For example, some basic things I might want to do:</p>
  
  <ul>
  <li>Create a position object from a FEN.    </li>
  <li>Get an evaluation from the position object (limiting with depth or time).    </li>
  <li>Return an array of positions for all the legal moves from the position.</li>
  </ul>
  
  <p>These are just some very basic examples. Can anyone supply some code snippets for these instructions? I'm really struggling to find any helpful documentation.</p>
  
  <p><em>EDIT</em>: It looks like this really has a two part solution. The first is piping the input/output to some external program. The second is understanding the UCI protocol to perform what I want to do. Does anyone know the UCI protocol for getting all of the possible moves/positions from a given position? Also, it looks like the 'eval' command only gives a static evaluation of a position (i.e. no consideration of the future). Is there anyway to retrieve a time/depth based evaluation as well?</p>
  
Tags: <engines><stockfish><programming>
Title: What is the optimal way to use Stockfish programmatically?
ThreadText: # What is the optimal way to use Stockfish programmatically?
  
  (Asked by: username_0 on 2016-10-22)
  
  I have Stockfish compiled on my machine. Instead of just running the Stockfish program in the terminal, is it possible to interact with it in a separate program?
  
  For example, some basic things I might want to do:
  
  * Create a position object from a FEN.
  * Get an evaluation from the position object (limiting with depth or time).
  * Return an array of positions for all the legal moves from the position.
  
  These are just some very basic examples. Can anyone supply some code snippets for these instructions? I'm really struggling to find any helpful documentation.
  
  *EDIT*: It looks like this really has a two part solution. The first is piping the input/output to some external program. The second is understanding the UCI protocol to perform what I want to do. Does anyone know the UCI protocol for getting all of the possible moves/positions from a given position? Also, it looks like the 'eval' command only gives a static evaluation of a position (i.e. no consideration of the future). Is there anyway to retrieve a time/depth based evaluation as well?
  
  **Tags:** engines, stockfish, programming
  
  
  ---
  
  ## 5 answers
  
  ### Answer by username_1 on 2016-10-23. Score: 1 | Accepted answer
  
  I think you're talking about how to fork a process for the engine and how to use it for the UCI protocol.
  What you need to do is:
  
  Fork a new child process for the Stockfish engine
  Send and receive UCI commands to/from the engine
  Parse the UCI commands yourself
  
  Do you want to study existing source code? Look at:
  http://talkchess.com/forum/viewtopic.php?t=57770
  Download Chess Game Analyzer, it's a simple Python script for automatic annotation.
  When you have the source code, look at the the following:
   p = subprocess.Popen(engineName, stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)
  
  This line creates a new process for the engine, where engineName is the path of the engine executive.
  p.stdin.write("uci\n")
  
  This line sends the uci command to the engine.
  for eline in iter(p.stdout.readline, '')
  
  This line parses a UCI response.
  
  > **Comments:**
  > **username_0**: How do you view the source code? It looks like you can only get the .rar from that download link. Is there a git repository somewhere for viewing the source code?  
  > **username_1**: @username_0 Download the archive and extract it. You'll find a Python script file. It's not on Github.  
  
  ---
  
  ### Answer by username_2 on 2016-10-24. Score: 1
  
  As for the first part, I have been using Perl and the IPC::Open2 package successfully for running Stockfish programmatically. <http://perldoc.perl.org/IPC/Open2.html>
  
  As for the UCI way to "get all possible moves", you need to set the "multiPV" parameter to some large value (99?), causing the engine to calculate and report a value for every possible move.
  
  As for making the engine calculate (and report), you use the "go" command.
  
  Try it first interactively from the console to get an idea of what the output looks like, so you can intelligently parse it with your program.
  
  
  ---
  
  ### Answer by username_3 on 2016-10-23. Score: 1
  
  > Can anyone supply some code snippets for these instructions? I'm really struggling to find any helpful documentation.
  
  Since you say you need to manipulate chess data structures programmatically, you might find the kind of specific programming guidance you want at the [***Chess Programming Wiki***](https://www.chessprogramming.org).
  
  It links to the [***Universal Chess Interface standard***](https://en.wikipedia.org/wiki/Universal_Chess_Interface), which Stockfish uses to interface to the chess GUI or other program you're using/writing.
  
  
  ---
  
  ### Answer by username_4 on 2022-11-11. Score: 0
  
  The easiest way is to use the python-chess library.
  First, download Stockfish from here and unzip it.
  Second, install the library with pip install chess
  Then follow the example of the engine communication page:
  import chess
  import chess.engine
  
  engine = chess.engine.SimpleEngine.popen_uci(r"C:\Users\xxxxx\Downloads\stockfish_14_win_x64\stockfish_14_win_x64_avx2.exe")
  
  board = chess.Board()
  while not board.is_game_over():
      result = engine.play(board, chess.engine.Limit(time=0.1))
      board.push(result.move)
  
  engine.quit()
  
  engine.analyze() will give you more information.
  import chess
  import chess.engine
  
  engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish")
  
  board = chess.Board()
  info = engine.analyse(board, chess.engine.Limit(time=0.1))
  print("Score:", info["score"])
  # Score: PovScore(Cp(+20), WHITE)
  
  board = chess.Board("r1bqkbnr/p1pp1ppp/1pn5/4p3/2B1P3/5Q2/PPPP1PPP/RNB1K1NR w KQkq - 2 4")
  info = engine.analyse(board, chess.engine.Limit(depth=20))
  print("Score:", info["score"])
  # Score: PovScore(Mate(+1), WHITE)
  
  engine.quit()
  
  The Board class constructor accepts a fen= parameter to set a custom FEN.
  Use board.legal_moves to get a list of all legal moves from the current position.
  
  
  ---
  
  ### Answer by username_5 on 2021-06-24. Score: 0
  
  As of June 24, 2021 when I am drafting this answer, I can guarantee to anyone that the above accepted answer is no longer true. The above provided ".zip" file no longer works. Hence, I seek and I found.
  
  The optimal way is [here](https://pypi.org/project/stockfish/). It is fully programmable, even your grandma can do it.
  
  
  ---
  
  