DimaKudosh / pydfs-lineup-optimizer

Daily Fantasy Sports lineup optimzer for all popular daily fantasy sports sites
MIT License
424 stars 157 forks source link

Using print() with CSVLineupExporter causes empty csv file #109

Closed brettdewoody closed 5 years ago

brettdewoody commented 5 years ago

I'd like to combine print() with CSVLineupExporter to view the generated lineups in the Python interpreter, and export the lineups to a .csv file.

When I combine both print() and

exporter = CSVLineupExporter(lineups)
exporter.export(file) 

into the same script, the exported file is always empty.

Here's a basic example:

# Import the Python DFS Library
from pydfs_lineup_optimizer import get_optimizer, Site, Sport, CSVLineupExporter

file = 'lineups.csv'

#  Create an optimiser for DK Captain Mode
optimizer = get_optimizer(Site.DRAFTKINGS_CAPTAIN_MODE, Sport.FOOTBALL)

#  Load the players from the DK Salaries file
optimizer.load_players_from_csv('DKSalaries.csv')

#   Generate 20 lineups from the optimiser, with some randomness
lineups = optimizer.optimize(n=20)

# Display the lineups
for lineup in lineups:
    print(lineup.players)

#   Export the lineups
exporter = CSVLineupExporter(lineups)
exporter.export(file) 
DimaKudosh commented 5 years ago

Optimize function is a generator, and you iterate over it in for loop after that it will be completed and empty for next iterations in export function. If you want both print lineup and export you should convert generator into list:lineups = list(optimizer.optimize(n=20)), in this case you will wait all lineups creation. If you want to print lineup on each step and don't want to wait all completion collect them to additional list:

lineups = []

# Display the lineups
for lineup in optimizer.optimize(n=20):
    lineups.append(lineup)
    print(lineup.players)

#   Export the lineups
exporter = CSVLineupExporter(lineups)
exporter.export(file) 
brettdewoody commented 5 years ago

Great, thank you. I'm currently learning Python so hopefully I don't need to ask about these things going forward.