relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent
Hi Folks,

I was arguing with a guy who was sure that incrementing a variable i with "i += 
1" is faster than "i = i + 1". I couldn't tell if he was right or wrong so I 
did a little benchmark with the very useful timeit module.
Here are the results on my little Linux Eeepc Netbook (using Python 3.2):


Computing, please wait...

Results for 100 times "i = i + 1":
0.37591004371643066
0.3827171325683594
0.37238597869873047
0.37305116653442383
0.3725881576538086
0.37294602394104004
0.3712761402130127
0.37357497215270996
0.371567964553833
0.37359118461608887
Total 3.7396 seconds.

Results for 100 times "i += 1":
0.3821070194244385
0.3802030086517334
0.3828878402709961
0.3823058605194092
0.3801591396331787
0.38340115547180176
0.3795340061187744
0.38153910636901855
0.3835160732269287
0.381864070892334
Total 3.8175 seconds.

==> "i = i + 1" is 2.08% faster than "i += 1".



I did many tests and "i = i + 1" always seems to be around 2% faster than "i += 
1". This is no surprise as the += notation seems to be a syntaxic sugar layer 
that has to be converted to i = i + 1 anyway. Am I wrong in my interpretation?

Btw here's the trivial Python 3.2 script I made for this benchmark:


import timeit

r = 10
n = 100

s1 = "i = i + 1"
s2 = "i += 1"

t1 = timeit.Timer(stmt=s1, setup="i = 0")
t2 = timeit.Timer(stmt=s2, setup="i = 0")

print("Computing, please wait...")

results1 = t1.repeat(repeat=r, number=n)
results2 = t2.repeat(repeat=r, number=n)

print('\nResults for {} times "{}":'.format(n, s1))
sum1 = 0
for result in results1:
print(result)
sum1 += result
print("Total {:.5} seconds.".format(sum1))

print('\nResults for {} times "{}":'.format(n, s2))
sum2 = 0
for result in results2:
print(result)
sum2 += result
print("Total {:.5} seconds.".format(sum2))

print('\n==> "{}" is {:.3}% faster than "{}".'.format(s1,(sum2 / sum1) * 100 - 
100, s2))



Comments are welcome...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent
Well I agree with you about string concatenation, but here I'm talking about 
integers incrementation...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent
Thanks for these explanations. So 2% speed difference just between "B..." and 
"I..." entries in a huge alphabetically-ordered switch case? Wow. Maybe there 
is some material for speed enhancement here... 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent
Well 2% more time after 1 million iterations so you're right I won't consider 
it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent
Actually 6% between float themselves is just as not-understandable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent

> With 64 bit 3.2.2 on my Win 7 Pentium, the difference was 4% and with 
> floats (0.0 and 1.0), 6%

For floats it is understandable. But for integers, seriously, 4% is a lot. I 
would never have thought an interpreter would have differences like this in 
syntax for something as fundamental as adding 1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent
I did the test several times with floats on my machine and the difference is 
not as big as for integers:


==> "i = i + 1.0" is 0.732% faster than "i += 1.0".

It seems normal as the float addition is supposed to be slower than integer 
addition, thus the syntaxic difference is comparatively less important. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Best way to check that you are at the beginning (the end) of an iterable?

2011-09-07 Thread Laurent
Hi there,

What is the simplest way to check that you are at the beginning or at the end 
of an iterable? I'm using enumerate with Python 3.2 (see below) but I'm 
wondering if there would be a better way.


l = ['a', 'b', 'a', 'c']

for pos, i in enumerate(l):
if pos == 0:
print("head =", i)
else:
print(i)


I know that Python is not exactly a functional language but wouldn't something 
like "ishead()" or "istail()" be useful?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to check that you are at the beginning (the end) of an iterable?

2011-09-07 Thread Laurent
I totally understand the performance issue that an hypothetical "istail" would 
bring, even if I think it would just be the programmer's responsibility not to 
use it when it's not certain that an end can be detected. 
But I don't see why *adding* something like "ishead" would be so bad (at worse 
by using a boolean somewhere as you mentioned).

Anyway I was just asking if there is something better than enumerate. So the 
answer is no? The fact that I have to create a tuple with an incrementing 
integer for something as simple as checking that I'm at the head just sounds 
awfully unpythonic to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to check that you are at the beginning (the end) of an iterable?

2011-09-07 Thread Laurent
Yes of course the use of a boolean variable is obvious but I'm mixing python 
code with html using Mako templates. In Mako for code readability reasons I try 
to stick to simple "for" and "if" constructions, and I try to avoid variables 
declarations inside the html, that's all.  Thanks anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters

2011-05-30 Thread Laurent



 Could you give an example of an object that has no name ? I've missed
 something ...


def foo():
 return 5

print(foo())

The int object 5 has no name here.


Cool. I was thinking that "5" was the name, but
>>> 5.__add__(6)
  File "", line 1
5.__add__(6)
^
SyntaxError: invalid syntax

while

>>> a=5
>>> a.__add__(6)
11


Very well. I learned something today.
Thanks
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


How to manage event of COM objects...

2005-12-05 Thread Laurent
Hello,

I'm currently trying to use event from a win32 application using it's
COM interface.

To connect to the application I use:

class MyApp_InterfaceManager (Thread):
  ...
  def run (self):
# First we initialize the COM libraries for current thread
pythoncom.CoInitialize()
#Then we connect to the app with event handling...
self.app = DispatchWithEvents('MyApp',MyApp_AppEvents)

class MyApp_AppEvents:
  OnHalt:
print "halt event..."

>From here all is ok when the OnHalt event arrives the print is called.
The problem I have is that I need that MyApp_AppEvents class knows the
thread object to call a thread function when the event occurs(for
example I need to toggle a flag)

I've got no idea how to do that!
Anyone has encoutered the problem?
I've tryied to use getevents but with no result...
Help!

Best regards,

Laurent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python...

2005-12-05 Thread Laurent
Falc wrote:
> Hi there...
> 
> I have been looking at learning Python, so far it looks like an
> absolutely grat language. I am having trouble finding some free
> resources to learn Python from. I am on windows and the only experience
> I have with programming is with PHP.
> 
> I have been trying to look at the free online book "Dive Into Python"
> but this is far too difficult for me as it explains it in caparison
> with C++ or Java.
> I like the book called "A Byte Of Python"
> (http://www.byteofpython.info) but it's made for version 2.3 (Would
> this matter anyway?).
> So if you have any books you could reccomend me that would rock, I
> can't really afford a book so if online that would be excellent.
> 
> Thanks in Advance.
> 

I must recommend you "Learning Python" from O'reilly that is an
excellent book but not free...This is the only one I've read about python.
For byteofpython I haven't read it but if it covers python 2.3 sure it
is sufficient to learn python as 2.4 has just introduced some new
advanced features.

Also take a look at:
http://www.awaretek.com/tutorials.html
Good examples that will help you in your learning.

Dive into python must be read _after_ you've read and tryied a little
python :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is your favorite Python web framework?

2005-07-18 Thread laurent
hello,
I follow somes projects that have a pythonic way to make web site.
there's thats projects :
   http://www.cherrypy.org/
and
   http://subway.python-hosting.com/
subway aim to be like ruby on rails frameworks , simple and fast
developpment. It uses cherrypy and other project like :
 * http://www.cheetahtemplate.org/
 * http://www.formencode.org/
 * http://www.sqlobject.org/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find Python path in Visual C++ install wizard

2005-08-13 Thread laurent
Hello,
there's a pretty solution. if the user  hasn't got python or don't want
to install python. You can  make your application executable without a
complete installation of python.

for this, look at project like py2exe or freeze. These tools make an
executable of your pyc files and produce some files : python.zip (for
python higher 2.3) and python.dll and other dll for application that
needs some dynamic python's extension.

regards,
Laurent

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to check that you are at the beginning (the end) of an iterable?

2011-09-07 Thread Laurent
Yes, I was just hoping for something already included that I wouldn't know (i'm 
new to Python).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to check that you are at the beginning (the end) of an iterable?

2011-09-07 Thread Laurent
Interesting. I will check that yield functionality out. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to check that you are at the beginning (the end) of an iterable?

2011-09-07 Thread Laurent

> I don't think this question is meaningful. There are basically two
> fundamental types of iterables, sequences and iterators.
> 
> Sequences have random access and a length, so if the "start" and "end" of
> the sequence is important to you, just use indexing:
> 
> beginning = sequence[0]
> end = sequence[-1]
> for i, x in enumerate(sequence):
> if i == 0: print("at the beginning")
> elif i == len(sequence)-1: print("at the end")
> print(x)
> 
> 
> Iterators don't have random access, and in general they don't have a
> beginning or an end. There may not be any internal sequence to speak of:
> the iterator might be getting data from a hardware device that provides
> values continuously, or some other series of values without a well-defined
> beginning or end. 

Maybe I should have said "best way to check that you didn't start the iteration 
process yet" but you see what I mean.

Well I guess I have to unlearn my bad lisp/scheme habits...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running Python Demo on the Web?

2011-09-07 Thread Laurent
Neat. But I can see some "print(x)" and some "print x". What is the Python 
version?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using python in web applications

2011-09-10 Thread Laurent
[troll]
For a serious web based MMO you'd rather stick to low level and forget about 
bloated Object Relational Mapping java-like layered kind of frameworks that are 
made for Rapid Applications Development, not for efficiency.
[/troll]

"Eve Online", a well known MMORPG was developped with stackless python : 
http://highscalability.com/eve-online-architecture

You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb 
(pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working 
fine after some tuning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using python in web applications

2011-09-10 Thread Laurent
Well PyPy is just an implementation of Python among many others (but limited to 
version 2.7). It is not a web server. If you want to make PyPy interact with a 
web server (such as nginx) you have to use a special protocol such as WSGI or 
Fast-CGI. For best performances you can for instance use uWSGI that integrates 
well with nginx but for this you have to recompile nginx. As you see it's a bit 
complex, you should read the wikis. May the Force be with you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using python in web applications

2011-09-11 Thread Laurent
+1 for PostgreSQL. It's faster than MySQL for years now, and is much more 
seriously featured.
If you don't need ACID properties (transactions stuff) you should also give 
Document-based databases like MongoDB a try. It changed my code life.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 1/2 evaluates to 0

2011-10-12 Thread Laurent



Include from __future__ import division on the top of your file


 from __future__ import division
 1/2

0.5



Wohaw. This means that this behavior is going to be default in a 
foreseeable future ?


Thanks
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Entre local et global

2011-10-28 Thread Laurent

Le 28/10/2011 10:43, ll.snark a écrit :

On 27 oct, 17:06, Laurent Claessens  wrote:

 >  J'aimerais donc pouvoir indiquer dans fonca, que la variable lst est
 >  celle définie dans fonc1.
 >  Je ne veux pas d'une variable locale à fonca, ni une variable globale
 >  à tout mon fichier (cf exemple ci-dessous)

 >  Une idée ?

 Je ne suis pas très sûr que ça réponse à la question, mais une piste
 serait de faire de fonca une classe avec une méthode __call__ et une
 variable de classe:

 class fonc2(object):
   fonc1.lst=[]
   def __call__(self,v):
   if len(fonc1.lst)<3:
   fonc1.lst=fonc1.lst+[v]
   print fonc1.lst




Effectivement, ça répond en partie à la question.
Il faudra que je vois si en faisant comme ça, je peux résoudre mon pb
de départ sur les décorateurs. MAis je suppose qu'entre une fonction
et une classe qui possède une
méthode __call__, il n'y a pas tant de différence que ça...



Moi je dirais que oui, il y a une différence énorme : dans une classe tu 
peux mettre beaucoup plus de choses ;)


