Custom PGNs

The module lichess.pgn provides functions to generate custom PGNs from games in JSON format.

If you only need a default PGN, see the lichess.format module for an easier way to get it.

lichess.pgn.from_game(game, headers=None)

Converts a JSON game to a PGN string.

Game:The game object.
Headers:An optional dictionary with custom PGN headers.
>>> game = lichess.api.game('Qa7FJNk2', with_moves=1)
>>> pgn = lichess.pgn.from_game(game)
>>> print(pgn)
[Event "Casual rapid game"]
...
lichess.pgn.io_from_game(game, headers=None)

Like from_game, except it wraps the result in StringIO.

This allows easy integration with the python-chess library. But if this is all you need, see the lichess.format module for an easier way.

Game:The game object.
Headers:An optional dictionary with custom PGN headers.
>>> import lichess.api
>>> import lichess.pgn
>>> import chess.pgn
>>> 
>>> api_game = lichess.api.game('Qa7FJNk2', with_moves=1)
>>> game = chess.pgn.read_game(lichess.pgn.io_from_game(api_game))
>>> print(game.end().board())
. . k . R b r .
. p p r . N p .
p . . . . . . p
. . . . . . . .
. . . p . . . .
P . . P . . . P
. P P . . P P .
. . K R . . . .
lichess.pgn.from_games(games, headers=None)

Converts an enumerable of JSON games to a PGN string.

Games:The enumerable of game objects.
Headers:An optional dictionary with (shared) custom PGN headers.
>>> import itertools
>>> 
>>> games = lichess.api.user_games('cyanfish', with_moves=1)
>>> pgn = lichess.pgn.from_games(itertools.islice(games, 5))
>>> print(pgn.count('\n'))
66
lichess.pgn.save_games(games, path, headers=None)

Saves an enumerable of JSON games to a PGN file.

Games:The enumerable of game objects.
Path:The path of the .pgn file to save.
Headers:An optional dictionary with (shared) custom PGN headers.
>>> import itertools
>>> 
>>> games = lichess.api.user_games('cyanfish', with_moves=1)
>>> lichess.pgn.save_games(itertools.islice(games, 5), 'mylast5games.pgn')