I have a CLI binary that I would like to control through Python. How could this easily be done?
I have tried making a terminal in a subprocess and opening it that way but that didn't work. I also thought about using keyboard emulation but that would be unreliable imo.
More specifically, I want to use Stockfish's CLI through Python.
The "I have tried making a terminal in a subprocess[...]" part refers to me trying to do that but being too unknowledgeable to actually achieve something.
minimal reproducible example:
import subprocess
My_Cmmnd = "cd"
process = subprocess.Popen(
"powershell -e 'bash -c \"" + My_Cmmnd + ";bash\"'",
stdout=subprocess.PIPE,
stderr=None,
shell=True,
)
As you can probably tell, this doesn't work.
I've also tried:
import os
os.system("cd path/to/stockfish")
os.system("cd")
This returns C:\path\to\project and not C:\path\to\stockfish as I would've expected.
I am open to any method, and am not saying I have to do this this specific way.
It was proposed that this may be similar to my question. In essence it is, but
its outdated
has no verified solution
when i try to use cd, it cannot change directory as it cannot find it for some reason
import subprocess
command = subprocess.Popen(['cd C:\\path\\to\\stockfish'], shell=True)
output: The filename, directory name, or volume label syntax is incorrect.
I pasted it into cmd and it worked just fine.
It was pointed out to me that there seems to be no cli, and i only use cd in the example. That is true in, the example i only use cd, but thats just for an example, if cd works and it correctly changes the directory than the whole thing works as i can then launch the cli and send commands to it.
cd C:\\path\\to\\stockfish? Does this answer your question? How do I change the working directory in Python? TL;DRos.chdir("path/to/stockfish"). The title mentions a CLI but it looks like you only want to change the current working directory.bashon the Linux executable? This would remove one layer of complexity and allow you to debug it more easilycdand a program.cdis a shell built-in command. You don't start it withsubprocess.Popen. You change the current working directory withos.chdirorcontextlib.chdir. It makes no sense to usecdas an example for a Stockfish CLI. Why do you think, you need to change the current working directory?.exewith/full/path/stockfish/program.exe? And if you need to change folder then you have to do all in one process - for exampleos.system("cd path/to/stockfish ; program.exe")