Search code examples
pythonmultithreadingoperating-systemsubprocesschess

How to run a '.exe' File in parallel to your python script (Asynchrously)


I am working on a chess engine in which the engine I am using is stored in .exe file and the gui is made in python (pygame) and I want to access the engine (.exe file) through python for which I am using subprocess library.

The problem I am facing is that the chess engine needs to work continuosly without closing, the format is:

  • input : e4
  • output : e5

something like this, so based on user's input, I need to send the input to the engine and then capture the output to make the move. I want my python script to run in parallel with the engine file while communicating with the engine back and fro, without closing the engine.

import subprocess
p1 = subprocess.run('scid_windows_5.0.2\scid_windows_x64\engines\phalanx-scid.exe',shell=True,capture_output=True)
print(p1.stdout.decode())

Here, the output is only shown after the .exe file ends (ctrl + Z) and also i am unable to give input to the engine. Please provide me a secure way of communicating with the engine while keeping the python script running.


Solution

  • import subprocess
    
    # Create a process without blocking, redirect stdin and stdout into pipes
    p = subprocess.Popen(["engine.exe"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    
    #Send data to the process
    p.stdin.write("e2\n".encode())
    p.stdin.flush()
    #Receive one line of data from the process (will block, if there is no input!)
    answer = p.stdout.readline().decode()