How to use stdin when stdin is redirected?

60 Views Asked by At

I am trying to make a CLI interface for lichess using lichess-bot

link: https://github.com/ShailChoksi/lichess-bot

Moves are made by making a class that extends MinimalEngine and giving it a search method which returns a move to make.

For example this works and I tested it on lichess, it makes a random legal move.

class RandomMove(ExampleEngine):
    def search(self, board, *args):
        return PlayResult(random.choice(list(board.legal_moves)), None)

My plan was to replace this functionality using input() to get a uci move string from the player and then have the bot play that move.

However this alone breaks it

class RandomMove(ExampleEngine):
    def search(self, board, *args):
        mv = input("Give me a move")
        return PlayResult(random.choice(list(board.legal_moves)), None)

I get this output repeated, when I run with input() in my code:

 INFO     Backing off play_game(...) for 19.9s (EOFError: EOF when reading a line) 

If I print(sys.stdin) from inside the search method I get this output:

<_io.TextIOWrapper name=21 mode='r' encoding='UTF-8'>

However if I print(sys.stdin) from my own python file I get:

stdin <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>

I guess that lichess-bot must somehow overwrite/redirect stdin, my question is how can I still read user input if this is the case, is there some trick to maybe reestablishing stdin and then setting it back when I am done or maybe something with running my input() on a separate thread/process ?

1

There are 1 best solutions below

0
On

Try this :

class RandomMove(ExampleEngine):
    def search(self, board, *args):
        mv = input("Give me a move")
        return PlayResult(chess.Move.from_uci(mv), None)

Actually your function has to return a PlayResult(chess.Move) type.