Pour le tp sur le pendu, je ne comprends pas pq ça ne me renvoie pas ce que je voudrais.
# -*-coding:utf-8 -*
import os
os.chdir("c:/users/****/downloads/python/jeudupendu")
import random
from donnees import *
def randomword():
random_word = random.choice(generator)
return random_word
def underscore():
for word_spaces in randomword():
final = word_spaces
return final #Censé renvoyer le mot choisit aléatoirement sur
#plusieurs lignes. Ca ne me renvoye que la dernière lettre.
print(underscore())
os.system("pause")
randomword() fonctionne. Il me prend bien un mot au hasard. Donc, pq la commande for x in randomword(): ne me donne pas le mot sur chaque ligne ? Au lieu de cela, j'ai juste la dernière lettre du mot.
Je comptais avoir une lettre sur chaque ligne, pour en créer une liste et ensuite remplacer celle-ci par uniquement des underscores. C'est une bonne idée ?
JeanMarc33 a écrit:
> randomword() fonctionne. Il me prend bien un mot au hasard. Donc, pq la commande for x in randomword(): ne me donne pas le mot sur chaque ligne ? Au lieu de cela, j'ai juste la dernière lettre du mot.
Alors quand tu itères sur le retour de randomword(), word_spaces prend bien successivement la valeur de chaque lettre.
À chaque tour de boucle, tu assignes final à word_spaces, final prend donc elle aussi la valeur de chaque lettre.
Mais à un instant t, une variable n'a qu'une et une seule valeur. Ta variable pointe donc sur la dernière lettre du mot à la fin de ta boucle, c'est tout à fait normal.
Si tu veux transformer le retour de randomword() en liste, tu peux simplement faire appel à list.
Comment puis-je modifier la syntaxe pour que ce code s'execute? (je travaille sur Python 2.7.6 shell sur Ubuntu)
File "<string>", line 1, in <module> NameError: name 'mpl' is not defined >>> a=input("choisir une année") choisir une année1995 >>> if a//4!=0 print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0 print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0: print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0:
SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0: print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0:\
SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0: ...print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a//4!=0 : ...print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> [DEBUG ON] >>> [DEBUG OFF] >>> a=input("choisir une année")\ if a//4!=0:\ ...print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>> a=input("choisir une année")\ if a%4!=0:\ ...print(a,"n'est pas bisextille") SyntaxError: invalid syntax >>>
>>>
>>> a = input("choisir une année ")
choisir une année 1961
>>> a = int(a)
>>> if a % 4 != 0:
print(a, "n'est pas bisextille")
1961 n'est pas bisextille
>>>
J'ai reçu un petit devoir à faire en spécialité ISN et il faut que je parvienne à mettre une moitié d'une image de (600x300 par exemple) découpée en deux par une diagonale en gris, ça fait plusieurs jours que je travaille sur le sujet.
Malheureusement je n'arrive pas à trouver une fonction qui ferait l'affaire pour faire cette diagonale, pourrait-on me donner des pistes pour réaliser mon devoir svp ? Je dois travailler sous Python et PIL
Merci.
- Edité par ArnoldTchiasso 13 novembre 2017 à 21:23:21
Bonjour, j'ai un problème avec ce générateur sur la co-routine. Le code est le suivant :
def mon_generateur3(a, b):
if a < b:
while a <= b:
var = (yield a)
if var != None:
a = var
else:
a +=1
else:
while b <= a:
yield a
a -=1
exemple = mon_generateur3(1, 15)
for i in exemple:
if i == 6:
exemple.send(10)
else:
print(i, end=", ")
print("")
j’obtiens :
1, 2, 3, 4, 5, 11, 12, 13, 14, 15,
ou est passé le 10 ???
si je "trace" je devrais avoir :
var = (yield 6)
if i == 6: exemple.send(10)
var = 10
if var != None: a = 10
while 10 <= 15: var = (yield 10)
else: print(10, end=", ")
Mais le 10 ne s'affiche pas !
Je ne pige pas !
- Edité par Triple Zero 15 novembre 2017 à 1:01:25
Les aller- retours entre la boucle for in et le générateur ne sont pas simples, et modifiés par le send ...
"tracé" cela donne ça :
else: a +=1 # a = 6
while a <= b: # a = 6
for i in exemple: # i = 6
if i == 6 # i = 6
while a <= b: var = (yield a) # a = 6
if var != None: a = var # a = 10
while a <= b: # a = 10
exemple.send(10) # i (i==6) = 6
while a <= b: var = (yield a) # a = 10
else: a +=1 # a = 11
while a <= b: # a = 11
for i in exemple: # i = 11
======> print(i) # 11
A propos existe-t-il un module de débugage avec un trace sur python ?
Merci Olygrim !
- Edité par Triple Zero 15 novembre 2017 à 13:41:22
A propos existe-t-il un module de débugage avec un trace sur python ?
Alors là j'avoue que j'en sais absolument rien. Moi je me sers simplement des messages de l'interpréteur, et quand je ne comprends vraiment pas pourquoi je n'obtiens pas le bon résultat (quand le chemin est tortueux par exemple, comme ton post ou comme le mien avec la récurrence) et bien je demande à la communauté .
Mais peut-être existe-t-il un module un peu plus puissant pour le débugage.
J'ai un autre problème ... je n'arrive pas a avoir une console python3.6 interactive. Je suis sous linux Mint 18 64bits (issue de ubuntu 16.04)
Si je rentre sur une console shell
$ python3
Python 3.6.3 (default, Nov 4 2017, 00:53:12)
[GCC 5.4.0 20160609] on linux
...
et je n'ai que la touche "retour arrière" pour naviguer, par exemple la flèche gauche donne
^[[D
j'ai trouvé ipython qui, si j'ai bien compris, est l'équivalent avec des fonctions interactives. je l'ai installé avec
$ sudo apt-get install ipython3
si je lance j'ai
$ ipython3
Traceback (most recent call last):
File "/usr/bin/ipython3", line 4, in <module>
from IPython import start_ipython
ModuleNotFoundError: No module named 'IPython'
j'ai installé ipython
$ ipython
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
Type "copyright", "credits" or "license" for more information. ...
et
$ ipython3
Traceback (most recent call last):
File "/usr/bin/ipython3", line 4, in <module>
from IPython import start_ipython
ModuleNotFoundError: No module named 'IPython'
je ne trouve rien concernant IPython dans mes fichiers
j'ai d'installé sur mon système :
$ sudo aptitude search python | grep ^i
i dh-python - Debian helper tools for packaging Python l
i ipython - enhanced interactive Python shell
i ipython3 - enhanced interactive Python 3 shell
i libpeas-1.0-0-python2loader - Application plugin library
i A libpeas-1.0-0-python3loader - Application plugin library
i libpython-stdlib - interactive high-level object-oriented lan
i libpython2.7 - Shared Python runtime library (version 2.7
i libpython2.7-minimal - Minimal subset of the Python language (ver
i libpython2.7-stdlib - Interactive high-level object-oriented lan
i libpython3-stdlib - interactive high-level object-oriented lan
i libpython3.5 - Shared Python runtime library (version 3.5
i libpython3.5-minimal - Minimal subset of the Python language (ver
i libpython3.5-stdlib - Interactive high-level object-oriented lan
i python - interactive high-level object-oriented lan
i python-appindicator - Python bindings for libappindicator
i python-apt - Python interface to libapt-pkg
i python-apt-common - Python interface to libapt-pkg (locales)
i python-aptdaemon - Python 2 module for the server and client
i python-aptdaemon.gtk3widgets - Python 2 GTK+ 3 widgets to run an aptdaemo
i python-attr - Attributes without boilerplate (Python 2)
i python-beautifulsoup - error-tolerant HTML parser for Python
i python-blinker - Fast, simple object-to-object and broadcas
i python-cairo - Python bindings for the Cairo vector graph
i python-cffi-backend - Foreign Function Interface for Python call
i python-chardet - universal character encoding detector for
i python-configglue - Glues together optparse.OptionParser and C
i python-configobj - simple but powerful config file reader and
i python-crypto - cryptographic algorithms and protocols for
i python-cryptography - Python library exposing cryptographic reci
i python-cups - Python bindings for CUPS
i python-dbus - simple interprocess messaging system (Pyth
i python-dbus-dev - main loop integration development files fo
i python-debian - Python modules to work with Debian-related
i python-debtagshw - Match debtags hardware:: tags against the
i A python-decorator - simplify usage of Python decorators by pro
i python-defer - Small framework for asynchronous programmi
i python-dirspec - Python User Folders Specification Library
i python-ecdsa - ECDSA cryptographic signature library (Pyt
i python-enum34 - backport of Python 3.4's enum package
i python-feedparser - Universal Feed Parser for Python
i python-gconf - Python bindings for the GConf configuratio
i python-gi - Python 2.x bindings for gobject-introspect
i python-gi-cairo - Python Cairo bindings for the GObject libr
i python-glade2 - GTK+ bindings: Glade support
i python-gnomekeyring - Python bindings for the GNOME keyring libr
i python-gobject - Python 2.x bindings for GObject - transiti
i python-gobject-2 - deprecated static Python bindings for the
i python-gtk2 - Python bindings for the GTK+ widget set
i python-gtksourceview2 - Python bindings for the GtkSourceView widg
i python-httplib2 - comprehensive HTTP client library written
i python-idna - Python IDNA2008 (RFC 5891) handling (Pytho
i python-imaging - Python Imaging Library compatibility layer
i python-ipaddress - Backport of Python 3 ipaddress module (Pyt
i python-jwt - Python implementation of JSON Web Token
i python-ldb - Python bindings for LDB
i python-libxml2 - Python bindings for the GNOME XML library
i python-lockfile - file locking library for Python — Python 2
i python-lxml - pythonic binding for the libxml2 and libxs
i python-mako - fast and lightweight templating for the Py
i python-markupsafe - HTML/XHTML/XML string library for Python
i python-minimal - minimal subset of the Python language (def
i python-nemo - Python binding for Nemo components
i python-netifaces - portable network interface information - P
i python-notify - Python bindings for libnotify
i python-oauthlib - generic, spec-compliant implementation of
i python-oneconf - synchronize your configuration data over t
i python-openssl - Python 2 wrapper around the OpenSSL librar
i python-pam - Python interface to the PAM library
i python-paramiko - Make ssh v2 connections with Python (Pytho
i python-parted - Python interface for libparted
i python-pexpect - Python module for automating interactive a
i python-pil - Python Imaging Library (Pillow fork)
i python-pip - alternative Python package installer
i A python-pip-whl - alternative Python package installer
i python-piston-mini-client - library for writing clients for Django's P
i python-pkg-resources - Package Discovery and Resource Access usin
i python-protobuf - Python bindings for protocol buffers
i python-ptyprocess - Run a subprocess in a pseudo terminal from
i python-pyasn1 - ASN.1 library for Python (Python 2 module)
i python-pyasn1-modules - Collection of protocols modules written in
i python-pyatspi - Assistive Technology Service Provider Inte
i python-pyatspi2 - Transitional package for assistive technol
i python-pycurl - Python bindings to libcurl
i python-pyinotify - simple Linux inotify Python bindings
i python-pyorbit - A Python language binding for the ORBit2 C
i python-qt4 - Python bindings for Qt4
i python-qt4-dbus - D-Bus Support for PyQt4
i python-renderpm - python low level render interface
i python-reportlab - ReportLab library to create PDF documents
i python-reportlab-accel - C coded extension accelerator for the Repo
i python-samba - Python bindings for Samba
i python-serial - pyserial - module encapsulating access for
i python-service-identity - Service identity verification for pyOpenSS
i python-sexy - python language bindings for libsexy
i A python-simplegeneric - simple generic functions for Python
i python-sip - Python/C++ bindings generator runtime libr
i python-six - Python 2 and 3 compatibility library (Pyth
i python-smbc - Python 2 bindings for the Samba client lib
i python-talloc - hierarchical pool based memory allocator -
i python-tdb - Python bindings for TDB
i A python-tk - Tkinter - Writing Tk applications with Pyt
i python-twisted-bin - Event-based framework for internet applica
i python-twisted-core - Event-based framework for internet applica
i python-twisted-names - twisted package for DNS protocol implement
i python-twisted-web - twisted dummy package for HTTP protocol im
i python-ubuntu-sso-client - Ubuntu Single Sign-On client - Python libr
i A python-urlgrabber - A high-level cross-protocol url-grabber
i python-utidylib - Python wrapper for TidyLib
i python-vte - Python bindings for the VTE widget set
i python-webkit - WebKit/Gtk Python bindings
i python-xapian - Xapian search engine interface for Python
i python-xdg - Python 2 library to access freedesktop.org
i python-zope.interface - Interfaces for Python
i python2.7 - Interactive high-level object-oriented lan
i python2.7-minimal - Minimal subset of the Python language (ver
i python3 - interactive high-level object-oriented lan
i python3-apt - Python 3 interface to libapt-pkg
i python3-aptdaemon - Python 3 module for the server and client
i python3-aptdaemon.gtk3widgets - Python 3 GTK+ 3 widgets to run an aptdaemo
i python3-aptdaemon.pkcompat - PackageKit compatibilty for AptDaemon
i python3-blinker - fast, simple object-to-object and broadcas
i python3-brlapi - Braille display access via BRLTTY - Python
i A python3-bs4 - error-tolerant HTML parser for Python 3
i python3-cairo - Python 3 bindings for the Cairo vector gra
i python3-cffi-backend - Foreign Function Interface for Python 3 ca
i python3-chardet - universal character encoding detector for
i python3-commandnotfound - Python 3 bindings for command-not-found.
i python3-crypto - cryptographic algorithms and protocols for
i python3-cryptography - Python library exposing cryptographic reci
i python3-cups - Python3 bindings for CUPS
i python3-cupshelpers - Python modules for printer configuration w
i python3-dbus - simple interprocess messaging system (Pyth
i python3-debian - Python 3 modules to work with Debian-relat
i A python3-decorator - simplify usage of Python decorators by pro
i python3-defer - Small framework for asynchronous programmi
i python3-dialog - Python module for making simple terminal-b
i python3-dirspec - Python User Folders Specification Library
i python3-gdbm - GNU dbm database support for Python 3.x
i python3-gi - Python 3 bindings for gobject-introspectio
i python3-gi-cairo - Python 3 Cairo bindings for the GObject li
i python3-httplib2 - comprehensive HTTP client library written
i python3-icu - Python 3 extension wrapping the ICU C++ AP
i python3-idna - Python IDNA2008 (RFC 5891) handling (Pytho
i python3-jwt - Python 3 implementation of JSON Web Token
i python3-louis - Python bindings for liblouis
i python3-lxml - pythonic binding for the libxml2 and libxs
i A python3-markdown - text-to-HTML conversion library/tool (Pyth
i python3-minimal - minimal subset of the Python language (def
i python3-oauthlib - generic, spec-compliant implementation of
i python3-oneconf - synchronize your configuration data over t
i python3-pexpect - Python 3 module for automating interactive
i python3-pil - Python Imaging Library (Python3)
i python3-pip - alternative Python package installer - Pyt
i python3-piston-mini-client - library for writing clients for Django's P
i python3-pkg-resources - Package Discovery and Resource Access usin
i python3-ptyprocess - Run a subprocess in a pseudo terminal from
i python3-pyasn1 - ASN.1 library for Python (Python 3 module)
i python3-pyatspi - Assistive Technology Service Provider Inte
i python3-pycurl - Python bindings to libcurl (Python 3)
i python3-reportlab - ReportLab library to create PDF documents
i python3-reportlab-accel - C coded extension accelerator for the Repo
i python3-requests - elegant and simple HTTP library for Python
i A python3-simplegeneric - simple generic functions for Python3
i python3-six - Python 2 and 3 compatibility library (Pyth
i python3-speechd - Python interface to Speech Dispatcher
i python3-tk - Tkinter - Writing Tk applications with Pyt
i python3-uno - Python-UNO bridge
i python3-urllib3 - HTTP library with thread-safe connection p
i python3-virtkey - Library to emulate keyboard keypresses.
i python3-xapian1.3 - Xapian search engine interface for Python3
i python3-xdg - Python 3 library to access freedesktop.org
i python3-xkit - library for the manipulation of xorg.conf
i python3.5 - Interactive high-level object-oriented lan
i python3.5-minimal - Minimal subset of the Python language (ver
que faire pour avoir au moins les même fonctionalités sur la console python 3.6 et la console shell (historique, déplacements avec les flèches) ?
J'ai trouvé
il faut passer par pip3 :
sudo pip3 install IPython
# avec IP en maj
maintenant ça fonctionne.
- Edité par Triple Zero 23 novembre 2017 à 15:55:46
J'écris ici concernant le TP du pendu du cours de python d'openclassroom. J'ai bien lu les précédents cours, j'ai aussi très bien réalisé sans problème le TP ZCasino, mais je rencontre un blocage au niveau du pendu.
Je ne sais pas du tout comment faire ni par quoi commencer. Enfin, si, j'ai finis par déjà créer un dictionnaire pour les mots du pendu. Mais ensuite je bloque, je ne sais pas si je cherche à faire trop compliquer ou si je ne comprends pas du tout. Auriez-vous des conseils sans donner de réponse s'il vous plaît ? J'aimerais vraiment m'améliorer !
(En l'occurrence ce que je cherchais à faire en premier c'était la sélection du mot pour la partie, en parcourant le dictionnaire et en assignant "motpendu" à l'un des résultats, mais euh, j'y arrive vraiment pas ? est-ce parce-que c'est un mauvais départ ? Ou suis-je sur le bon chemin ?
Le seul dictionnaire est le score { nom-utilisateur: score ...}
J'ai écris le programme de façon différente du corrigé mais dans les deux cas les mots possibles et le mot tiré au sort sont dans des listes : il n'y a pas besoin de clés pour ces données. On converti le mot en liste, un élément de la liste par lettre
Et tu peux comparer par itération la lettre saisie et le mot tiré, dans une boucle jusqu’à ce que les mots construit et tiré soit == ou le nombre de coups (erreur de lettre) soit atteint.
J'espère t'en avoir assez dit sans en avoir trop dit ...
- Edité par Triple Zero 22 novembre 2017 à 23:41:19
Je suis le cours Python "Apprenez à programmer en Python", j'en suis à l'exercice "Créez votre jeu de Labyrinthe".
Je cherche à créer une class "Lab" qui hérite de la classe matrix. L'objectif est que cette classe, durant la création d'un matrice Lab :
- prenne en paramètres une chaine de caractère
- découpe le labyrinthe (sous forme d'une chaine)
- crée la matrice Lab formé par le labyrinthe
J'ai commencé par tester la prise en argument d'une chaine :
import numpy
class Lab(numpy.matrix):
#On déclare la création de la classe Lab
#un objet de type Lab va se comporter exactement comme un objet Matrix
#Par contre la fonction print renvoie une image différente
#Dans le but d'afficher correctemnt le labyrinthe
def __init__(self,chain)
liste=list(chain)
numpy.matrix(liste,str)
def __str__(self):
chain=""
compteur=0
for i in self[:,0]:
l=self[compteur,:].tolist()
chain+=''.join(l[0])+"\n"
l.clear()
compteur+=1
return chain
Quand j'essaye de créer un objet Lab, voilà ce qu'il se passe :
matrice=Lab("Bonjour")
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
matrice=Lab("Bonjour")
File "C:\Program Files\Python36\lib\site-packages\numpy\matrixlib\defmatrix.py", line 233, in __new__
data = _convert_from_string(data)
File "C:\Program Files\Python36\lib\site-packages\numpy\matrixlib\defmatrix.py", line 23, in _convert_from_string
newrow.extend(map(ast.literal_eval, temp))
File "C:\Program Files\Python36\lib\ast.py", line 85, in literal_eval
return _convert(node_or_string)
File "C:\Program Files\Python36\lib\ast.py", line 84, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x0000012C77ABC898>
J'ai beau cherché sur internet la raison de la levée de cette erreur mais je ne trouve pas.
Le seul dictionnaire est le score { nom-utilisateur: score ...}
J'ai écris le programme de façon différente du corrigé mais dans les deux cas les mots possibles et le mot tiré au sort sont dans des listes : il n'y a pas besoin de clés pour ces données. On converti le mot en liste, un élément de la liste par lettre
Et tu peux comparer par itération la lettre saisie et le mot tiré, dans une boucle jusqu’à ce que les mots construit et tiré soit == ou le nombre de coups (erreur de lettre) soit atteint.
J'espère t'en avoir assez dit sans en avoir trop dit ...
- Edité par Triple Zero il y a environ 15 heures
Merci beaucoup pour ces indications ! J'avais continué d'essayer de mon côté en attendant une réponse, et en effet j'ai finis par remplacer le dictionnaire des mots par une liste. Je vais tenté de continuer avec tes indications merci !
Je n'ai pas assez d'activite a corriger pour etre moi-meme corrige.... Je me demande si je dois faire l'Activite 4 si il y a personne a corriger ou pour corriger pour completer ce cours en entier??!!
Je n'ai pas assez d'activite a corriger pour etre moi-meme corrige.... Je me demande si je dois faire l'Activite 4 si il y a personne a corriger ou pour corriger pour completer ce cours en entier??!!
je ne comprends pas bien ce que tu veux dire, moi aussi j'attends d'être corrigé de l'exo labyrinthe mais je ne vois rien venir
Je n'ai pas assez d'activite a corriger pour etre moi-meme corrige.... Je me demande si je dois faire l'Activite 4 si il y a personne a corriger ou pour corriger pour completer ce cours en entier??!!
je ne comprends pas bien ce que tu veux dire, moi aussi j'attends d'être corrigé de l'exo labyrinthe mais je ne vois rien venir
Je viens de corriger trois personnes, maintenant ca me dit que dans 5 jours j'aurais mon activite corrige, on verra la semaine prochaine :-)
@leosum : eh bien j'aimerais pouvoir corrigé ta copie bientôt, étant aussi sur la 4.
J'ai déjà failli rendre copie blanche juste pour avoir la correction ;-)
Mais comme mon problème évolue en persistant un peu... Ces histoires de threads et de socket m'ont un peu mis le tournis.
je bloque pour l'instant sur la saisie du <C> de Commencer...
coté serveur :
import socket, sys, threading
class ThreadClient(threading.Thread):
def __init__(self, conn):
threading.Thread.__init__(self)
self.connexion = conn
def run(self):
nom = self.getName()
while True:
msgClient = self.connexion.recv(1024).decode("Utf8")
if not msgClient or msgClient.upper() == 'FIN':
break
message = "%s> %s" % (nom, msgClient)
print(message)
for cle in conn_client:
if cle != nom:
conn_client[cle].send(message.encode("Utf8"))
self.connexion.close()
del conn_client[nom]
print("Client %s deconnecte." % nom)
HOST = '127.0.0.1'
PORT = 50000
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mySocket.bind((HOST, PORT))
except socket.error:
print("La liason su socket à l'adresse choisie a echoué")
sys.exit()
print("serveur prêt, en attente de requêtes")
mySocket.listen(5)
conn_client = {}
while True:
connexion, adresse = mySocket.accept()
th = ThreadClient(connexion)
th.start()
it = th.getName() # identifiant du thread
conn_client[it] = connexion
print("Client %s connecté, adresse IP %s, port %s."% (it, adresse[0], adresse[1]))
msg = "Vous êtes connecté. Envoyez vos messages"
connexion.send(msg.encode("Utf8"))
ce qui coince apparement c'est l'enchainement des sequences d'envois et de reception des messages, lorsqu'il yen qu'un ca va, mais dès que j'en rajoute... c'est bizarre et pas fluide. par exemple le client reçoit bien le "over" qui lui "donne la parole", il envoit "C", le serveur n'affiche rien (au lieu de mettre "tel client est prêt"), par contre sur un Ctrl-C dans la console client, le serveur l'affiche enfin, à n'y rien comprendre.
Apparement il aime pas ces enchainements, mais je vais pas créer un thread pour chaque etape avant le tour par tour...
Si qqun a une piste ..
cote client :
class ThreadEmission(threading.Thread):
def __init__(self, connexion):
threading.Thread.__init__(self)
self.connexion = connexion
def run(self):
message_emis = input()
self.connexion.send(message_emis.encode("Utf8"))
class ThreadReception(threading.Thread):
def __init__(self, conn):
threading.Thread.__init__(self)
self.connexion = conn
def run(self):
while True:
message_recu = self.connexion.recv(1024).decode("utf8")
#print(message_recu)
if str(message_recu) == "over": # le client ne peut emettre que lorsque le serveur lui demande
print(message_recu)
te = ThreadEmission(self.connexion)
te.start()
if __name__ == "__main__":
host = '127.0.0.1'
port = 50001
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
connexion.connect((host,port))
except socket.error:
print("la connexion a echoue")
sys.exit()
print("connexion établie avec le serveur")
tr = ThreadReception(connexion)
tr.start()
Je viens de corriger trois personnes, maintenant ca me dit que dans 5 jours j'aurais mon activite corrige, on verra la semaine prochaine :-)
Pour le labyrinthe 1ère version
j'ai corrigé 6 (6 !) exercices ce we et j'ai eu ma note 5/7 il faut dire qu'il était parfaitement fonctionnel mais je n'avais pas fait d'effort sur la POO et le découpage en +ieurs fichiers ... ma note est méritée et la même pour les 3 correcteurs, donc cohérent tout ça !
Je vais le réécrire avec des classes pour pouvoir faire la 2ème version
python3.6 et tkinter sur ubuntu 16 / mint 18 et certainement debian 8
import tkinter donne une erreur : il manque __tkinter
tkinter module inclus dans python ... n'est pas vraiment inclus !!!
il faut installer Tcl/Tk et recompiler pithon3.6 avec les bonnes directives !!!
Télécharger sur www.activestate.com "Community Edition of ActiveTcl for Linux"
./configure --with-tcltk-includes='-I/opt/ActiveTcl-8.6/include' --with-tcltk-libs='/opt/ActiveTcl-8.6/lib/libtcl8.6.so /opt/ActiveTcl-8.6/lib/libtk8.6.so' # sur une seul ligne
make
sudo make install
et l'import de tkinter fonctionne.
A bon entendeur salut !
- Edité par Triple Zero 27 novembre 2017 à 14:31:32
Ben justement, cette page donne aussi la bonne manière d'installer Tkinter pour Python, c'est à dire à l'aide du gestionnaire de paquets.
Devoir recompiler Python pour installer un module complémentaire, tu devrais te dire qu'il y a quelque chose de sale dans la démarche.
Devoir recompiler Python pour installer un module complémentaire, tu devrais te dire qu'il y a quelque chose de sale dans la démarche.
c'est vrai, c'est ce que je pensais aussi !!! d’où l'émotîcone ...
dans mes essaies d'importer tkinter j'avais installé les paquets tk mais je n'avais pas du faire toute la bonne démarche à l'époque et cela n'avait rien donné ... il manquait toujours __tkinter et dans plusieurs forum il parlaient de recompiler python donc je l'ai fais
Je suis actuellement à la partie "Notre premier objet", et là le code de notre professeur ne fonctionne pas sur ma console (je suis sur linux). J'ai pourtant copié collé cette partie :
# -*-coding:utf-8 -*
chaine = str()
while chaine.lower() != "q":
print("Tapez 'Q' pour quitter...")
chaine = input()
print("Merci !")
Mais dès que "l'utilisateur" entre un mot pour quitter par exemple "s" à la place q, j'ai cette erreur : NameError: name 'q' is not defined
Pourquoi?
Merci d'avance pour votre aide...
- Edité par Dalila Hannouche 18 décembre 2017 à 16:04:30
Tu essayes de compiler Python 3 manuellement ?
Il ne faut pas faire ça, installe directement python3 à l'aide de ton gestionnaire de paquets (apt je suppose) : sudo apt-get install python3.
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique
We Make the NetWork -- @ngenibre
We Make the NetWork -- @ngenibre
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique
entwanne — @entwanne — Un zeste de Python — La POO en Python — Notions de Python avancées — Les secrets d'un code pythonique