class Exemple(object):
def __init__(self,a):
self.a=a
def __call__(self,x):
return a+x

f=Exemple(2)
g=Exemple(10)

f(1) # 3
g(1) # 11
f.a=6
f(1) # 7

Faire ça avec une fonction, ça me semblerait ardu, sauf à faire comme tu 
faisais : une fonction qui contient une fonction et qui la retourne. 
(mais à mon avis c'est moins lisible)



Merci pour la réponse en tous cas. Je suppose donc qu'il n'y a pas de
mot clé, un peu comme global, mais qui
désigne une portée plus petite ?


Je ne sais pas.



Je l'aurais sans doute vu dans la doc
ou dans des bouquin si ça avait été le cas, mais je trouve
que c'est bizarre.


A priori, ça ne me semble pas tellement bizarre. J'utiliserais une 
fonction seulement pour quelque chose qui a une entrée et une sortie qui 
dépend uniquement de l'entrée.
Pour quelque chose dont le comportement dépend du contexte (c'est le cas 
de ce que tu demandes), j'utiliserais une classe dans les attributs de 
laquelle je mettrais les éléments du contexte.
Bon, je dis ça, mais je ne suis pas assez fort pour prétendre être 
certain de ce qui est "bizarre" ou non :)


Bonne journée
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


property decorator and inheritance

2011-11-10 Thread Laurent
Hi. I couldn't find a way to overwrite a property declared using a decorator in 
a parent class. I can only do this if I use the "classic" property() method 
along with a getter function. Here's an example:

#!/usr/bin/python3

class Polite:

def __init__(self):
self._greeting = "Hello"

def get_greeting(self, suffix=", my dear."):
return self._greeting + suffix
greeting1 = property(get_greeting)

@property
def greeting2(self, suffix=", my dear."):
return self._greeting + suffix


class Rude(Polite):

@property
def greeting1(self):
return self.get_greeting(suffix=", stupid.")

@property
def greeting2(self):
return super().greeting2(suffix=", stupid.")


p = Polite()
r = Rude()

print("p.greeting1 =", p.greeting1)
print("p.greeting2 =", p.greeting2)
print("r.greeting1 =", r.greeting1)
print("r.greeting2 =", r.greeting2) # TypeError: 'str' object is not callable



In this example I can easily overwrite the greeting1 property. But the 
inherited greeting2 doesn't seem to be a property but a mere string.

I use a lot of properties decorators for simple properties in a project and I 
hate mixing them with a couple of "undecorated" properties that have to be 
overwritten in child classes. I tried using @greeting2.getter decorator and 
tricks like this but inheritance overwriting failed every time I used 
decorators.
 Can someone tell me a way to use decorator-declared properties that can be 
overwritten in child classes?? That would be nice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property decorator and inheritance

2011-11-10 Thread Laurent
Yes using a separate class variable would transfer the problem to the class 
level. But adding 10 class variables if I have 10 properties would be ugly. 
Maybe I should reformulate the subject of this thread to "is there some python 
magic to pass parameters to decorator-declared properties ?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property decorator and inheritance

2011-11-11 Thread Laurent
Hey yes it's working that way. But I don't like it very much either. If as OKB 
said the whole point is that outside functions can't detect a property then I'm 
going to stick with the non-decorator way. Thanks anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem of types:

2006-01-14 Thread Laurent
I do not understand why he is talking me about 'str', no str given!!!

I have this:

-

def to_float(elt):
  if type(elt) is list:
return map(to_float, elt)
  else:
return float(elt)

def Denombrement(A,b,c,type):
  .
  .
  .
  A = to_float(A)
  b = to_float(b)
  c = to_float(c)
  .
  .
  .

if __name__ == '__main__':
  A = [[1,0],[0,1]]
  b = [2,2]
  c = [1,1]
  type = 'min'

  Denombrement(A, b, c, type)

---

And this error msg:
-
Traceback (most recent call last):
  File "./Denombrement.py", line 160, in ?
Denombrement(A, b, c, type)
  File "./Denombrement.py", line 31, in Denombrement
A = to_float(A)
  File "./Denombrement.py", line 10, in to_float
if type(elt) is list:
TypeError: 'str' object is not callable

--

Changing 'list' to 'type(list)' don't change anything

-- 
http://mail.python.org/mailman/listinfo/python-list


my openGL API need threads!!! But how to ,ake it work???

2006-02-02 Thread Laurent
Hi,

here is the context:

I'm coding a openGL API I will need for a project for my school.
This API is quite simple:

an ooglScene describe all needed to make an openGL, and inherits from a
list. So an ooglScene is fundamentaly a list of ooglObjects (which is
organised as a Composite Pattern).

ooglScene.run() do everthing needed to initialise GL and GLUT, and then
launch the GLUT Main Loop.
(the display function I wrote juste call the display method of each
ooglObject in the ooglScene)

Here is the problem!

Once the GLUT Main Loop is launched, I cannot add other ooglObjects to
my ooglScene, neither modify any existing ooglObject in my scene!

exemple that works but is sequential:
--
Scene = ooglScene()
Scene.append(ooglObject())
Scene.run()

What I want to do:
---
Scene = ooglScene()
Scene.run()
Scene.append(ooglObject())



I don't know the threqding system, I've take a look on that but I don't
know how to make what I need: the ooglScene.run() method must create a
separate thread to launch the glutMainLoop!

Actually I see only one solution: create two threads out of the
ooglScene and launch run() in one, and the rest of my program in the
other:

Thread1.start() --> launch the ooglScene.run()
Thread2.start() --> launch the rest of my program...

THIS IS NOT ENOUGH TRANSPARENT IN MY POINT OF VIEW!!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my openGL API need threads!!! But how to ,ake it work???

2006-02-02 Thread Laurent
Here are my codes:
it doesn't use threading...!

# 
# test_pyoogl.py
# 

#!/usr/bin/env python

from pyoogl import *
import unittest

class test(unittest.TestCase):
  def testWindow(self):
global Scene

print 'Test 1:'
print '---'
print 'This test simply verify if a GL window can be created.'
print

Scene = ooglScene()
Scene.run()

print 'Test 2:'
print '---'
print 'Verify if a Point can ben drawed, and then if the
ooglBaseObject inheritance scheme is in order.'
print

Scene.append(ooglPoint())

if __name__ == '__main__':
  Scene = None
  unittest.main()

# 
# pyoogl.py
# 

#!/usr/bin/env python

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import math
import sys
import threading

#---
class ooglBaseObject(object):
  def __init__(self):
pass

#---
class ooglObject(ooglBaseObject, list):
  """
  An ooglObject represent a object in a OpenGL scene.
  This is based on a Composite Pattern: an ooglObject is a list of
ooglObjects, and an ooglObject can ben specialised in ooglPoint,
ooglPolygon, ...
  """

  def __init__(self):
ooglBaseObject.__init__(self)
list.__init__(self)

  def ooglDraw(self):
for obj in self:
  obj.ooglDraw()

#---
class ooglPoint(ooglBaseObject):
  """
  An ooglPoint is the simpliest stuff you can creat into your scene.
  It inherits directly from ooglObject.
  """
  def __init__(self, **kwargs):
ooglBaseObject.__init__(self)

if 'x' in kwargs:
  self.__x = kargs['x']
else:
  self.__x = 0

if 'y' in kwargs:
  self.__y = kargs['y']
else:
  self.__y = 0

if 'z' in kwargs:
  self.__z = kargs['z']
else:
  self.__z = 0

  def ooglSend(self):
glVertex3f(self.__x, self.__y, self.__z)

  def ooglDraw(self):
glBegin(GL_POINTS)
self.ooglSend()
glEnd()
glFlush()

#---
class ooglScene(list):
  """
  An ooglScene describe all that is needed to represent a OpenGL scene.
  Fundamentaly, this is a list of ooglObjects.
  """

  def __init__(self):
list.__init__(self)

# GLUT variables:
self.__argv = sys.argv
self.__DisplayMode = GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE
self.__WindowPosition = {'x': 200, 'y': 200}
self.__WindowSize = {'height': 250, 'width': 250}
self.__WindowName = 'Untitled'
self.__ClearColor = {'red': 0, 'green': 0, 'blue': 0, 'alpha': 0}

# GL variables:
self.__PointSize = 2
self.__Enable = GL_DEPTH_TEST

# Callback functions:
self.__DisplayFunc = self.display
self.__KeyboardFunc = self.keyboard

# Display variables:
self.__Clear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT
self.__DefaultColor = {'red': 1, 'green': 1, 'blue': 1}

  def run(self):
"""
Make the GL, GLUT initialisations & launch the GLUT main loop.
"""
# GLUT initialisation + window creation:
glutInit(self.__argv)
glutInitDisplayMode(self.__DisplayMode)
glutInitWindowPosition(self.__WindowPosition['x'],
self.__WindowPosition['y'])
glutInitWindowSize(self.__WindowSize['height'],
self.__WindowSize['width'])
glutCreateWindow(self.__WindowName)

# GL initialisation:
glClearColor(self.__ClearColor['red'], self.__ClearColor['green'],
self.__ClearColor['blue'], self.__ClearColor['alpha'])
glPointSize(self.__PointSize)
glEnable(self.__Enable)

# setting callback functions:
glutDisplayFunc(self.__DisplayFunc)
glutKeyboardFunc(self.__KeyboardFunc)

# GLUT main loop:
glutMainLoop()
sys.exit(0)

  def display(self):
"""
The default for glutDisplayFunc.
"""
glClear(self.__Clear)

glColor3f(self.__DefaultColor['red'], self.__DefaultColor['green'],
self.__DefaultColor['blue'])
for obj in self:
  obj.ooglDraw()

glFlush()
glutSwapBuffers()

  def keyboard(self, key, x, y):
"""
The default for glutKeyboardFunc.
"""
if key == 'q':
  sys.exit(1)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my openGL API need threads!!! But how to ,ake it work???

2006-02-02 Thread Laurent
That is exactly what I do not want!!

this is not transparent, I'm sure it is possible to make what I want:
Scene = ooglScene()
Scene.run()
scene.append(ooglPoint())

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my openGL API need threads!!! But how to ,ake it work???

2006-02-02 Thread Laurent
This is not a fantasm...

Why this can not work??

in a thread a loop (the glut main loop) called by Scene.run()
and in a second something else, e.g. function A

A want to add an object in the Scene, the it call
Scene.append(anObject)
and in his next step, the glutmainloop will see that there is a new
object in the list...

If we cannot do something like that, wheere is the parrallelism? What
are the advantages of threads??!!

My code is quiet simple, plz take a look. I tried to launch the
glutMainLoop in a separate thread:

threading.Thread(glutMainLoop).start()

but the execution never reach the print 'Test 2' --> the loop freeze
the program, or the program wait for start() to end...

How this can not stop at this point?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my openGL API need threads!!! But how to ,ake it work???

2006-02-02 Thread Laurent
threading.Thread(target = Scene.run).start()   WORKS !!!

great thx ;)

now this should be better if the thread can ben declared inside the
class!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my openGL API need threads!!! But how to ,ake it work???

2006-02-02 Thread Laurent
Youpe!

