Skip to content

Commit

Permalink
Migration vers Python 3
Browse files Browse the repository at this point in the history
  • Loading branch information
NicolasP committed Aug 22, 2019
1 parent a2d718e commit 1634ca7
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 62 deletions.
8 changes: 4 additions & 4 deletions README.md
Expand Up @@ -15,7 +15,7 @@ L'outil propos

## Prérequis

Il suffit de disposer d'un interpréteur Python. Les bibliothèques utilisées sont incluses dans la distribution standard Python 2.7 ou installées automatiquement au lancement du script. On suppose ici que l'interpréteur est situé dans /usr/bin/python.
Il suffit de disposer d'un interpréteur Python. Les bibliothèques utilisées sont incluses dans la distribution standard Python 3 ou installées automatiquement au lancement du script. On suppose ici que l'interpréteur est situé dans /usr/bin/python.

## Utilisation

Expand All @@ -29,15 +29,15 @@ Dans un terminal, taper :

### Sous Windows

Python 2.7 peut être téléchargé ici : https://www.python.org/ftp/python/2.7.11/python-2.7.11.msi
Python 3 peut être téléchargé ici : https://www.python.org/downloads/windows/

* lancer l'invite de commandes
* remonter dans le dossier C: grâce à la ligne de commande cd ".."
* aller dans le dossier d'installation python, par exemple
```
cd "Python27"
cd "Python37"
```
si Python est installé dans C://Python27)
si Python est installé dans C://Python37)
* entrer la ligne de commande
```
python.exe palmares.py
Expand Down
8 changes: 4 additions & 4 deletions README.txt
Expand Up @@ -15,7 +15,7 @@ L'outil propos

## Pr�requis

Il suffit de disposer d'un interpr�teur Python. Les biblioth�ques utilis�es sont incluses dans la distribution standard Python 2.7 ou install�es automatiquement au lancement du script. On suppose ici que l'interpr�teur est situ� dans /usr/bin/python.
Il suffit de disposer d'un interpr�teur Python. Les biblioth�ques utilis�es sont incluses dans la distribution standard Python 3 ou install�es automatiquement au lancement du script. On suppose ici que l'interpr�teur est situ� dans /usr/bin/python.

## Utilisation

Expand All @@ -27,13 +27,13 @@ Dans un terminal, taper :

### Sous Windows

Python 2.7 peut �tre t�l�charg� ici : https://www.python.org/ftp/python/2.7.11/python-2.7.11.msi
Python 3 peut �tre t�l�charg� ici : https://www.python.org/downloads/windows/

* lancer l'invite de commandes
* remonter dans le dossier C: gr�ce � la ligne de commande cd ".."
* aller dans le dossier d'installation python, par exemple
cd "Python27"
si Python est install� dans C://Python27)
cd "Python37"
si Python est install� dans C://Python37)
* entrer la ligne de commande
python.exe palmares.py
(apr�s avoir mis tous les fichiers .py dans ce m�me r�pertoire)
Expand Down
19 changes: 8 additions & 11 deletions classement.py
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


Expand All @@ -15,9 +15,6 @@
" - Joli formattage de sortie
"""


from __future__ import print_function, unicode_literals

import re

classementNumerique = { "S" : -1,
Expand Down Expand Up @@ -435,9 +432,9 @@ def plusGrosseVictoirePlusN( myVictoires, E ):
if grosse == "Top 60/Top 100" or grosse == "Top 40/Top 60":
return "Top 40/Top 60"
else:
for( k, v ) in classementNumerique.iteritems():
for k, v in classementNumerique.items():
if( k == grosse ):
for( k_, v_ ) in classementNumerique.iteritems():
for k_, v_ in classementNumerique.items():
if( v_ == v + E ):
return k_

Expand All @@ -448,7 +445,7 @@ def echelonInferieur( myClassement ):
if( v == 0 ):
return 0

for( k_, v_ ) in classementNumerique.iteritems():
for k_, v_ in classementNumerique.items():
if( v_ == v - 1 ):
return k_

Expand Down Expand Up @@ -647,7 +644,7 @@ def test():
fd_d = open( file_def, 'r' )
except:
import sys
print("Erreur ouverture", sys.exc_type, sys.exc_value)
print("Erreur ouverture", sys.exc_info()[0], sys.exc_info()[1])


try:
Expand Down Expand Up @@ -693,7 +690,7 @@ def test():
except:

import sys
print("Erreur lecture", sys.exc_type, sys.exc_value)
print("Erreur lecture", sys.exc_info()[0], sys.exc_info()[1])

fd_v.close()
fd_d.close()
Expand Down Expand Up @@ -759,7 +756,7 @@ def main():

if __name__ == "__main__":
import sys
if sys.version_info[0] != 2:
print("Erreur -- Fonctionne avec Python 2.x")
if sys.version_info[0] != 3:
print("Erreur -- Fonctionne avec Python 3.x")
exit( -1 )
main()
8 changes: 4 additions & 4 deletions interface.py
@@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/env python3

## http://alain72.developpez.com/tutos/wxPython/
## http://www.borer.name/files/eivd/wxpython/introduction_a_wxpython.pdf
Expand Down Expand Up @@ -116,7 +116,7 @@ def getValues( self ):
try:
numLicence = int( sLicence )
except:
print "probleme avec le numero de licence saisi ", self.tLicence.GetValue( )
print("probleme avec le numero de licence saisi ", self.tLicence.GetValue( ))
self.creerDial( "probleme avec le numero de licence saisi " + self.tLicence.GetValue( ) )
sProf = self.tProfondeur.GetValue( )
if '' == sProf :
Expand All @@ -126,13 +126,13 @@ def getValues( self ):
try:
profondeur = int( sProf )
except:
print "probleme avec la profondeur saisie ",
print("probleme avec la profondeur saisie ", end=' ')
return textLogin, textPassword, numLicence, profondeur

def OnRun( self, event ):
# Recuperer ce qui a ete saisi
textLogin, textPassword, numLicence, profondeur = self.getValues()
print textLogin, textPassword, numLicence, profondeur
print(textLogin, textPassword, numLicence, profondeur)

# Calcul du classement
palmares.recupClassement( textLogin, textPassword, numLicence, profondeur )
Expand Down
21 changes: 11 additions & 10 deletions interface2.py
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
#coding: utf8

""" Outil de recuperation du classement: interface graphique.
Expand All @@ -11,11 +11,15 @@
" Version très très très alpha.
"""


import sys

if sys.version_info[0] != 3:
print("Erreur -- Fonctionne avec Python 3.x")
exit(1)

import threading
import Tkinter as tk
import Queue
import tkinter as tk
import queue
import signal
import platform
import palmares
Expand Down Expand Up @@ -129,8 +133,8 @@ def stopThread():
def sighandler( signum, frame ):
print( "Caught signal" )
# sys.exit()
import thread
thread.exit()
import _thread
_thread.exit()
#raise ExitThreadNow

class ExitThreadNow( Exception ):
Expand Down Expand Up @@ -169,7 +173,7 @@ def write(self,string):
class ThreadSafeText( tk.Text ):
def __init__(self, master, **options):
tk.Text.__init__(self, master, **options)
self.queue = Queue.Queue()
self.queue = queue.Queue()
self.update_me()

def write(self, line):
Expand Down Expand Up @@ -273,9 +277,6 @@ def main():


if __name__ == "__main__" :
if sys.version_info[0] != 2:
exit_pause(1, "Erreur -- Fonctionne avec Python 2.x")

try:
main()
except KeyboardInterrupt:
Expand Down
48 changes: 23 additions & 25 deletions palmares.py
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

""" Outil de recuperation du classement.
Expand All @@ -14,22 +14,25 @@
" Meilleure gestion des erreurs
"""

import sys

from __future__ import print_function, unicode_literals
if sys.version_info[0] != 3:
print("Erreur -- Fonctionne avec Python 3.x")
exit(1)

import argparse
import urllib
import re
import HTMLParser
import html
import logging
import itertools
import time
import thread
import _thread
import json

from getpass import getpass
from threading import Thread
from Queue import Queue
from queue import Queue
from decimal import Decimal

from classement import calculClassement
Expand Down Expand Up @@ -98,7 +101,7 @@ def requete(session, url, data=None, timeout=20, retries=4):
except Timeout:
print("Timeout -- connexion impossible au serveur de la FFT")
except KeyboardInterrupt:
thread.interrupt_main()
_thread.interrupt_main()
except Exception as e:
print("Autre exception : {} - {}".format(type(e).__name__, e.message))

Expand Down Expand Up @@ -130,7 +133,7 @@ def getIdentifiant(session, numLicence):

page = "/recherche-licencies"
payload = { 'numeroLicence' : numLicence }
data = urllib.urlencode( payload )
data = urllib.parse.urlencode(payload)

rep = requete(session, server + page + '?' + data, retries=2)
if rep is None:
Expand Down Expand Up @@ -182,7 +185,7 @@ def getPalma(annee, joueur, joueurs, session):

page = "/simulation-classement/" + joueur.identifiant
payload = { 'millesime': annee }
data = urllib.urlencode( payload )
data = urllib.parse.urlencode(payload)
timeout = 8

logging.debug('getPalma ' + joueur.nom)
Expand Down Expand Up @@ -271,7 +274,7 @@ def traitement():
if q.unfinished_tasks:
print('{} palmarès n\'ont pas pu être récupérés'.format(q.unfinished_tasks))

joueurs_avec_palmares = len(set(j.identifiant for j in joueurs.itervalues() if j.victoires or j.defaites))
joueurs_avec_palmares = len(set(j.identifiant for j in joueurs.values() if j.victoires or j.defaites))
print('Palmarès récupérés pour {} joueurs'.format(joueurs_avec_palmares))
print()

Expand All @@ -296,7 +299,7 @@ def extractInfo(ligne, joueurs):
return None

# Il peut y avoir des caractères spéciaux à décoder dans le nom
nom = HTMLParser.HTMLParser().unescape(cell_matches[0]).strip() or '(anonyme)'
nom = html.unescape(cell_matches[0]).strip() or '(anonyme)'

# classement du joueur
clmt = cell_matches[1]
Expand Down Expand Up @@ -372,7 +375,7 @@ def classementJoueur(joueur, sexe, profondeur, details_profondeur):
:type joueur: Joueur
"""

if joueur.calcul_fait >= profondeur:
if joueur.calcul_fait and joueur.calcul_fait >= profondeur:
logging.debug("Calcul déjà fait pour {} en profondeur {} ou plus ({})".format(joueur.nom, profondeur, joueur.calcul_fait))
nc, harm = joueur.classement_calcul
return nc, harm, None
Expand Down Expand Up @@ -406,8 +409,7 @@ def classementJoueur(joueur, sexe, profondeur, details_profondeur):
impression = profondeur >= details_profondeur

if impression:
print("Calcul du classement de {} (profondeur {})".format(joueur.nom, profondeur)
.encode(sys.stdout.encoding, errors='replace'))
print("Calcul du classement de {} (profondeur {})".format(joueur.nom, profondeur))

# nb de victoires en championnat indiv
champ = nbVictoiresChamp(joueur.victoires)
Expand All @@ -420,7 +422,7 @@ def classementJoueur(joueur, sexe, profondeur, details_profondeur):
if impression:
# sorties
s = strClassement(joueur, cl, harm)
print(s.encode(sys.stdout.encoding, errors='replace'))
print(s)
else:
s = None

Expand Down Expand Up @@ -464,9 +466,9 @@ def recupClassement( login, password, LICENCE, profondeur, details_profondeur=0
print("Nouveau classement: ", harm, " (après harmonisation) - ", new_cl, " (calculé)")

# on crache la sortie du joueur dans un fichier
fn = str( LICENCE ) + "_" + str( nom ) + "_p" + str( profondeur ) + ".txt"
fn = "{}_{}_p{}.txt".format(LICENCE, nom, profondeur)
fd = open( fn, "w" )
fd.write( s.encode('utf-8') )
fd.write(s)
fd.close()

return
Expand Down Expand Up @@ -499,25 +501,24 @@ def main():
if args.verbeux:
logging.basicConfig(level=logging.DEBUG)

login = args.login if args.login else raw_input("Identifiant : ")
password = args.password if args.password else getpass(b"Mot de passe : ")
login = args.login if args.login else input("Identifiant : ")
password = args.password if args.password else getpass("Mot de passe : ")

licence = trimNumLicence(args.licence if args.licence else raw_input("Numero de licence : "))
licence = trimNumLicence(args.licence if args.licence else input("Numero de licence : "))
if licence is None:
print("Erreur de saisie du numéro de licence")
return -1

try:
profondeur = args.profondeur if args.profondeur is not None else int(raw_input("Profondeur : "))
profondeur = args.profondeur if args.profondeur is not None else int(input("Profondeur : "))
except:
print('Erreur de saisie de la profondeur')
return -1

if profondeur > 2 and not args.force:
print("Vous avez choisi une profondeur importante ({}).\n"
"Cela va générer un très grand nombre de requêtes au site de la FFT.\n"
"Êtes-vous sûr de vouloir continuer ?".format(profondeur)
.encode(sys.stdout.encoding, errors='replace'))
"Êtes-vous sûr de vouloir continuer ?".format(profondeur))
if not confirmation():
return -1

Expand All @@ -526,9 +527,6 @@ def main():


if __name__ == "__main__" :
if sys.version_info[0] != 2:
exit_pause(1, "Erreur -- Fonctionne avec Python 2.x")

check_dependencies()

try:
Expand Down
6 changes: 2 additions & 4 deletions util.py
@@ -1,7 +1,5 @@
# coding=utf-8

from __future__ import print_function, unicode_literals

import importlib
import os
import platform
Expand All @@ -12,7 +10,7 @@
def confirmation():
oui = {"oui", "o", ""}
non = {"non", "n"}
choix = raw_input("(oui/non) ").lower()
choix = input("(oui/non) ").lower()
if choix in oui:
return True
elif choix in non:
Expand All @@ -30,7 +28,7 @@ def exit_pause(status=0, error_message=""):
# Si le script a été lancé en dehors de cmd (en double-cliquant), on pause l'exécution
# pour laisser la possibilité de lire la sortie.
# La variable PROMPT n'est présente qu'avec cmd (https://stackoverflow.com/q/558776/119323)
raw_input("Appuyez sur une touche pour terminer")
input("Appuyez sur une touche pour terminer")

sys.exit(status)

Expand Down

0 comments on commit 1634ca7

Please sign in to comment.