That work as I want

Thx everybody ;)

The problem was that I launched the glut main loop into a thread, and
then it was separated from his initialisations functions


I put it into another method and launch that method into a thread...!

That work!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do you consider Python a 4GL? Why (not)?

2013-06-11 Thread Laurent Pointal
Dennis Lee Bieber wrote:

> On Tue, 4 Jun 2013 18:17:33 -0700, Dan Stromberg 
> declaimed the following in gmane.comp.python.general:
> 
> 
>> Perhaps "Scripting language" is the best general category we have that
>> Python fits into.  But I hope not.
> 
> Heh... Having encountered ARexx (the Amiga version of REXX), Python
> is NOT a scripting language... The ARexx implementation (along with the
> Amiga's interprocess communication system) allowed for scripting any
> application that opened an "ARexx Port"... Other than, maybe, the
> original IBM REXX, I've not seen any other REXX implementation that
> would permit embedding application specific commands into a script.
> 
> Python's subprocess (and related) are all based on explicit startup
> and communication over stdin/stdout... Nothing like:
> 
> address TextEditor/* a fictitious application port */
> 'DN 5'/* move down five lines *?:
> 'MARK'/* start a selection*/
> 'RW 5'/* move right five words */
> 'COPY'/* copy selection to operation result */
> string = result
> address PageSetter/* fictitious here, but a real program */
> 'PASTE' string/* insert selected string into page document /*
> 
> Yes, maybe the above could be done as two sessions of subprocess --
> presuming both programs had a command line interface. But what if the
> script was going to switch between the two of them throughout one
> session.

For me this is not a DSL, but an external API of an application, like you 
have with COM under Windows, DBUS under Linux. Unix streams are just an 
ancestor way of communication, you could have local-RPC also, or CORBA.

So, as this is just inter-process communication procotol, if you have the 
Amigaes interprocess communication system tool written for Python, you could 
easily write things using a Python syntax:

te = TextEditor()
te.dn(5)
te.mark()
te.rw(5)
te.copy()
string = te.result()
ps = PageSetter()
ps.paste(string)

Python is a scripting language, and a nice one to use as glue between 
different components, eventually of different technologies.

(note: if you have more than one process to control via streams, you can 
open more than one pipe)

And... here http://www.solie.ca/articles/pythonmod/pythonmod.html
you could find modules for using Python with Amiga APIs and combining it 
with ARexx.

> The C compiler suites used this ability to read the error log from a
> compile, and move to the line/column in the source file associated with
> each error. (Before "integrated" development environments)

This is a + for compiled environments that you effectively cannot have with 
Python, non-syntaxic errors found at runtime.

A+
Laurent.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use Python to post image to Facebook

2012-06-24 Thread Laurent Pointal
davecotef...@gmail.com wrote:

> On Monday, 9 April 2012 20:24:54 UTC-7, CM  wrote:
>> Shot in the dark here:  has any who reads this group been successful
>> with getting Python to programmatically post an image to Facebook?
>> 
>> I've tried using fbconsole[1] and facepy[2], both of which apparently
>> work fine for their authors and others and although I have an
>> authorization code, publish permissions, a Facebook app, I get back
>> these unhelpful errors when I try this (like "an unknown  error
>> occurred").
>> 
>> If anyone has been able to do this, maybe you can help me figure out
>> what I am doing wrong.
> 
> Hi, I am not sure, but have a similar question.  How can I post (upload)
> an image to google images and return the resulting page..?  In python? If
> you can help I would appreciate it ever so much, Dave:)

Note: if you develop such a tool, make it a "Web Out Of Browser" module.

http://weboob.org/


-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can I implement "cd" like shell in Python?

2012-06-28 Thread Laurent Pointal
Sergi Pasoev wrote:

> Do you mean to implement the cd command ? To what extent do you want to
> implement it ? if what you want is just to have a script to change the
> current working directory, it is as easy as this:
> 
> 
> import sys
> import os
> os.chdir(sys.argv[1])
> 
> plus you could add some error-handling code.

To have a shell / python script interaction for cwd management, you can take 
a look at autojump

https://github.com/joelthelion/autojump/wiki

Its a Python script + different shells glue.

A+
Laurent.


-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


argparse limitations

2012-07-27 Thread Benoist Laurent
Hi,

I'm impletting a tool in Python.
I'd like this tool to behave like a standard unix tool, as grep for exemple.
I chose to use the argparse module to parse the command line and I think I'm 
getting into several limitations of this module.

> First Question.
How can I configure the the ArgumentParser to allow the user to give either an 
input file or to pipe the output from another program?

$ mytool.py file.txt
$ cat file.txt | mytool.py


> Second Question.
How can I get the nargs options working with subparser?
Cause basically if I've got a positionnal argument with nargs > 1, then the 
subparsers are recognized as values for the positionnal argument.

$ mytool.py file1.txt file2.txt foo

Here foo is a command I'd like to pass to mytool but argparse considers it's 
another input file (as are file1.txt and file2.txt).


Any help would be appreciated.
Ben. 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse limitations

2012-07-27 Thread Benoist Laurent

Le Jul 27, 2012 à 4:43 PM, Oscar Benjamin a écrit :

> 
> 
> On 27 July 2012 15:26, Benoist Laurent  wrote:
> Hi,
> 
> I'm impletting a tool in Python.
> I'd like this tool to behave like a standard unix tool, as grep for exemple.
> I chose to use the argparse module to parse the command line and I think I'm 
> getting into several limitations of this module.
> 
> > First Question.
> How can I configure the the ArgumentParser to allow the user to give either 
> an input file or to pipe the output from another program?
> 
> $ mytool.py file.txt 
> $ cat file.txt | mytool.py
>  
> A better way to do that last line is:
> $ mytool.py < file.txt 
> 
> To answer the question, just make the first argument optional defaulting to 
> None. Then you can do:
> if file1 is None:
> file1 = sys.stdin

That's the solution I came to.
But I'm not very happy with this since I can definitively not make my program 
act as a standard unix tool.
Any other solution?


>  
> 
> 
> > Second Question.
> How can I get the nargs options working with subparser?
> Cause basically if I've got a positionnal argument with nargs > 1, then the 
> subparsers are recognized as values for the positionnal argument.
> 
> $ mytool.py file1.txt file2.txt foo
> 
> Here foo is a command I'd like to pass to mytool but argparse considers it's 
> another input file (as are file1.txt and file2.txt).
> 
> I haven't used subparsers in argparse but I imagine that you would call it 
> like:
> $ mytool.py foo file1.txt file2.txt

As far as I know it is not the case.
Let's get into the code.

parser = argparse.ArgumentParser()
parser.add_argument("-i", help="input files", nargs="+")

subparsers = parser.add_subparsers() 
foo_parser = subparser.add_parser("foo")
# ... here come some foo parser options
bar_parser = subparser.add_parser("bar")
# ... here come some bar parser options

What argparse expects is the "-i" arguments coming before the subparsers.

To summarize, if I adopt your solution to my first question, the I should add 
the "-i" argument to each subparser.
I don't want to since it's ugly and I'd have to write the help myself (which I 
don't want to).


Cheers


>  
> 
> Cheers,
> Oscar.
> 
> 
> 
> Any help would be appreciated.
> Ben.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

-- 
Benoist Laurent
Laboratoire de Biochimie Theorique / CNRS UPR 9080
Institut de Biologie Physico-Chimique
13, rue Pierre et Marie Curie
F-75005 Paris
Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse limitations

2012-07-27 Thread Benoist Laurent


Yes basically looks like you get it.
I have to further test it but my first impression is that it's correct.

So actually the point was to use nargs="?".

Thank you very much.
Ben



Le Jul 27, 2012 à 5:44 PM, Peter Otten a écrit :

> Benoist Laurent wrote:
> 
>> I'm impletting a tool in Python.
>> I'd like this tool to behave like a standard unix tool, as grep for
>> exemple. I chose to use the argparse module to parse the command line and
>> I think I'm getting into several limitations of this module.
>> 
>>> First Question.
>> How can I configure the the ArgumentParser to allow the user to give
>> either an input file or to pipe the output from another program?
>> 
>> $ mytool.py file.txt
>> $ cat file.txt | mytool.py
> 
> $ echo alpha > in.txt
> $ cat in.txt | ./mytool.py 
> ALPHA
> $ cat in.txt | ./mytool.py - out.txt
> $ cat out.txt 
> ALPHA
> $ ./mytool.py in.txt 
> ALPHA
> $ ./mytool.py in.txt out2.txt
> $ cat out2.txt 
> ALPHA
> $ cat ./mytool.py
> #!/usr/bin/env python
> assert __name__ == "__main__"
> 
> import argparse
> import sys
> 
> parser = argparse.ArgumentParser()
> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), 
> default=sys.stdin)
> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), 
> default=sys.stdout)
> args = parser.parse_args()
> 
> args.outfile.writelines(line.upper() for line in args.infile)
> 
> Is that good enough?
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

-- 
Benoist Laurent
Laboratoire de Biochimie Theorique / CNRS UPR 9080
Institut de Biologie Physico-Chimique
13, rue Pierre et Marie Curie
F-75005 Paris
Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse limitations

2012-07-31 Thread Benoist Laurent
Well sorry about that but it seems I was wrong.
It was Friday evening and I guess I've not been careful.

Actually when you specify nargs="?",  the doc says "One argument will be 
consumed from the command line if possible, and produced as a single item".
So you can't pass several arguments to the program.

So, to rephrase the question, how can I get a argument parser that parses the 
command-line just as Unix grep would do?
i.e.

$ echo 42 > foo.txt
$ echo 172 >> foo.txt
$ cp foo.txt bar.txt
$
$ grep 42 foo.txt
42
$ grep 42 foo.txt bar.txt
foo.txt:42
bar.txt:42
$ cat foo.txt | grep 42
42
$ grep -c 42 foo.txt
1


Cheers,
Ben




Le Jul 27, 2012 à 7:08 PM, Benoist Laurent a écrit :

> 
> 
> Yes basically looks like you get it.
> I have to further test it but my first impression is that it's correct.
> 
> So actually the point was to use nargs="?".
> 
> Thank you very much.
> Ben
> 
> 
> 
> Le Jul 27, 2012 à 5:44 PM, Peter Otten a écrit :
> 
>> Benoist Laurent wrote:
>> 
>>> I'm impletting a tool in Python.
>>> I'd like this tool to behave like a standard unix tool, as grep for
>>> exemple. I chose to use the argparse module to parse the command line and
>>> I think I'm getting into several limitations of this module.
>>> 
>>>> First Question.
>>> How can I configure the the ArgumentParser to allow the user to give
>>> either an input file or to pipe the output from another program?
>>> 
>>> $ mytool.py file.txt
>>> $ cat file.txt | mytool.py
>> 
>> $ echo alpha > in.txt
>> $ cat in.txt | ./mytool.py 
>> ALPHA
>> $ cat in.txt | ./mytool.py - out.txt
>> $ cat out.txt 
>> ALPHA
>> $ ./mytool.py in.txt 
>> ALPHA
>> $ ./mytool.py in.txt out2.txt
>> $ cat out2.txt 
>> ALPHA
>> $ cat ./mytool.py
>> #!/usr/bin/env python
>> assert __name__ == "__main__"
>> 
>> import argparse
>> import sys
>> 
>> parser = argparse.ArgumentParser()
>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), 
>> default=sys.stdin)
>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), 
>> default=sys.stdout)
>> args = parser.parse_args()
>> 
>> args.outfile.writelines(line.upper() for line in args.infile)
>> 
>> Is that good enough?
>> 
>> 
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>> 
> 
> -- 
> Benoist Laurent
> Laboratoire de Biochimie Theorique / CNRS UPR 9080
> Institut de Biologie Physico-Chimique
> 13, rue Pierre et Marie Curie
> F-75005 Paris
> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
Benoist Laurent
Laboratoire de Biochimie Theorique / CNRS UPR 9080
Institut de Biologie Physico-Chimique
13, rue Pierre et Marie Curie
F-75005 Paris
Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse limitations

2012-07-31 Thread Benoist Laurent
Really sorry about that.

So, for the community, below is the full code for a tool that behaves like a 
Unix standard tool.
It takes in argument the files to process and a command.

"""Just to setup a command-line parser that acts just like a unix
standard tool."""

import argparse
import sys

def define_options():
parser = argparse.ArgumentParser()
parser.add_argument("fname", help="input file", nargs="*")

# create subparsers
subparsers = parser.add_subparsers(dest="cmd", metavar="command")

# create the parser for the "foo" command
get_parser = subparsers.add_parser("foo", help="foo help")
get_parser.add_argument("-n", help="number of foo to print", 
type=int, default=10)

# create the parser for the "bar" command
sum_parser = subparsers.add_parser("bar", help="bar help")

return parser


if __name__ == '__main__':
args = define_options().parse_args()

if not args.fname:
content = sys.stdin.read()
# do something
else:
for fname in args.fname:
with(open(fname, "rt")) as f:
content = f.read()
# do somet


Benoist



Le Jul 31, 2012 à 11:55 AM, Oscar Benjamin a écrit :

> 
> On Jul 31, 2012 10:32 AM, "Benoist Laurent"  wrote:
> >
> > Well sorry about that but it seems I was wrong.
> > It was Friday evening and I guess I've not been careful.
> >
> > Actually when you specify nargs="?",  the doc says "One argument will be 
> > consumed from the command line if possible, and produced as a single item".
> > So you can't pass several arguments to the program.
> 
> Right below that in the docs it explains about using nargs='*' and nargs='+'. 
> One of those will do what you want.
> 
> Oscar.
> 
> >
> > So, to rephrase the question, how can I get a argument parser that parses 
> > the command-line just as Unix grep would do?
> > i.e.
> >
> > $ echo 42 > foo.txt
> > $ echo 172 >> foo.txt
> > $ cp foo.txt bar.txt
> > $
> > $ grep 42 foo.txt
> > 42
> > $ grep 42 foo.txt bar.txt
> > foo.txt:42
> > bar.txt:42
> > $ cat foo.txt | grep 42
> > 42
> > $ grep -c 42 foo.txt
> > 1
> >
> >
> > Cheers,
> > Ben
> >
> >
> >
> >
> > Le Jul 27, 2012 à 7:08 PM, Benoist Laurent a écrit :
> >
> >>
> >>
> >> Yes basically looks like you get it.
> >> I have to further test it but my first impression is that it's correct.
> >>
> >> So actually the point was to use nargs="?".
> >>
> >> Thank you very much.
> >> Ben
> >>
> >>
> >>
> >> Le Jul 27, 2012 à 5:44 PM, Peter Otten a écrit :
> >>
> >>> Benoist Laurent wrote:
> >>>
> >>>> I'm impletting a tool in Python.
> >>>>
> >>>> I'd like this tool to behave like a standard unix tool, as grep for
> >>>>
> >>>> exemple. I chose to use the argparse module to parse the command line and
> >>>>
> >>>> I think I'm getting into several limitations of this module.
> >>>>
> >>>>
> >>>>> First Question.
> >>>>
> >>>> How can I configure the the ArgumentParser to allow the user to give
> >>>>
> >>>> either an input file or to pipe the output from another program?
> >>>>
> >>>>
> >>>> $ mytool.py file.txt
> >>>>
> >>>> $ cat file.txt | mytool.py
> >>>
> >>>
> >>> $ echo alpha > in.txt
> >>> $ cat in.txt | ./mytool.py 
> >>> ALPHA
> >>> $ cat in.txt | ./mytool.py - out.txt
> >>> $ cat out.txt 
> >>> ALPHA
> >>> $ ./mytool.py in.txt 
> >>> ALPHA
> >>> $ ./mytool.py in.txt out2.txt
> >>> $ cat out2.txt 
> >>> ALPHA
> >>> $ cat ./mytool.py
> >>> #!/usr/bin/env python
> >>> assert __name__ == "__main__"
> >>>
> >>> import argparse
> >>> import sys
> >>>
> >>> parser = argparse.ArgumentParser()
> >>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), 
> >>> default=sys.stdin)
> >>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), 
> >>> default=sys.stdout)
> >>> args = parser.parse_args()
> >>>
> >>> args.outfile.writelines(line.upper() for line in args.infile)
> >>>
> >>> Is that good enough?
> >>>
> >>>
> >>> -- 
> >>> http://mail.python.org/mailman/listinfo/python-list
> >>>
> >>
> >> -- 
> >> Benoist Laurent
> >> Laboratoire de Biochimie Theorique / CNRS UPR 9080
> >> Institut de Biologie Physico-Chimique
> >> 13, rue Pierre et Marie Curie
> >> F-75005 Paris
> >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56
> >>
> >> -- 
> >> http://mail.python.org/mailman/listinfo/python-list
> >
> >
> > -- 
> > Benoist Laurent
> > Laboratoire de Biochimie Theorique / CNRS UPR 9080
> > Institut de Biologie Physico-Chimique
> > 13, rue Pierre et Marie Curie
> > F-75005 Paris
> > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56
> >
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >

-- 
Benoist Laurent
Laboratoire de Biochimie Theorique / CNRS UPR 9080
Institut de Biologie Physico-Chimique
13, rue Pierre et Marie Curie
F-75005 Paris
Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse limitations

2012-07-31 Thread Benoist Laurent
Finally.

The code I proposed doesn't work in this case: if you add any positional 
argument to one of the subparsers, then the parsing doesn't work anymore.
The reason seems to be that argparse thinks the last argument of the first 
parser is the last but one argument.
Hence, if a subparser takes some arguments, it fails.

Example: if the "-n" argument of the foo parser is set mandatory (so becomes 
"n" instead of "-n")

python toto.py foo.txt bar.txt foo 10
usage: toto.py [-h] [fname [fname ...]] command ...
toto.py: error: argument command: invalid choice: '10' (choose from 'foo', 
'bar')


Any solution?

Cheers,
Ben



Le Jul 31, 2012 à 12:37 PM, Benoist Laurent a écrit :

> Really sorry about that.
> 
> So, for the community, below is the full code for a tool that behaves like a 
> Unix standard tool.
> It takes in argument the files to process and a command.
> 
> """Just to setup a command-line parser that acts just like a unix
> standard tool."""
> 
> import argparse
> import sys
> 
> def define_options():
> parser = argparse.ArgumentParser()
> parser.add_argument("fname", help="input file", nargs="*")
> 
> # create subparsers
> subparsers = parser.add_subparsers(dest="cmd", metavar="command")
> 
> # create the parser for the "foo" command
> get_parser = subparsers.add_parser("foo", help="foo help")
> get_parser.add_argument("-n", help="number of foo to print", 
> type=int, default=10)
> 
> # create the parser for the "bar" command
> sum_parser = subparsers.add_parser("bar", help="bar help")
> 
> return parser
> 
> 
> if __name__ == '__main__':
> args = define_options().parse_args()
> 
> if not args.fname:
> content = sys.stdin.read()
> # do something
> else:
> for fname in args.fname:
> with(open(fname, "rt")) as f:
> content = f.read()
> # do somet
> 
> 
> Benoist
> 
> 
> 
> Le Jul 31, 2012 à 11:55 AM, Oscar Benjamin a écrit :
> 
>> 
>> On Jul 31, 2012 10:32 AM, "Benoist Laurent"  wrote:
>> >
>> > Well sorry about that but it seems I was wrong.
>> > It was Friday evening and I guess I've not been careful.
>> >
>> > Actually when you specify nargs="?",  the doc says "One argument will be 
>> > consumed from the command line if possible, and produced as a single item".
>> > So you can't pass several arguments to the program.
>> 
>> Right below that in the docs it explains about using nargs='*' and 
>> nargs='+'. One of those will do what you want.
>> 
>> Oscar.
>> 
>> >
>> > So, to rephrase the question, how can I get a argument parser that parses 
>> > the command-line just as Unix grep would do?
>> > i.e.
>> >
>> > $ echo 42 > foo.txt
>> > $ echo 172 >> foo.txt
>> > $ cp foo.txt bar.txt
>> > $
>> > $ grep 42 foo.txt
>> > 42
>> > $ grep 42 foo.txt bar.txt
>> > foo.txt:42
>> > bar.txt:42
>> > $ cat foo.txt | grep 42
>> > 42
>> > $ grep -c 42 foo.txt
>> > 1
>> >
>> >
>> > Cheers,
>> > Ben
>> >
>> >
>> >
>> >
>> > Le Jul 27, 2012 à 7:08 PM, Benoist Laurent a écrit :
>> >
>> >>
>> >>
>> >> Yes basically looks like you get it.
>> >> I have to further test it but my first impression is that it's correct.
>> >>
>> >> So actually the point was to use nargs="?".
>> >>
>> >> Thank you very much.
>> >> Ben
>> >>
>> >>
>> >>
>> >> Le Jul 27, 2012 à 5:44 PM, Peter Otten a écrit :
>> >>
>> >>> Benoist Laurent wrote:
>> >>>
>> >>>> I'm impletting a tool in Python.
>> >>>>
>> >>>> I'd like this tool to behave like a standard unix tool, as grep for
>> >>>>
>> >>>> exemple. I chose to use the argparse module to parse the command line 
>> >>>> and
>> >>>>
>> >>>> I think I'm getting into several limitations of this module.
>> >>>>
>> >>>>
>> >>&g

Re: argparse limitations

2012-07-31 Thread Benoist Laurent

Le Jul 31, 2012 à 1:45 PM, Oscar Benjamin a écrit :

> 
> 
> On 31 July 2012 12:03, Benoist Laurent  wrote:
> Finally.
> 
> The code I proposed doesn't work in this case: if you add any positional 
> argument to one of the subparsers, then the parsing doesn't work anymore.
> The reason seems to be that argparse thinks the last argument of the first 
> parser is the last but one argument.
> Hence, if a subparser takes some arguments, it fails.
> 
> Example: if the "-n" argument of the foo parser is set mandatory (so becomes 
> "n" instead of "-n")
> 
> python toto.py foo.txt bar.txt foo 10
> usage: toto.py [-h] [fname [fname ...]] command ...
> toto.py: error: argument command: invalid choice: '10' (choose from 'foo', 
> 'bar')
> 
> What about:
> 
> $ python toto.py foo.txt bar.txt foo -n 10
> 
> Note that contrary to what you said above, your program does not work like a 
> "standard unix tool". A standard command line program to do what you want 
> would normally look like

You're right.
But then, using argparse, I would have to add the same argument to all my 
subparsers since argparse does the work sequentially: once it recognized the 
start of a subparser, everything that follows have to be an argument of this 
subparser.
Hence, arguments (therefore options) from the main parser are not recognized 
anymore.

> 
> $ python toto.py foo -n 10 foo.txt bar.txt

Same remark as above: if I want the command line to look like this, then I 
would have setup each subparser with all the main program options.


> 
> or perhaps
> 
> $ python toto.py foo foo.txt bar.txt -n 10
> 
> so that the algorithm for differentiating the command 'foo' from the 
> filenames is well defined. How do you propose that your user enters a 
> filename 'foo'?

Well I guess it is a intrinsec limitation: I think it's quite natural that the 
user can't enter a filename named as a command.


> 
> Oscar.
> 
> 
> 
> Any solution?
> 
> Cheers,
> Ben
> 
> 
> 
> Le Jul 31, 2012 à 12:37 PM, Benoist Laurent a écrit :
> 
>> Really sorry about that.
>> 
>> So, for the community, below is the full code for a tool that behaves like a 
>> Unix standard tool.
>> It takes in argument the files to process and a command.
>> 
>> """Just to setup a command-line parser that acts just like a unix
>> standard tool."""
>> 
>> import argparse
>> import sys
>> 
>> def define_options():
>> parser = argparse.ArgumentParser()
>> parser.add_argument("fname", help="input file", nargs="*")
>> 
>> # create subparsers
>> subparsers = parser.add_subparsers(dest="cmd", metavar="command")
>> 
>> # create the parser for the "foo" command
>> get_parser = subparsers.add_parser("foo", help="foo help")
>> get_parser.add_argument("-n", help="number of foo to print", 
>> type=int, default=10)
>> 
>> # create the parser for the "bar" command
>> sum_parser = subparsers.add_parser("bar", help="bar help")
>> 
>> return parser
>> 
>> 
>> if __name__ == '__main__':
>> args = define_options().parse_args()
>> 
>> if not args.fname:
>> content = sys.stdin.read()
>> # do something
>> else:
>> for fname in args.fname:
>> with(open(fname, "rt")) as f:
>> content = f.read()
>> # do somet
>> 
>> 
>> Benoist
>> 
>> 
>> 
>> Le Jul 31, 2012 à 11:55 AM, Oscar Benjamin a écrit :
>> 
>>> 
>>> On Jul 31, 2012 10:32 AM, "Benoist Laurent"  wrote:
>>> >
>>> > Well sorry about that but it seems I was wrong.
>>> > It was Friday evening and I guess I've not been careful.
>>> >
>>> > Actually when you specify nargs="?",  the doc says "One argument will be 
>>> > consumed from the command line if possible, and produced as a single 
>>> > item".
>>> > So you can't pass several arguments to the program.
>>> 
>>> Right below that in the docs it explains about using nargs='*' and 
>>> nargs='+'. One of those will do what you want.
>>> 
>>> Oscar.
>>> 
>>> >
>>> > So, to rephrase the question, 

Re: argparse limitations

2012-07-31 Thread Benoist Laurent
> The standard way, however, is to have a parser that takes the first 
> non-option argument as a subcommand name and parses the remaining arguments 
> according to that subcommand. Your command line users are more likely to be 
> able to understand how to use the program if it works that way.

I'll do this way.
Thank a lot.

Ben

Le Jul 31, 2012 à 3:04 PM, Oscar Benjamin a écrit :

> 
> 
> On 31 July 2012 13:51, Benoist Laurent  wrote:
> 
> Le Jul 31, 2012 à 1:45 PM, Oscar Benjamin a écrit :
> 
>> 
>> 
>> On 31 July 2012 12:03, Benoist Laurent  wrote:
>> Finally.
>> 
>> The code I proposed doesn't work in this case: if you add any positional 
>> argument to one of the subparsers, then the parsing doesn't work anymore.
>> The reason seems to be that argparse thinks the last argument of the first 
>> parser is the last but one argument.
>> Hence, if a subparser takes some arguments, it fails.
>> 
>> Example: if the "-n" argument of the foo parser is set mandatory (so becomes 
>> "n" instead of "-n")
>> 
>> python toto.py foo.txt bar.txt foo 10
>> usage: toto.py [-h] [fname [fname ...]] command ...
>> toto.py: error: argument command: invalid choice: '10' (choose from 'foo', 
>> 'bar')
>> 
>> What about:
>> 
>> $ python toto.py foo.txt bar.txt foo -n 10
>> 
>> Note that contrary to what you said above, your program does not work like a 
>> "standard unix tool". A standard command line program to do what you want 
>> would normally look like
> 
> You're right.
> But then, using argparse, I would have to add the same argument to all my 
> subparsers since argparse does the work sequentially: once it recognized the 
> start of a subparser, everything that follows have to be an argument of this 
> subparser.
> Hence, arguments (therefore options) from the main parser are not recognized 
> anymore.
> 
> If the parsing after the subcommand is to be the same for each subcommand, 
> then don't use subparsers. You could just make the first argument be the 
> command name and use one parser for everything.
> 
> If the parsing is supposed to be different for different subcommands then use 
> subparsers and add the files argument to each subparser; you can make a 
> function to add the common arguments and options if you don't want to 
> duplicate the code.
> 
> Well I guess it is a intrinsec limitation: I think it's quite natural that 
> the user can't enter a filename named as a command.
> 
> There is an intrinsic limitation on any parser that it must be possible to 
> determine the targets of the arguments uniquely. If you want the parser to 
> scan through and take the first argument matching 'foo' or 'bar' and parse 
> the remaining arguments accordingly then you already have your solution. It 
> just won't work if the user wants to pass in a file called 'foo' or 'bar' 
> (maybe that's acceptable, though).
> 
> The standard way, however, is to have a parser that takes the first 
> non-option argument as a subcommand name and parses the remaining arguments 
> according to that subcommand. Your command line users are more likely to be 
> able to understand how to use the program if it works that way.
> 
> Oscar.

-- 
Benoist Laurent
Laboratoire de Biochimie Theorique / CNRS UPR 9080
Institut de Biologie Physico-Chimique
13, rue Pierre et Marie Curie
F-75005 Paris
Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing a text over an image

2012-11-07 Thread Laurent Pointal
Martha Morrigan wrote:

> 
> 3) Any more simple approach or module to deals with printers (paper
> and/or pdf) will be welcome.

For pdf, you can take a look at ReportLab's Toolkit. I used it to build a 
"trombinoscope" (ie an employee directory with each member's photo on top of 
his name and room number).

http://www.reportlab.com/software/opensource/

Once created the pdf, you must find a solution to send it to the printer...

> 
> Thanks in advance,
> 
> Martha

A+
Laurent.

-- 
http://mail.python.org/mailman/listinfo/python-list


Killing threads, and os.system()

2012-01-30 Thread Laurent Claessens

Hello all


  I've a program that launches a lot of  threads and each of them 
launches a os.system("my_command").


My program also keeps a list of the launched threads, so I can make 
"for" loops on the threads.



My aim is to kill everything with ctrl-C (KeyboardInterrupt).

Of course I tried to do

try:
   [...]
except KeyboardInterrupt :
   for task in task_list :
  task.stop()
  #task_list is the list of threads to be killed


It does not work.

How can I produce an "emergency" stop of all processes, including the 
externals programs that were called by os.system() ?


My aim is of course to write an ultimate log file containing the status 
of the program when KeyboardInterupt was raised. (if not, the unix 
command "kill" does the job ;) )



Thanks for any help
have a good day
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing threads, and os.system()

2012-01-31 Thread Laurent Claessens

Le 31/01/2012 17:04, Dennis Lee Bieber a écrit :


Of course, if that thread is stuck waiting for a call to os.system()
to complete, then it can not do anything...

os.system() is a rather limited, restrictive, call -- best used for
quick one-of operations. If running Python 2.6+, I'd recommend
converting from os.system() to subprocess.Popen(). .Popen() objects now
have .terminate() and .kill() methods.


Ok, I'll try that Popen. Indeed I think that my threads are stuck 
waiting os.system to complete.


Thanks
Laurent

--
http://mail.python.org/mailman/listinfo/python-list


Re: Naming convention for in-house modules (Newbie question)

2012-02-09 Thread Laurent Claessens



Here is my question: I would like to start an in-house library of small
modules to import, for things like error handling/logging. That's easy
enough, but is there a recommended way of naming such modules? I am
concerned about avoiding name clashes with standard modules and site
packages.

Thanks.



This is not 100% an answer to the question, but you should read that :
http://www.python.org/dev/peps/pep-0008/

This explain you WhatCaseToChoose for_naming youVariables.

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Naming convention for in-house modules (Newbie question)

2012-02-09 Thread Laurent Claessens



 This is not 100% an answer to the question, but you should read that :
 http://www.python.org/dev/peps/pep-0008/


The OP mentions PEP 8 in the bit of his message that you *don't* quote.


Well... I've to sleep. Sorry :(

Laurent


--
http://mail.python.org/mailman/listinfo/python-list


Re: what is best method to set sys.stdout to utf-8?

2012-03-07 Thread Laurent Claessens



I would. The io module is more recent an partly replaces codecs. The
latter remains for back compatibility and whatever it can do that io cannot.



 I've a naive question : what is wrong with the following system ?

class MyStdOut(object):
def __init__(self):
self.old_stdout=sys.stdout
def write(self,x):
try:
if isinstance(x,unicode):
x=x.encode("utf8")
except (UnicodeEncodeError,UnicodeDecodeError):
sys.stderr.write("This should not happen !")
raise
self.old_stdout.write(x)
sys.stdout=MyStdOut()


... well ... a part of the fact that it is much longer ?


Laurent Claessens
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distribution

2012-03-20 Thread Laurent Claessens

Il 20/03/2012 12:21, Ben Finney ha scritto:

"prince.pangeni"  writes:


I am doing a simulation project using Python. In my project, I want
 to use some short of distribution to generate requests to a server.


I guess scipy is also available in plain python (didn't check), but the 
following works with Sage :


--
| Sage Version 4.8, Release Date: 2012-01-20 |
| Type notebook() for the GUI, and license() for information.|
--
sage: from scipy import stats
sage: X=stats.poisson.rvs
sage: X(4)
5
sage: X(4)
2
sage: X(4)
3


Hope it helps
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: string interpolation for python

2012-04-02 Thread Laurent Claessens



Seems you miss understood my notion of dynamic string.
Dynamic strings are expressions in disguise: the things
in between $...$ are plain old expressions (with optional
formatting specifications). They are evaluated
as if they were outside the dynamic string. We put them
in there to to kill two birds with one stone:
1) ease of reading;
2) place holding.



like this one ?

b = dict(name="Sue", job="SAS sharp-shooter")
print "$b['name']$ works as b['job']"

Is it really easier to read that the following ?
"{0} works as {1}".format(b['name'],b['job'])

In the case in which b is an object having "job" and "name" attribute, 
the dynamic string will write


"$b.name$ works as $b.job$"
instead of
"{0}.name works as {0}.job".format(b)

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Naming future objects and their methods

2012-04-15 Thread Laurent Pointal
Stefan Schwarzer wrote:

> Hello,
> 
> I wrote a `Connection` class that can be found at [1]. A
> `Connection` object has a method `put_bytes(data)` which
> returns a "future" [2]. The data will be sent asynchronously
> by a thread attached to the connection object.
> 
> The future object returned by `put_bytes` has a `was_sent`
> method which will return `True` once the sender thread has
> actually sent the data via a socket call. An example might
> look like
> 
> put_result = connection.put_bytes(data)
> if put_result.was_sent(timeout=1.0):
> print "Data has been sent."
> else:
> print "Data hasn't been sent within one second."
> 
> However, I'm not comfortable with the combination of the
> names of the future and its method. After all, not the
> `put_result` was sent, but the data that was the argument in
> the `put_bytes` call. Maybe `data_was_sent` is better than
> `was_sent`, but `put_result.data_was_sent()` doesn't feel
> right either.


Just an idea:
put_result ==> dataput
was_sent ==> sent

dataput = connection.put_bytes(data)
if dataput.sent(timeout=1.0):
print "Data has been sent."
else:
print "Data hasn't been sent within one second."


-- 
Laurent POINTAL - laurent.poin...@laposte.net
3 allée des Orangers - 91940 Les Ulis - France
Tél. 01 69 29 06 59

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to list for submission to easygui multenterb​ox

2012-05-02 Thread Laurent Pointal
ksals wrote:

> On May 1, 5:29 pm, John Gordon  wrote:
>> In <3b5f65c4-cd95-4bb4-94f2-0c69cf2b1...@d20g2000vbh.googlegroups.com>
>> ksals  writes:
>>
>> > The original choice looks like this when I print it:
>> > print(choice)
>> > ('ksals', '', 'alsdkfj', '3', '')
>> > I need to submit these as defaults to a multenterbox. Each entry above
>> > ksals, "", "alsdkfj', 3 , '' need to fill the five fields in the box.
>> > I tried your suggestion so you must be right it is a tuple of 5
>> > strings.  But I need them to work in an instruction like
>> > fieldValues =3D eg.multenterbox(msg1,title, fieldNames, choice)
>> > fieldNames has 5 fields.
>>
>> If you just need to convert a tuple to a list, that's easy.  Call the
>> built-in function list() and pass the tuple as an intializer:
>>
>> >>> choice = ('ksals', '', 'alsdkfj', '3', '')
>> >>> print choice
>>
>> ('ksals', '', 'alsdkfj', '3', '')>>> choice_list = list(choice)
>> >>> print choice_list
>>
>> ['ksals', '', 'alsdkfj', '3', '']
>>
>> --
>> John Gordon   A is for Amy, who fell down the stairs
>> gor...@panix.com  B is for Basil, assaulted by bears
>> -- Edward Gorey, "The Gashlycrumb Tinies"
>>
>>
> This is a small excert to show you what I get
> 
> for choice in easygui.multchoicebox(msg1, title,qstack):
> if choice[0] == None:
> print ("No entries made")
> break
> 
> 
> print("CHOICE IS: ",choice). CHOICE IS:
> ('', 'ksals', '', '', '')
> c=list(choice)
> print("C IS: ",c)  .  C IS:  ['(',
> "'", "'", ',', ' ', "'", 'k', 's', 'a', 'l', 's', "'", ',', ' ', "'",
> "'", ',', ' ', "'", "'", ',', ' ', "'", "'",
> ')']

Looks like you have your tuple expression
('ksals', '', 'alsdkfj', '3', '')
not as a tuple, but as a string. Do you convert it somewhere ? 

If you have it as a string, you can use eval() (not safe!) on the string to 
retrieve the tuple, then list() on the tuple to get a list.


-- 
Laurent POINTAL - laurent.poin...@laposte.net
3 allée des Orangers - 91940 Les Ulis - France
Tél. 01 69 29 06 59

-- 
http://mail.python.org/mailman/listinfo/python-list


English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Laurent Pointal
Hello,

I started a first translation of my document originally in french. Could 
some fluent english people read it and indicate errors or bad english 
expressions.

http://perso.limsi.fr/pointal/python:memento

Thanks.
A+
Laurent.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-05 Thread Laurent Pointal
Paul Rubin wrote:

> Laurent Pointal  writes:
>> I started a first translation of my document originally in french. Could
>> some fluent english people read it and indicate errors or bad english
>> expressions.
>>
>> http://perso.limsi.fr/pointal/python:memento
> 
> It looks nice.  It took me a minute to find the English version:
> 
>   http://perso.limsi.fr/pointal/_media/python:cours:mementopython3-
english.pdf
> 
> A few minor things:
> 
> 1) We would usually call this a "reference card" rather than "memento"
> 
> 2) In the dictionary example,
>{"clé":"valeur"} =>  {"key":"value"}
>{1:"un",3:"trois",2:"deux",3.14:""} => {1:"one", etc. }
> 
> 3) "bloc" in a few places should be "block"
> 
> 4) On side 2, the part about writing files is still mostly in French
> 
> There are a few other things like that, and I'll try to look more
> carefully tonight, I can't spend more time on it right now.
> 
> Thanks for writing it and sharing it.
> 
> --Paul

Thanks,

I updated the document into 1.0.5a (and fix some other errors).

A+
Laurent.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-06 Thread Laurent Pointal
Paul Rubin wrote:

> Laurent Pointal  writes:
>>> There are a few other things like that, and I'll try to look more
>>> carefully tonight, I can't spend more time on it right now.
>> I updated the document into 1.0.5a (and fix some other errors).
> 
> A few more things:
> 


> In "Files"
>   don't miss to close file => don't forget to close the file
> [but you might mention the "with" statement]

I put it as a note (I want students to have file closing in mind, they may 
practice other languages without such constructions).

> In "Function definition"
>   bloc => block
>   (« black box »)  => ("black box")
> [English speakers may not recognize « » symbols]

I switched them to "". 
Its here to remember students that they can't access to functions internal 
variables from outside (and should try to limit access to outside world from 
inside functions) - a common error during practice. In lecture class, I try 
to show them only two access points to functions: parameters and return 
value, and a "black box" blocking all other informations.

> In "Generator of int sequences"
>   You might mention that range makes a generator only in Python 3.
>   In Python 2 it makes an actual list and xrange makes a generator.

We teach with Python3 as several modifications in the language are better 
for leaning programming basics (like 1/2 => 0.5).

Thanks for all your corrections, I'll continue with other posters.

A+
L.Pointal.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English version for Mémento Python 3 (draft, readers needed)

2012-06-06 Thread Laurent Pointal
Ulrich Eckhardt wrote:

> Am 05.06.2012 19:32, schrieb Laurent Pointal:
>> I started a first translation of my document originally in french. Could
>> some fluent english people read it and indicate errors or bad english
>> expressions.
> 
> Just one note up front: Languages or nationalities are written with
> uppercase letters, like English and French. Other common faults of that
> category are days of the week (Monday..) and month names (January..),
> although that's irrelevant for your doc.

I modified slightly the page, to have first links in the page for document 
downloading (and other links deeper in the page).

> Another thing I noticed that was missing was that the "in" keyword can
> not only be used to iterate over a sequence (for i in seq:...) but also
> to test if something is contained in a sequence (if i in seq:...).

I reworked the second page to have less informations about string formating 
(nice, but less important than operations on containers), and add sections 
on containers, lists, dictionaries and set.

> "don't miss to close file after use": Use a "with" statement.

Added as a note.

> "see verso for string formatting..." - what is "verso"?

Modified with Paul indications (its the "other side" in french - from 
latin).

> "dont" -> "don't"

Done.

> "char strings" -> "strings" (in the context of indexing, byte strings
> have the same syntax)

Modified (even if I dont teach byte strings with my students).

> "with several else if, else if..." - there is no "else if" but "elif".

Modified (it was originally a translation from french, but the 
correcpondance between english version and keywords can be confusing).

> "block else for other cases" - this sounds as if it was blocking the
> else. Maybe "else-block for other cases", but English hyphenation is
> complicated and I'm not sure.

Modified to "else block..."

Thanks for your reading and comments.

A+
Laurent.

-- 
Laurent POINTAL - laurent.poin...@laposte.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the stupid encoding problem to stdout

2011-06-09 Thread Laurent Claessens

Le 09/06/2011 04:18, Sérgio Monteiro Basto a écrit :
> hi,
> cat test.py
> #!/usr/bin/env python
> #-*- coding: utf-8 -*-
> u = u'moçambique'
> print u.encode("utf-8")
> print u
>
> chmod +x test.py
> ../test.py
> moçambique
> moçambique


The following tries to encode before to print. If you pass an already 
utf-8 object, it just print it; if not it encode it. All the "print" 
statements pass by MyPrint.write


#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys

class MyPrint(object):
def __init__(self):
self.old_stdout=sys.stdout
sys.stdout=self
def write(self,text):
try:
encoded=text.encode("utf8")
except UnicodeDecodeError:
encoded=text
self.old_stdout.write(encoded)


MyPrint()

u = u'moçambique'
print u.encode("utf-8")
print u

TEST :

$ ./test.py
moçambique
moçambique

$ ./test.py > test.txt
$ cat test.txt
moçambique
moçambique


By the way, my code will not help for error message. I think that the 
errors are printed by sys.stderr.write. So if you want to do

raise "moçambique"
you should think about add stderr to the class MyPrint


If you know French, I strongly recommend "Comprendre les erreurs 
unicode" by Victor Stinner :

http://dl.afpy.org/pycon-fr-09/Comprendre_les_erreurs_unicode.pdf

Have a nice day
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: the stupid encoding problem to stdout

2011-06-09 Thread Laurent Claessens

Le 09/06/2011 04:18, Sérgio Monteiro Basto a écrit :
> hi,
> cat test.py
> #!/usr/bin/env python
> #-*- coding: utf-8 -*-
> u = u'moçambique'
> print u.encode("utf-8")
> print u
>
> chmod +x test.py
> ../test.py
> moçambique
> moçambique


The following tries to encode before to print. If you pass an already 
utf-8 object, it just print it; if not it encode it. All the "print" 
statements pass by MyPrint.write


#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys

class MyPrint(object):
def __init__(self):
self.old_stdout=sys.stdout
sys.stdout=self
def write(self,text):
try:
encoded=text.encode("utf8")
except UnicodeDecodeError:
encoded=text
self.old_stdout.write(encoded)


MyPrint()

u = u'moçambique'
print u.encode("utf-8")
print u

TEST :

$ ./test.py
moçambique
moçambique

$ ./test.py > test.txt
$ cat test.txt
moçambique
moçambique


By the way, my code will not help for error message. I think that the 
errors are printed by sys.stderr.write. So if you want to do

raise "moçambique"
you should think about add stderr to the class MyPrint


If you know French, I strongly recommend "Comprendre les erreurs 
unicode" by Victor Stinner :

http://dl.afpy.org/pycon-fr-09/Comprendre_les_erreurs_unicode.pdf

Have a nice day
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: the stupid encoding problem to stdout

2011-06-09 Thread Laurent Claessens

Le 09/06/2011 04:18, Sérgio Monteiro Basto a écrit :
> hi,
> cat test.py
> #!/usr/bin/env python
> #-*- coding: utf-8 -*-
> u = u'moçambique'
> print u.encode("utf-8")
> print u
>
> chmod +x test.py
> ../test.py
> moçambique
> moçambique


The following tries to encode before to print. If you pass an already 
utf-8 object, it just print it; if not it encode it. All the "print" 
statements pass by MyPrint.write


#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys

class MyPrint(object):
def __init__(self):
self.old_stdout=sys.stdout
sys.stdout=self
def write(self,text):
try:
encoded=text.encode("utf8")
except UnicodeDecodeError:
encoded=text
self.old_stdout.write(encoded)


MyPrint()

u = u'moçambique'
print u.encode("utf-8")
print u

TEST :

$ ./test.py
moçambique
moçambique

$ ./test.py > test.txt
$ cat test.txt
moçambique
moçambique


By the way, my code will not help for error message. I think that the 
errors are printed by sys.stderr.write. So if you want to do

raise "moçambique"
you should think about add stderr to the class MyPrint


If you know French, I strongly recommend "Comprendre les erreurs 
unicode" by Victor Stinner :

http://dl.afpy.org/pycon-fr-09/Comprendre_les_erreurs_unicode.pdf

Have a nice day
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.path and Path

2011-06-16 Thread Laurent Claessens



So, I suppose I shall have to let go of my dreams of

-->  Path('/some/path/and/file') == '\\some\\path\\and\\file'

and settle for

-->  Path('...') == Path('...')

but I don't have to like it.  :(



Why not define the hash method to first convert to '/some/path/and/file' 
and then hash ?


By the way it remains some problems with

/some/another/../path/and/file

which should also be the same.

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is this syntax ?

2011-06-19 Thread Laurent Claessens

Le 19/06/2011 15:41, candide a écrit :

With Python 2.7 :

  >>>  x="foo"
  >>>  print '"'+x+'"'
"foo"
  >>>


What is this curious syntax on line 2 ? Where is it documented ?


When you want to have an explicit double quote " in a string, you put in 
between single quote '.

(and vice versa)

So here you have the string
'"'
which is "
then
+x
(add x)
then
+'"'

Try also

>>> print "'"
'
>>> print "'"
"

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading : make stop the caller

2011-06-19 Thread Laurent Claessens

Le 19/06/2011 17:19, Chris Angelico a écrit :

On Mon, Jun 20, 2011 at 12:42 AM, Laurent Claessens  wrote:

Hello


 I've a list of tasks to perform. Each of them is a threading.Thread.
 Basically I have :

 while task_list :
task = task_list[0]
task.run()
task_list.remove(task)


I'm not understanding what you're doing with threads here. Are you
using threading.Thread but then calling its run() method
synchronously?


Woops yes. I missprinted my example. I was using task.start() of course.

The aim is to copy the content of a repertory (with some conditions on 
each file, so I cannot use shutils or something).


I've one thread that runs over the repertory and fill the list 
'task_list' with taskes from the following class :



class FileCopyTask(threading.Thread):
def __init__(self,source,destination,old_version):
threading.Thread.__init__(self)
self.source = source
self.destination = destination
def run(self):
try :
shutil.copy(self.source,self.destination)
except (IOError,OSError),data :

else :
print "file copied"


In the same time I've a thread that read the list and perform the 
operations:


def run():
   while task_list :
  task = task_list[0]
  task_list.remove(task)
  task.start()


My problem is that when FileToCopyTask raises an error, the program does 
not stop.
In fact when the error is Disk Full, I want to stop the whole program 
because I know that the next task will fail too.


thanks for any help
Laurent


--
http://mail.python.org/mailman/listinfo/python-list


Re: threading : make stop the caller

2011-06-19 Thread Laurent Claessens

Le 19/06/2011 18:03, Chris Angelico a écrit :

On Mon, Jun 20, 2011 at 1:39 AM, Laurent Claessens  wrote:

 My problem is that when FileToCopyTask raises an error, the program does not
 stop.
 In fact when the error is Disk Full, I want to stop the whole program
 because I know that the next task will fail too.


If you're starting a thread for every file you're copying, you're
starting a huge number of threads that probably will just end up
fighting over the disk. To get a reasonably efficient early-abort, I'd
recommend having a fixed pool of worker threads (say, ten of them),
and have each thread (a) check if the early-abort flag is set, and
then (b) start copying the next file in queue. Once the queue's empty
or the early-abort flag is set, all ten threads will terminate when
they finish their current transfers.


Yes, my example was simplified, but I do that :)

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading : make stop the caller

2011-06-19 Thread Laurent Claessens



Popping task off the end of the list is more efficient:



while task_list:
task_list.pop().start()


That's cool. In my case it's better to do
task_list.pop(0).start

in order to pop the first element.


or if the list is static


No, my list is dynamic and is feeded by an other thread (which also has 
to be closed).


Finally, I solved the problem by using a global flag looked at each 
iteration of the loop. A break is done if the global flag reports an error.


That was suggested by Alain Ketterlin from the French speaking python's 
usenet and Chris Angelico here.


Thanks all
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


threading : make stop the caller

2011-06-19 Thread Laurent Claessens

   Hello


I've a list of tasks to perform. Each of them is a threading.Thread. 
Basically I have :


while task_list :
   task = task_list[0]
   task.run()
   task_list.remove(task)


Now I want, in some circumstance to raise errors that make the loop stop.

In order IOError to make stop the loop, I tried this :

no_error = True
while task_list and no_error:
   task = task_list[0]
   try :
  task.run()
   except IOError :
  no_error = False
   task_list.remove(task)

But it does not work (I think the exception is raised too late).

I prefer that the taske are not aware to be included in a loop, but I 
can make them raise personnal exceptions.

How can I do ?


Thanks
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading : make stop the caller

2011-06-19 Thread Laurent Claessens
I read the library documentation. I think that if I get a trick to kill 
a thread, then I'm done.


Is there a way ?

Laurent


Le 19/06/2011 17:39, Laurent Claessens a écrit :

Le 19/06/2011 17:19, Chris Angelico a écrit :

 On Mon, Jun 20, 2011 at 12:42 AM, Laurent Claessens   
wrote:

 Hello


  I've a list of tasks to perform. Each of them is a threading.Thread.
  Basically I have :






--
http://mail.python.org/mailman/listinfo/python-list


Re: help me in knowing the syntax for loop and switch statements in python 3.2

2011-06-23 Thread Laurent Claessens

Le 23/06/2011 11:48, mahantesh varavattekar a écrit :

Hi,

i am new to python please help to let me know the syntax for python
3.2. with examples.
and how can i use these things for ranges


http://lmgtfy.com/?q=python+syntax+range+example

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: reg: playing with the list

2011-06-24 Thread Laurent Claessens



You might try  writing the boolean function is_prime(n) for almost any n.

There was a recent discussion on this topic.


Since the guy is "new in programming", I complete the answer, just in 
case. Using the function is_prime(n),


FIRST POSSIBILITY :

new_list=[]
for n in old_list:
   if is_prime(n):
  new_list.append(n)

SECOND POSSIBILITY :

new_list=[ n for n in old_list if is_prime(n) ]



There is a primiality test in Sage which is basically a module over 
python (www.sagemath.org).


Have a good WE
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to call a function for evry 10 secs

2011-06-30 Thread Laurent Claessens



But if the function itself runs for longer than 10 seconds, there
will be a major problem, as the sleep apparently takes the argument as
unsigned, and a negative number is a very big sleep!


Launch each call in a separate thread. If the calls are independent, 
this could be a solution.


Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

2011-08-21 Thread Laurent Payot
I made Python my language of choice because of its readability and simpleness, 
and not because of its speed. But it's always good to know what is the fastest 
sometimes when you don't want to write a module in C. So I was just wondering 
if there was a difference. There is, of a few percent. Anyway I will keep on 
using the 2% slower "i += 1" because for me that's less prone to errors because 
you write the variable only once, and that's more important than speed.
-- 
http://mail.python.org/mailman/listinfo/python-list


nntplib encoding problem

2011-02-27 Thread Laurent Duchesne

Hi,

I'm using python 3.2 and got the following error:


nntpClient = nntplib.NNTP_SSL(...)
nntpClient.group("alt.binaries.cd.lossless")
nntpClient.over((534157,534157))
... 'subject': 'Myl\udce8ne Farmer - Anamorphosee (Japan Edition) 1995 
[02/41] "Back.jpg" yEnc (1/3)' ...

overview = nntpClient.over((534157,534157))
print(overview[1][0][1]['subject'])

Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce8' in 
position 3: surrogates not allowed


I'm not sure if I should report this as a bug in nntplib or if I'm 
doing something wrong.


Note that I get the same error if I try to write this data to a file:


h = open("output.txt", "a")
h.write(overview[1][0][1]['subject'])

Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce8' in 
position 3: surrogates not allowed


Thanks,
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: nntplib encoding problem

2011-02-28 Thread Laurent Duchesne

Hi,

Thanks it's working!
But is it "normal" for a string coming out of a module (nntplib) to 
crash when passed to print or write?


I'm just asking to know if I should open a bug report or not :)

I'm also wondering which strings should be re-encoded using the 
surrogateescape parameter and which should not.. I guess I could 
reencode them all and it wouldn't cause any problems?


Laurent

On Mon, 28 Feb 2011 02:12:20 +, MRAB wrote:

On 28/02/2011 01:31, Laurent Duchesne wrote:

Hi,

I'm using python 3.2 and got the following error:


nntpClient = nntplib.NNTP_SSL(...)
nntpClient.group("alt.binaries.cd.lossless")
nntpClient.over((534157,534157))
... 'subject': 'Myl\udce8ne Farmer - Anamorphosee (Japan Edition) 
1995

[02/41] "Back.jpg" yEnc (1/3)' ...

overview = nntpClient.over((534157,534157))
print(overview[1][0][1]['subject'])

Traceback (most recent call last):
File "", line 1, in 
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce8' in
position 3: surrogates not allowed

I'm not sure if I should report this as a bug in nntplib or if I'm 
doing

something wrong.

Note that I get the same error if I try to write this data to a 
file:



h = open("output.txt", "a")
h.write(overview[1][0][1]['subject'])

Traceback (most recent call last):
File "", line 1, in 
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce8' in
position 3: surrogates not allowed


It's looks like the subject was originally encoded as Latin-1 (or
similar) (b'Myl\xe8ne Farmer - Anamorphosee (Japan Edition) 1995
[02/41] "Back.jpg" yEnc (1/3)') but has been decoded as UTF-8 with
"surrogateescape" passed as the "errors" parameter.

You can get the "correct" Unicode by encoding as UTF-8 with
"surrogateescape" and then decoding as Latin-1:

overview[1][0][1]['subject'].encode("utf-8",
"surrogateescape").decode("latin-1")


--
http://mail.python.org/mailman/listinfo/python-list


Re: alphanumeric list

2011-03-15 Thread Laurent Claessens

Le 15/03/2011 09:10, yqyq22 a écrit :

Hi all,
I would like to put an alphanumeric string like this one
EE472A86441AF2E629DE360 in a list, then iterate inside the entire
string lenght and change each digit with a random digit.
Do u have some suggestion? thanks a lot


This can be a way to begin :

s="EE472A86441AF2E629DE360"
for a in s:
   print a

The following is a very basic trick to build a list  containing the
elements of the string 

s="EE472A86441AF2E629DE360"
t=[]
for a in s:
   t.append(a)

All that you have to change is t.append(a) into something that
tests if a is a number and append something else in that case.

Depending what you want, you can even do

s.replace("1","ONE").replace("2","TWO").replace("3","FIVE")

This is however far from being random ;)

Have good tests
Laurent

--
http://mail.python.org/mailman/listinfo/python-list


Re: alphanumeric list

2011-03-16 Thread Laurent Claessens



string = "EE472B"
t = []
for x in string[:]:
 print t.append("A")   #i don't want to append A, the final
result is EAEA4A7A2ABA


As it, it prints "None" 6 times. Then t is ['A','A','A','A','A']

What you have to do is to read about basic python. Search for python 
tutorial on the net.


Then try the following exercices :

Exercises

1
print the first 1000 intergers

2
print the sine of 1 ... 1000

3
print the intergers x between 1 and 1000 such that cos(x) is between 0 
and 0.5



Have a good afternoon
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: alphanumeric list

2011-03-16 Thread Laurent Claessens



string = "EE472B"
t = []
for x in string[:]:
 print t.append("A")   #i don't want to append A, the final
result is EAEA4A7A2ABA


As it, it prints "None" 6 times. Then t is ['A','A','A','A','A']

What you have to do is to read about basic python. Search for python 
tutorial on the net.


Then try the following exercices :

Exercises

1
print the first 1000 intergers

2
print the sine of 1 ... 1000

3
print the intergers x between 1 and 1000 such that cos(x) is between 0 
and 0.5



Have a good afternoon
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.walk() to get full path of all files

2011-03-17 Thread Laurent Claessens



file_list = []
for root, _, filenames in os.walk(root_path):
  for filename in filenames:
  file_list.append(os.path.join(root, filename))



What does the notation "_" stands for ? Is it a sort of /dev/null ?

I know that in the terminal it represents the last printed text.

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator Syntax

2011-03-22 Thread Laurent Claessens

And I'm willing to bet that there are plenty of
scripts out there that use "dec" as a name for Decimal objects.


You won. I owe you a beer ;)

Laurent

--
http://mail.python.org/mailman/listinfo/python-list


Re: Non-deterministic output

2011-03-28 Thread Laurent Claessens



One of us thought it could be set and dictionaries not always yielding
the same results. I, however, would think that given the exact same
operations, a set/dictionary would always yield the same results. Am I
correct? Or could different runs of the same program yield different
results due to, say, different memory locations?


If you have

d={"a":1,"b":2}
print d.keys()

then there are no way to be deterministic.

What you can do is

d={"a":1,"b":2}
k = d.keys()
k.sort()
print k

This is deterministic.

An other source of non-deterministic behaviour is to rely on the 15th 
decimal of a difficult computation.


I had the following with Sage[1] :

sage: p=plot(x**2,-1,1)
sage: p.get_minmax_data()
{'xmin': -1.0, 'ymin': 3.0448943892610684e-06, 'ymax': 1.0, 'xmax': 1.0}

and in a new Sage shell :

sage: p=plot(x**2,-1,1)
sage: p.get_minmax_data()
{'xmin': -1.0, 'ymin': 1.2545281288559271e-05, 'ymax': 1.0, 'xmax': 1.0}

Hope it helps
Laurent


[1] www.sagemath.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: [2.5.1] Script to download and rename bunch of files?

2011-04-08 Thread Laurent Claessens

Le 08/04/2011 14:47, Gilles Ganault a écrit :

Hello,

Before I go ahead and learn how to write this, I was wondering if
someone knew of some source code I could use to download and rename a
bunch of files, ie. the equivalent of wget's -O switch?

I would provide a two-column list where column 1 would contain the
full URL, and column 2 would contain the name to use to rename the
file once downloaded.

Thank you.


The following puts in the string `a` the code of the page urlBase :

a = urllib.urlopen(urlBase).read()

Then you have to write `a` in a file.

There could be better way.

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-05-08 Thread Mali Laurent
On Apr 16, 5:20 am, Alec Taylor  wrote:
> Good Afternoon,
>
> I'm looking for an IDE which offers syntax-highlighting,
> code-completion, tabs, an embedded interpreter and which is portable
> (for running from USB on Windows).
>
> Here's a mockup of the app I'm looking for:http://i52.tinypic.com/2uojswz.png
>
> Which would you recommend?
>
> Thanks in advance for any suggestions,


What about geany?  I mostly use that.  And sometimes eclipse with
python support.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python backup programs?

2011-05-10 Thread Laurent Claessens

Le 11/05/2011 01:57, James Mills a écrit :
> On Wed, May 11, 2011 at 9:00 AM, Dan Stromberg 
wrote:

>>
>>  What are your favorite backup programs written, in whole or in part, in
>>  Python?

My favorite one is the one I wrote myself for myself ;)

The point I like :

1. the backup is a simple copy. I can retrieve it without any specific 
programs.
2. if a file changed, before to be copied, the backup file is moved to a 
specific repertory
   whose name is the date and hour. So if I destroy a file and backup 
the destroyed one, the old

   non-destroyed one is still available.
3. Since the program is anyway performing a long os.walk operation, in 
the same time, it performs `git commit`

   in the directories that need it.
4. My program is command-line only. Works fine in tty

Points that are of no importance (very personal and adapted to my 
specific case !) :


1. time. One backup takes between 10 minutes and one hour. I don't 
really care.
2. space. Since my backup is a copy (and copy of copies), my backup 
directory takes ~150Go

   while my home is about 25 Go.

Hope it answer your question.

Have a nice day
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens

In this case, the interpretation of an arbitrary object as a boolean
is peculiar for python.  An empty list is a real, existing object, and
the supposition that [] be false is counter-intuitive.  It can be
learnt, and the shorthand may be powerful when it is, but it will
confuse many readers.


Once I wrote something like:

def f(x=None):
   if x:
  print x
   else:
  print "I have no value"


The caller of that function was something like f(cos(2*theta)) where 
theta come from some computations.


Well. When it turned out that theta was equal to pi/4, I got "I have no 
value". I spent a while to figure out the problem :)


Conclusion: the boolean value of an object is to be used with care in 
order to tests if an optional parameter is given or not (when default 
value is None).



Have a good noon
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens



I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:


 theta = math.pi/4
 f(math.cos(2*theta))

6.12303176911e-17


Yes: its oversimplifued. The angle come from a normal vector of a curve 
and so on In particular, I was using Sage; the computations are 
exact: pi is pi and cos(pi) is zero.



 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).


Or, to put it another way: if you want to test for an object being None,
test for the object being None.


It was my conclusion too ;)

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-11 Thread Laurent Claessens



I believe you are grossly oversimplifying whatever code you had. Using
the definition of f from above:


 theta = math.pi/4
 f(math.cos(2*theta))

6.12303176911e-17


Yes: its oversimplifued. The angle come from a normal vector of a curve 
and so on In particular, I was using Sage; the computations are 
exact: pi is pi and cos(pi) is zero.



 Conclusion: the boolean value of an object is to be used with care in
 order to tests if an optional parameter is given or not (when default
 value is None).


Or, to put it another way: if you want to test for an object being None,
test for the object being None.


It was my conclusion too ;)

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a graph image

2011-05-13 Thread Laurent Claessens



Yes, I want to extract the data that is contained in an image file.
Greets


Maybe ask to imagemagick's or matplotlib. They should know if it is 
possible at all.


Good luck.
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a graph image

2011-05-13 Thread Laurent Claessens



Yes, I want to extract the data that is contained in an image file.
Greets


Maybe ask to imagemagick's or matplotlib. They should know if it is 
possible at all.


Good luck.
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a graph image

2011-05-13 Thread Laurent Claessens



Yes, I want to extract the data that is contained in an image file.
Greets


Maybe ask to imagemagick's or matplotlib. They should know if it is 
possible at all.


Good luck.
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a graph image

2011-05-13 Thread Laurent Claessens



Yes, I want to extract the data that is contained in an image file.
Greets


Maybe ask to imagemagick's or matplotlib. They should know if it is 
possible at all.


Good luck.
Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a graph image

2011-05-13 Thread Laurent Claessens



Yes, I want to extract the data that is contained in an image file.
Greets

Basti


> Yes, I want to extract the data that is contained in an image file.
> Greets

Maybe ask to imagemagick's or matplotlib. They should know if it is 
possible at all.


Good luck.
Laurent


--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a graph image

2011-05-13 Thread Laurent Claessens



I guess it requires some kind of image processing , where you can move around 
image pixel
by pixel and somehow figure out what color is present in that pixel .
If there isn’t much noise in the image you should sharp contrast and would
be able to differentiate between two colors ? if yes ( I don’t know matlab
>might provide some tools ..  just guessing ) then its easy i think to 
pick (X,Y) as time and value ?


You made me think that in addition to ask to imagemagick's and 
matplotlib, one can also as to Sage[1]


In order of pythonicity :
- matplotlib
- sage
- imagemagick's


Laurent

[1] www.sagemath.org

PS : Sorry for having send my previous answer 5 times. I don't understand :(
--
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters

2011-05-30 Thread Laurent Claessens

Le 29/05/2011 23:42, Ben Finney a écrit :

Peter Pearson  writes:


 Python works in terms of objects having names, and one
 object can have many names.


Or no names. So it's less accurate (though better than talking of
“variables”) to speak of Python objects “having names”.


Could you give an example of an object that has no name ? I've missed 
something ...


Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters

2011-05-30 Thread Laurent Claessens

Le 30/05/2011 11:02, Terry Reedy a écrit :

On 5/30/2011 3:38 AM, Laurent wrote:


 Cool. I was thinking that "5" was the name, but
  >>>  5.__add__(6)
 File "", line 1
 5.__add__(6)



Try 5 .__add__(6)


What is the rationale behind the fact to add a space between "5" and 
".__add__" ?

Why does it work ?

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters

2011-05-30 Thread Laurent Claessens



 What is the rationale behind the fact to add a space between "5" and
 ".__add__" ?
 Why does it work ?


It's a hint for the tokenizer.


I didn't know the tokenizer. Now I understand.
Thanks

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


Re: scope of function parameters

2011-05-30 Thread Laurent Claessens



 What is the rationale behind the fact to add a space between "5" and
 ".__add__" ?
 Why does it work ?


It's a hint for the tokenizer.


I didn't know the tokenizer. Now I understand.
Thanks

Laurent
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] German translation of Python 3 Cheat Sheet

2016-09-14 Thread Laurent Pointal
Hello,

The Python 3 Sheet Cheat (Mémento Bases Python 3) has been 
translated into german by StR Martin Putzlocher. Thanks to him.

It can be downloaded on the same page as english and french
versions: https://perso.limsi.fr/pointal/python:memento

A+
L.Pointal.
-- 
https://mail.python.org/mailman/listinfo/python-list


Update to Python 3 Cheat Sheet

2017-01-28 Thread Laurent Pointal
Hi,

I updated the cheat sheet on the aesthetic side. Parts bloc and their 
title are now more easily identified with colors (but its nice with B&W 
printing too).
French and german versions have also been updated.

See https://perso.limsi.fr/pointal/python:memento

A+
L.Pointal.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: After a year using Node.js, the prodigal son returns

2016-05-07 Thread Laurent Pointal
Chris Angelico wrote:

> On Fri, May 6, 2016 at 11:45 PM, Grant Edwards
>  wrote:
>>> JavaScript is terrible. Really, really bad. And because of that, it
>>> has the potential to sweep the world.
>>
>> If your reasoning is correct, it'll never be able to overtake PHP.
>>
>> I've never written anything over a hundred or two lines in JavaScript,
>> but for small stuff it seems OK -- though as others have noted there
>> are some oddly missing batteries that result in use of a lot of small
>> external libraries for things that any C, PHP, or Python user would
>> have expected to be in the standard library.
> 
> Except that it's pretty easy to switch out PHP for Python, or anything
> else. JavaScript is what it is because it's hard to just use a
> different language.

Maybe Pyhton, using Brython (http://www.brython.info/)

(ok, its translated into JavaScript for execution in the web browser… maybe 
somedays it will be asmsjs)

A+
Laurent.

-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   >