Re: Code coverage to Python code

2009-01-05 Thread Kay Schluehr
On 4 Jan., 12:35, Hussein B  wrote:
> Hey,
> What is the best code coverage tool available for Python?
> Thanks.

It depends. What are your requirements?
--
http://mail.python.org/mailman/listinfo/python-list


Re: AttributeError: 'tuple' object has no attribute 'lstrip'

2009-01-05 Thread John Machin
On Jan 5, 6:15 pm, Gilles Ganault  wrote:
> Hello
>
>         I successfully use the email package to send e-mail from Python
> scripts, but this script fails when I fetch addresses from an SQLite
> database where data is Unicode-encoded:
>
> ==
> from email.MIMEText import MIMEText
> import smtplib,sys
> import apsw
>
> connection=apsw.Connection("test.sqlite")
> cursor=connection.cursor()
>
> subject = "My subject"
> f = open("message.txt", "r")
> message = f.read()
> f.close()
>
> msg = MIMEText(message)
>
> msg['Subject'] = subject
> From = "m...@acme.com"
> msg['From'] = From
>
> server = smtplib.SMTP("smtp.acme.com")
>
> sql="SELECT email FROM people WHERE email IS NOT NULL"
> rows=list(cursor.execute(sql))
> for email in rows:
>         To = email
>         msg['To'] = email
>
>         #print To
>         #(u'du...@acme.com',)

That looks like a tuple to me. What does it look like to you?

>
>         #AttributeError: 'tuple' object has no attribute 'lstrip'
>         #server.sendmail(From,[To],msg.as_string())

When are asking for help, could you *PLEASE* supply the actual code
that you ran, with the actual output, and (just in case the problem is
not otherwise screamingly obvious) the *FULL* traceback?

The to_addrs arg of SMTP.sendmail() should be a single string, or a
list of strings. You have supplied [(u'du...@acme.com',)] which is a
list containing one tuple. That tuple is a result of your SQL query,
which has returned a 1-column row as a tuple (as expected/documented).
SMTP.sendmail() treats your tuple as though it were a string, and
consequently an exception is raised.

> server.quit

Should that perhaps be server.quit() ?

> Does email choke on Unicode?

I've got no idea; I've never used email or smtplib. Why don't you feed
them some Unicode and find out? Also consider having a look at the
manual.

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Erik Max Francis

Derek Martin wrote:


On Sun, Jan 04, 2009 at 09:30:20PM -0500, Steve Holden wrote:

I'm going to go out on a limb and assert that there's NO POSSIBLE WAY
a student could intuit Python's variable assignment behavior, having
never been exposed to that same behavior prior.  It needs to be
taught.

As does assignment of any kind. 


I'm not sure that's true.  Having taken algebra prior to learning Basic,
I intuitively understood what this program would do when I executed
it, the first time I saw the code, and before I read the explanation:

10 let x = 10
20 print x


Did you understand that the first time you saw the statement in BASIC:

X = X + 1

the = symbol couldn't possibly have the same meaning as it does in 
algebra?  In BASIC, this is a statement which replaces the value of a 
variable X with the previous value, incremented by one.  In algebra, 
this is an equation which has no solutions, since it reduces to 0 = 1, 
an equation which is inconsistent.  The two things aren't even related.


That is the whole point here.  Computer science and programming 
languages have objects.  Mathematics has no such concept whatsoever, 
unless you wish to define one.  You're welcome to do so with a rigorous 
definition that you can publish papers about and decide whether other 
mathematicians are interested in your line of reasoning, but pretending 
that there is a natural overlap between the mathematical concepts of 
equality and identity and the computer scientific ones (especially since 
the term _identity_ isn't even used in remotely the same way) is simply 
ignoring the fact that other people either won't know what you mean or 
will presume you're misunderstanding something.  Because, based on your 
previous comments, you are.


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  Do we ask what profit the little bird hopes for in singing?
   -- Johannes Kepler, 1571-1630
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Steven D'Aprano
On Sun, 04 Jan 2009 20:03:11 -0600, Derek Martin wrote:


> I am happily ignorant of C#.  As for Java, take the following code:
> 
>   a = 6;
>   a = 5;
> 
> In Python, when you execute the equivalent code, it causes two different
> objects to spring into existence, the first of which may be cleaned up
> by the GC (except that since we're using small integers, that's not
> likely to happen).  Unless I'm misinformed (which is very possible, my
> experience with Java has been extremely limited) in Java that's not the
> case...  the storage is allocated to the name a when you execute its
> declaration, and the *same storage* is reused upon subsequent
> assignment.
> 
> That behaves exactly like named bins.

In the case of Java, that's because Java uses two assignment models: 
named bins for "primitives" like ints and floats, and the Python model 
for class instances, which is *nearly* everything in Java except a few 
primitive types.



>> > And for that matter, it's pretty unintuitive generally.
>> 
>> Names and objects are quite "natural" IMHO.  There are many real world
>> objects which we attach one or more names to, or refer to in sequences
>> like "please give me the third book on that shelve" (``shelve[2]``).
> 
> Indeed, but the way we assign names to them does not behave as it does
> in Python.

It doesn't? 

Oh my, you're going to be confused in a few weeks when The President of 
the USA ceases to be George W Bush and becomes Barack Obama. Same name 
(or rather, title), different object (person).



> Nor does Python's assignment work like it does in algebra,

Nor does any programming language, with the possible exception of 
computer algebra systems.


> or anywhere else the Python student is particularly likely to have seen
> variable assignment before encountering it in Python.  Let's define
> intuitive, shall we?  From dictionary.com (choosing the definition which
> most easily makes my point):
> 
>   intuitive: adj.  capable of being perceived or known by intuition.
> 
> I'm going to go out on a limb and assert that there's NO POSSIBLE WAY a
> student could intuit Python's variable assignment behavior, having never
> been exposed to that same behavior prior.

Unless they've used Java, Perl, Ruby, or any number of other languages.

> It needs to be taught.

Exactly the same as the named bins assignment model needs to be taught.

But, really, you're exaggerating the differences. There are differences 
of course, but for somebody writing a simple programming with (say) 
mathematical expressions, there's little or no difference between the 
models.

x = 4
if y > 2:
x = x-1
else:
x = x+1
print x+y

will have the same effect whether you are using the named bins model or 
not.



[...]
> I cheerfully disagree. :)  "Named bins" is essentially how algebra
> works, 

I don't think so. Variables in algebra are quite different from variables 
in programming languages. Contrast the statement:

x = x+1

as a programming expression and an algebraic equation. As a programming 
expression, it means "increment x by one". But as an algebraic 
expression, it means "x is some value such that it is equal to one more 
than itself", and there is no solution to such an equation.

In algebra, a variable name (like x, or c) generally represents one of 
three things:

(1) an an unknown quantity to be solved for;

(2) a constant (either a known constant, or an arbitrary parameter); or 

(3) an alias, such as when you do a change-of-variable.

One thing which algebraic variables are not is a bucket or bin that you 
can set to some value, then modify over and over again.


> and how several generations of computer languages, not to mention
> the actual machine language those generated, behaved, before the current
> crop.

Sure. And?

> Those interpretations came first, because, much as in the
> evolution of any other science, that was the model which was most
> intuitive or easily explained.

No no no no. That was the model that was most easily implemented!

Before the named bins model of assignment was pure machine code, where 
you didn't have bins at all, just bits, and there was no distinction 
between code and data. And before that was *wires* -- early programmers 
literally had to plug and unplug wires to change the state of the 
computer. And before that were purely mechanical devices, such as the 
Enigma Machine, old calculators, and the grand-daddy of them all, Charles 
Babbage's difference engine and it's precursors.



> But you need not take my word for it.  Simply read the archives and see
> for yourself how much confusion this has caused on this list. [Please
> include the closely related behavior of parameter passing in your
> search.]

In my opinion, the cause of that confusion is nothing to do with Python's 
assignment model, and everything to do with the instance of some people 
to use named bins terminology when describing the Python model. If you 
keep the named bins terminology for describing the 

Tkinter - problem closing window

2009-01-05 Thread Djames Suhanko
Hello!
I'm sorry my terrible english (my native language is portuguese).
I has a litle program that open another window. When I close de root
window in quit button, I need clicking 2 times to close. is where the
problem?

The source:
  1 #!/usr/bin/env python
  2 from Tkinter import *
  3 import sys
  4 import random
  5 class App:
  6  def __init__(self, master):
  7frame = Frame(master)
  8frame.pack()
  9rotulo = Label(frame, text="Clique em 'Gerar' e boa
sorte!",borderwidth=2,bg="gray",justify=CENTER,relief=SUNKEN)
 10rotulo.pack()
 11
 12self.button = Button(frame, text="Sair", fg="red",
command=frame.quit,borderwidth=1)
 13self.button.pack(side=LEFT)
 14self.hi_there = Button(frame, text="Gerar Numero",
command=self.say_hi,borderwidth=1)
 15self.hi_there.pack(side=RIGHT,padx=2,pady=2)
 16
 17  def gera_seis(self):
 18a = {}
 19for i in range(6):
 20   a[i] = "%02d" %  int (random.randint(0,60))
 21resultadoA = "%s-%s-%s-%s-%s-%s" %
(str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5]))
 22return resultadoA
 23
 24  def say_hi(self):
 25resultado = self.gera_seis()
 26raiz = Tk()
 27F = Frame(raiz)
 28F.pack()
 29hello = Label(F, text=resultado)
 30hello.pack()
 31F.mainloop()
 32
 33 root = Tk()
 34 root.title("$$$ Loteria $$$")
 35 app = App(root)
 36 root.mainloop()

-- 
Djames Suhanko
LinuxUser 158.760
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter - problem closing window

2009-01-05 Thread Peter Otten
Djames Suhanko wrote:

> Hello!
> I'm sorry my terrible english (my native language is portuguese).
> I has a litle program that open another window. When I close de root
> window in quit button, I need clicking 2 times to close. is where the
> problem?
> 
> The source:
>   1 #!/usr/bin/env python
>   2 from Tkinter import *
>   3 import sys
>   4 import random
>   5 class App:
>   6  def __init__(self, master):
>   7frame = Frame(master)
>   8frame.pack()
>   9rotulo = Label(frame, text="Clique em 'Gerar' e boa
> sorte!",borderwidth=2,bg="gray",justify=CENTER,relief=SUNKEN)
>  10rotulo.pack()
>  11
>  12self.button = Button(frame, text="Sair", fg="red",
> command=frame.quit,borderwidth=1)
>  13self.button.pack(side=LEFT)
>  14self.hi_there = Button(frame, text="Gerar Numero",
> command=self.say_hi,borderwidth=1)
>  15self.hi_there.pack(side=RIGHT,padx=2,pady=2)
>  16
>  17  def gera_seis(self):
>  18a = {}
>  19for i in range(6):
>  20   a[i] = "%02d" %  int (random.randint(0,60))
>  21resultadoA = "%s-%s-%s-%s-%s-%s" %
> (str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5]))
>  22return resultadoA
>  23
>  24  def say_hi(self):
>  25resultado = self.gera_seis()
>  26raiz = Tk()
>  27F = Frame(raiz)
>  28F.pack()
>  29hello = Label(F, text=resultado)
>  30hello.pack()
>  31F.mainloop()

You need only one mainloop(). Remove line 31 and you should be OK.

>  32
>  33 root = Tk()
>  34 root.title("$$$ Loteria $$$")
>  35 app = App(root)
>  36 root.mainloop()

Peter 

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


Re: My last working day of 2007

2009-01-05 Thread skip

Jack> It's simple, a small program running on background, logging the
Jack> title of foreground window. A python script parses the log file
Jack> and then generates chart by matplotlib.

Jack> I just want to get suggestions to improve it, or know the news
Jack> that somebody had implemented a better one so I can abandon my
Jack> toy.

For starters, you might figure out how to make it work on a real operating
system which allows multiple active processes.

Nudge, nudge.  Wink, wink.  Say no more.  Say no more. ;-)

-- 
Skip Montanaro - s...@pobox.com - http://smontanaro.dyndns.org/
--
http://mail.python.org/mailman/listinfo/python-list


Python return values

2009-01-05 Thread koranthala
I have a newbie doubt about Python return values.

In (say) C/C++, if we try to return a value which is stored inside the
procedure stack, we will get an error when trying to access it outside
of that procedure.
For example:
function foo():
   dcl y int
   dcl x pointer to int pointing to y
   return x


function bar():
   x = foo()
   ...
   use x

This will error out since the memory has be taken back.

Now, in Python, we do it everytime, because all variables are
references, and even returns just copies the references.
function pyfoo():
  return 786

function pyfoo1():
  x = xclass()
  return x

function pybar():
  x = pyfoo()
  y = pyfoo1()
  ...
  use x, y

Why doesnt it error out?
--
http://mail.python.org/mailman/listinfo/python-list


Re: reflection as in Java: how to create an instance from a classname

2009-01-05 Thread Bruno Desthuilliers

guss a écrit :

I cannot find a satisfying answer to this question on the web so let's
try here.

My problem is the following, I would like to instantiate some object
from a configuration file that would contain class names like for
example classname=org.common.resource.MyResource.
Here my resource is the class to instanciate and it is in the module
resource that is in a package hierachy.

In fact I would like to do something very similar to the Java:

klass = Class.forname("org.common.resource.MyResource")

instance = klass.newInstance()

The second line is easy once I have a classobj but I have some
problems to find the right recipe for getting it.

I know how to create a class from scratch with new.classobj but how do
you get a class object and then create an object ?

I would like a recipe working for all cases (whatever the module is
not the local one ...)


use __import__ to get the module object, then getattr(module, classname) 
to get the class object (sorry, no much time right now to give you a 
full recipe, but that should be enough to get you started).


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


Re: Tkinter - problem closing window

2009-01-05 Thread Roger
On Jan 5, 11:52 am, Collin D  wrote:
> On Jan 5, 6:25 am, "Djames Suhanko"  wrote:
>
>
>
> > Hello!
> > I'm sorry my terrible english (my native language is portuguese).
> > I has a litle program that open another window. When I close de root
> > window in quit button, I need clicking 2 times to close. is where the
> > problem?
>
> > The source:
> >   1 #!/usr/bin/env python
> >   2 from Tkinter import *
> >   3 import sys
> >   4 import random
> >   5 class App:
> >   6  def __init__(self, master):
> >   7    frame = Frame(master)
> >   8    frame.pack()
> >   9    rotulo = Label(frame, text="Clique em 'Gerar' e boa
> > sorte!",borderwidth=2,bg="gray",justify=C    ENTER,relief=SUNKEN)
> >  10    rotulo.pack()
> >  11
> >  12    self.button = Button(frame, text="Sair", fg="red",
> > command=frame.quit,borderwidth=1)
> >  13    self.button.pack(side=LEFT)
> >  14    self.hi_there = Button(frame, text="Gerar Numero",
> > command=self.say_hi,borderwidth=1)
> >  15    self.hi_there.pack(side=RIGHT,padx=2,pady=2)
> >  16
> >  17  def gera_seis(self):
> >  18    a = {}
> >  19    for i in range(6):
> >  20       a[i] = "%02d" %  int (random.randint(0,60))
> >  21    resultadoA = "%s-%s-%s-%s-%s-%s" %
> > (str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5]))
> >  22    return resultadoA
> >  23
> >  24  def say_hi(self):
> >  25    resultado = self.gera_seis()
> >  26    raiz = Tk()
> >  27    F = Frame(raiz)
> >  28    F.pack()
> >  29    hello = Label(F, text=resultado)
> >  30    hello.pack()
> >  31    F.mainloop()
> >  32
> >  33 root = Tk()
> >  34 root.title("$$$ Loteria $$$")
> >  35 app = App(root)
> >  36 root.mainloop()
>
> > --
> > Djames Suhanko
> > LinuxUser 158.760
>
> Also for style, you might want to group the import lines so they look
> like this:
>
> from Tkinter import *
> import sys, random
>
> A bit more pythonic. :P

In that case you probably want to take out the 'from' import and:

import Tkinter, sys, random

in order to avoid any namespace issues especially if you have a large
project with lots of gui manipulations.  But that's just me being
pedantic. ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python callback functions and static methods

2009-01-05 Thread MRAB

Joris wrote:

Hello,

I'm trying to implement callback functionality in a static class.

I have a feeling that I'm doing something against the Python philosophy 
and not some programming error but any help would be appreciated.


First, a piece of proof-of-concept-code:
*
class Data:

callfunc = None

@staticmethod
def setCallBack(callfunc):
Data.callfunc = callfunc

@staticmethod
def OnData(data):
Data.callfunc(data)

def DataCallback(a):
print 'I received some data: '+ a
   
Data.setCallBack(DataCallback)

Data.OnData('I have new data')
*

I have defined a class called Data, which I want to use as a "static" 
class (i.e. I will never create an instance of it). (I come from a Java 
background so forgive me calling this static)

It contains a class variable and 2 static methods.

I also defined a separate function called DataCallback, which would just 
print the data it receives.


The goal of this is to use the Data class as a dispatcher of some chunk 
of data to whatever function I would like, settable at run-time.


When executing this script, following error occurs:

*Traceback (most recent call last):
  File "callback.py", line 17, in 
Data.OnData('I have new data')
  File "callback.py", line 11, in OnData
Data.callfunc(data)
TypeError: unbound method DataCallback() must be called with Data 
instance as first argument (got str instance instead)

*
What I don't understand is why Python is expecting me to call the 
DataCallback() function with a Data instance. To my understanding, the 
DataCallback() function can be called from a static method and thus does 
not require any instance.


Can anyone point me in the right direction ?


DataCallback isn't a static method, it's a plain function. Try this instead:

class Data:
...
@staticmethod
def setCallBack(callfunc):
Data.callfunc = staticmethod(callfunc)
...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python callback functions and static methods

2009-01-05 Thread Chris Rebert
On Mon, Jan 5, 2009 at 9:00 AM, Joris  wrote:
> Hello,
>
> I'm trying to implement callback functionality in a static class.
>
> I have a feeling that I'm doing something against the Python philosophy and
> not some programming error but any help would be appreciated.
>
> First, a piece of proof-of-concept-code:
>
> class Data:
>

The call to setCallBack effectively makes it as though you'd done this
(note that we're within the class body):

def callfunc(a):
 print 'I received some data: '+ a

Obviously this method is not "static" in the Java sense, hence the
error about not being called with an instance. Here are my suggested
changes:

>
 @classmethod #class methods are closer to Java "static" methods;
Python static methods are just functions in a class
 def setCallBack(cls, callfunc):
 cls.callfunc = staticmethod(callfunc)
>
 @classmethod
 def OnData(cls, data):
 cls.callfunc(data)
>
>
> def DataCallback(a):
> print 'I received some data: '+ a
>
> Data.setCallBack(DataCallback)
> Data.OnData('I have new data')
>
>

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: reflection as in Java: how to create an instance from a classname

2009-01-05 Thread Quentin Gallet-Gilles
On Mon, Jan 5, 2009 at 5:34 PM, Bruno Desthuilliers
 wrote:

> guss a écrit :
>
>> I cannot find a satisfying answer to this question on the web so let's
>> try here.
>>
>> My problem is the following, I would like to instantiate some object
>> from a configuration file that would contain class names like for
>> example classname=org.common.resource.MyResource.
>> Here my resource is the class to instanciate and it is in the module
>> resource that is in a package hierachy.
>>
>> In fact I would like to do something very similar to the Java:
>>
>> klass = Class.forname("org.common.resource.MyResource")
>>
>> instance = klass.newInstance()
>>
>> The second line is easy once I have a classobj but I have some
>> problems to find the right recipe for getting it.
>>
>> I know how to create a class from scratch with new.classobj but how do
>> you get a class object and then create an object ?
>>
>> I would like a recipe working for all cases (whatever the module is
>> not the local one ...)
>>
>
> use __import__ to get the module object, then getattr(module, classname) to
> get the class object (sorry, no much time right now to give you a full
> recipe, but that should be enough to get you started).
>
> HTH
>


A longer version of Bruno's idea can be found here :
http://mail.python.org/pipermail/python-list/2003-March/192221.html

Cheers,
Quentin
--
http://mail.python.org/mailman/listinfo/python-list


My last working day of 2007

2009-01-05 Thread Jack.Chu
Hello guys:
I created a simple tool to count how I wasted my time day by day ;-)
http://www.flickr.com/photos/34017...@n07/3169438647/sizes/o/

It's simple, a small program running on background, logging the title
of foreground window. A python script parses the log file and then
generates chart by matplotlib.

I just want to get suggestions to improve it, or know the news that
somebody had implemented a better one so I can abandon my toy.

thanks.


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


Re: How to "kill" orphaned threads at program exit

2009-01-05 Thread BlueBird
On Dec 28 2008, 6:33 pm, "Giampaolo Rodola'"  wrote:
> Hi,
> I know that it's not possible to "kill" threads but I'm wondering if
> does exist some workaround for my problem.
> I have a test suite which does a massive usage of threads.
> Sometimes happens that one test fails, the test suite keeps running
> until the end, and when it's finished the program hangs on and the
> only way to stop is to kill it manually.
> I noticed that, at the end of the program, I can call
> threading.enumerate() and see the pending thread objects:
>

Hi,

The way I handle it is to make sure that after each test, the thread
count has returned to what I expect.

It is possible to kill a thread if it's not blocked on a system call.
It's highly unrecommended for standard usage but your use case exactly
the one where the ability to kill a thread is very useful.

I use the following code, which I borrowed to the Python Cook book
somewhere:

def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in
trouble,
# and you should call it again with exc=NULL to revert the
effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError("PyThreadState_SetAsyncExc failed")


class ThreadWithExc(threading.Thread):
'''A thread class that supports raising exception in the thread
from another thread.
'''
def _get_my_tid(self):
"""determines this (self's) thread id

CAREFUL : this function is executed in the context of the
caller thread,
to get the identity of the thread represented by this
instance.
"""
if not self.isAlive():
raise threading.ThreadError("the thread is not active")

# do we have it cached?
if hasattr(self, "_thread_id"):
return self._thread_id

# no, look for it in the _active dict
for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid

# TODO : in python 2.6, there's a simpler way to do :
self.ident ...

raise AssertionError("could not determine the thread's id")

def raiseExc(self, exctype):
"""Raises the given exception type in the context of this
thread.

If the thread is busy in a system call (time.sleep(),
socket.accept(), ...) the exception
is simply ignored.

If you are sure that your exception should terminate the
thread, one way to ensure that
it works is:
t = ThreadWithExc( ... )
...
t.raiseExc( SomeException )
while t.isAlive():
time.sleep( 0.1 )
t.raiseExc( SomeException )

If the exception is to be caught by the thread, you need a way
to check that your
thread has caught it.

CAREFUL : this function is executed in the context of the
caller thread,
to raise an excpetion in the context of the thread represented
by this instance.
"""
_async_raise( self._get_my_tid(), exctype )



   cheers,

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


Re: socket send help

2009-01-05 Thread Gabriel Genellina
En Sat, 03 Jan 2009 21:44:34 -0200, Bryan Olson   
escribió:



Gabriel Genellina wrote:

greyw...@gmail.com escribió:

[...]

A simple server:

from socket import *
myHost = ''
 Try with myHost = '127.0.0.1' instead - a firewall might be blocking  
your server.


Just a nit: I'd say the reason to use '127.0.0.1' instead of the empty  
string is that a firewall might *not* be blocking your server.


The Python sockets module interprets the empty string as INADDR_ANY,  
which means to bind to all available adapters including the loopback,  
A.K.A localhost, A.K.A '127.0.0.1'.


I thought a firewall would block an attempt to bind to any routeable  
address, but not to localhost. So using INADDR_ANY would be rejected.


--
Gabriel Genellina

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


Re: cx_Oracle issues

2009-01-05 Thread huw_at1
On Dec 18 2008, 10:34 am, huw_at1  wrote:
> On Dec 16, 12:17 pm, huw_at1  wrote:
>
>
>
> > On Dec 15, 12:59 pm, "ron.re...@gmail.com" 
> > wrote:
>
> > > On Dec 15, 2:44 am, huw_at1  wrote:
>
> > > > On Dec 11, 5:34 pm, "ron.re...@gmail.com"  wrote:
>
> > > > > On Dec 10, 9:48 am, huw_at1  wrote:
>
> > > > > > Hey all. When usingcx_Oracleto run a procedure like:
>
> > > > > > cursor.execute("select (obj.function(value)) from table where
> > > > > > id=blah")
>
> > > > > > I am getting the following error:
>
> > > > > > ORA-06502: PL/SQL: numeric or value error: character string buffer 
> > > > > > too
> > > > > > small ORA-06512: at line 1
>
> > > > > > Looking at cursor.description I get:
>
> > > > > > [('(obj.function(value))', , 4000, 4000, 0,
> > > > > > 0, 1)]
>
> > > > > > Any tips - i have never seen this error before but am guessing that
> > > > > > the value being returned is too big for the buffer size set for the
> > > > > > cursor. the procedure fetches data from a LOB.
>
> > > > > > Any suggestions/confirmations?
>
> > > > > > Many thanks
>
> > > > > This error is a problem with the PL/SQL, notcx_Oracle.  You need to
> > > > > debug obj.function to see what kind of data is being accessed and then
> > > > > a data analysis of that data to understand why this error occurs.  I
> > > > > can tell you the function is most likely expecting characters from a
> > > > > column that are numeric [0 .. 9] and is getting alpha characters.
>
> > > > > --
> > > > > Ron Reidy
> > > > > Sr. Oracle DBA
>
> > > > Hi thanks for the responses. Unfortunately the procedure in question
> > > > is from a third party vendor so I can't really debug it so I'd say I
> > > > was fairly stumped. Just out of interest how do you increase the
> > > > output buffer size withcx_Oracle?
>
> > > > Many thanks- Hide quoted text -
>
> > > > - Show quoted text -
>
> > > Hi,
>
> > > Sure you can.  You can see the PL/SQL source from the ditionary view
> > > ALL_SOURCE:
> > > select text from all_source where name = 'NAME_OF_FUNCTION';
>
> > > From there, reverse engineeer which table(s) and column(s) are being
> > > accesses and do the data analysis.
>
> > > --
> > > Ron Reidy
>
> > Hi all,
>
> > So I tried Rons query but unfortunately I got 0 records returned.
> > However I can confirm that running the select query from a client does
> > indeed generate the same error. Is there anything else I could try?
> > Otherwise I'll just get in touch with the vendor I guess.
>
> Hi again. A further update to theseissuesis that I found some java
> executable which seemed to execute the SQL query without hitch. My
> Java isn't great but from what I could make out it seems that the
> query is broken down from:
>
> select (obj.function(value)) from table where id=blah
>
> to:
>
> select value from table where id=blah
>
> obj.function(value)
>
> So make two queries. In the first retrieve the BLOB (value) and store
> it in a java.sql.blob object. Then pass this back in to the stored
> procedure. I'm a bit puzzled as to why this way would work over just
> performing the straight select statement. Culd it be the jdbc
> connector handles BLOBs better? Anyway I was wondering if I could
> implement something similar usingcx_Oracle. however I am a bit stuck
> on how to pass a BLOB in to the second query - specifically:
>
> cursor.execute(obj.function(value))
>
> where value is the BLOB. I get an error:
>
> cx_Oracle.NotSupportedError: Variable_TypeByValue(): unhandled data
> typecx_Oracle.LOB
>
> So I wonder if I need to set something for the input type but I do not
> know how to do this.
>
> Any suggestions?
>
> Many thanks again.

Hi there. Any suggestions? I'm still a bit stuck on this one?

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


Re: Python callback functions and static methods

2009-01-05 Thread Jean-Paul Calderone

On Mon, 5 Jan 2009 18:00:37 +0100, Joris  wrote:

Hello,

I'm trying to implement callback functionality in a static class.

I have a feeling that I'm doing something against the Python philosophy and
not some programming error but any help would be appreciated.



Others have explained what was wrong with your `Data` class, so I won't
bother going into that.

I will recommend that you take a look at Deferred and perhaps use it, rather
than implementing something yourself:

http://twistedmatrix.com/projects/core/documentation/howto/defer.html

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


Re: Python callback functions and static methods

2009-01-05 Thread Steve Holden
Joris wrote:
> Hello,
> 
> I'm trying to implement callback functionality in a static class.
> 
> I have a feeling that I'm doing something against the Python philosophy
> and not some programming error but any help would be appreciated.
> 
> First, a piece of proof-of-concept-code:
> *
> class Data:
> 
> callfunc = None
> 
> @staticmethod
> def setCallBack(callfunc):
> Data.callfunc = callfunc
> 
> @staticmethod
> def OnData(data):
> Data.callfunc(data)
> 
> def DataCallback(a):
> print 'I received some data: '+ a
>
> Data.setCallBack(DataCallback)
> Data.OnData('I have new data')
> *
> 
> I have defined a class called Data, which I want to use as a "static"
> class (i.e. I will never create an instance of it). (I come from a Java
> background so forgive me calling this static)
> It contains a class variable and 2 static methods.
> 
> I also defined a separate function called DataCallback, which would just
> print the data it receives.
> 
> The goal of this is to use the Data class as a dispatcher of some chunk
> of data to whatever function I would like, settable at run-time.
> 
> When executing this script, following error occurs:
> 
> *Traceback (most recent call last):
>   File "callback.py", line 17, in 
> Data.OnData('I have new data')
>   File "callback.py", line 11, in OnData
> Data.callfunc(data)
> TypeError: unbound method DataCallback() must be called with Data
> instance as first argument (got str instance instead)
> *
> What I don't understand is why Python is expecting me to call the
> DataCallback() function with a Data instance. To my understanding, the
> DataCallback() function can be called from a static method and thus does
> not require any instance.
> 
> Can anyone point me in the right direction ?
> 
Although other posters have pointed out your mistake in strict terms, I
would like to suggest that as long as you never intend to instantiate
the class you would be better off without it, defining this
functionality as a module and using the nodule global namespace instead
of the class namespace. Something like this:

callfunc = None

def setCallBack(f):
global callfunc
callfunc = f

def OnData(data):
callfunc(data)

if __name__ == "__main__":
def DataCallback(a):
print "I received this data:", a
setCallBack(DataCallback)
OnData("I have new data")
OnData("And here's some more!")

In other words, I'm not sure what you feel the class organization is
buying you.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: f.seek() unwanted output

2009-01-05 Thread Tim Chase

I'm having trouble with a script that is printing the output of f.seek
() 

[snip]

I have a file in memory.
when i try f.seek(0) #or any other value in f.tell()
it gives me 0 as output:

the following script illustrates my 'problem'

for a in range(10):

f.seek(a)


0
1
2
3
4
5
6
7
8
9


You're seeing an artifact of the command-line (evidenced by your 
">>>" before your command).  Just like


  int("42")

returns output...the Python console prints the output while a 
script (saved to the disk) doesn't.


Try putting your test in foo.py and running that -- you'll notice 
that it doesn't echo back the numbers as you describe.


The behavior seems to vary.  In my Python2.4, seek() for 
file/cStringIO/StringIO objects returns None with each. 
Whichever version (or object-type) you're using seems to return 
its input offset as its output.


-tkc




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


Re: threading a 10 lines out of a file

2009-01-05 Thread Steve Holden
alex goretoy wrote:
> I've found a great example on how to do threads. It compares a ping
> program in regular for loop and with threaded for loop. The link is
> below if anyone is interested.
> 
> http://www.wellho.net/solutions/python-python-threads-a-first-example.html
> 
> I hope my eagerness to post doesn't annoy anyone. I like to get as much
> info from as many places as possible and compare. This way I think I may
> have a better solution for a problem. Plus people that Google will find
> this post or any words in it. Any more information on threading a for
> loop would be greatly appreciated. TIA
> 
Your understanding that such eagerness can become annoying if taken too
far is appreciated. So far I haven't heard anyone suggest you should
move to comp.lang.somewhere-noobs-get-flamed ...

Be aware, however, that the CPython implementation won't net you any
benefit if all threads are CPU-bound, since due to something called the
GIL (global interpreter lock) no two threads will run concurrently.

If you search my past posts on threading you will doubtless find a
couple where I've posted my standard example. I don't want to bore
long-time readers (any more than I normally do) by repeating it yet again.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


f.seek() unwanted output

2009-01-05 Thread thomasvang...@gmail.com
I'm having trouble with a script that is printing the output of f.seek
() whereas in the documentation it is quoted not to have any output:


file.seek(offset[, whence])¶

Set the file’s current position, like stdio‘s fseek. The whence
argument is optional and defaults to os.SEEK_SET or 0 (absolute file
positioning); other values are os.SEEK_CUR or 1 (seek relative to the
current position) and os.SEEK_END or 2 (seek relative to the file’s
end). There is no return value.
--

I have a file in memory.
when i try f.seek(0) #or any other value in f.tell()
it gives me 0 as output:

the following script illustrates my 'problem'
>>> for a in range(10):
f.seek(a)


0
1
2
3
4
5
6
7
8
9
>>>

I don't want python to produce output when setting the file pointer.
Any help woul be appreciated.
Kind regards,
Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Steve Holden
Derek Martin wrote:
> On Sun, Jan 04, 2009 at 09:56:33PM -0600, Grant Edwards wrote:
>> On 2009-01-05, Derek Martin  wrote:
>>> On Sat, Jan 03, 2009 at 11:38:46AM -0600, Grant Edwards wrote:
 One presumes that Mr. Martin finds anything different from his
 first computer language to be BIZARRE.  He should try out
 Prolog or something genuinely different.
>>> One's presumption would be mistaken.  However thank you for
>>> illustrating my point so precisely, which was after all the
>>> condescending and insulting way people "communicate" with
>>> people whom (they think) know less than they do in this forum,
>>> and not actually how difficult or easy the assignment model of
>>> Python is to understand.
>> I'm sorry, but I really don't see how Python's assignment model
>> could be considered bizarre by anybody who's familiar with more
>> than one or two languages.  
> 
> And... what if one wasn't?  The OP of this thread clearly didn't
> understand... Whereas if you've read the thread, clearly I do.
> Of course, had you read my post, you probably would have understood
> that my comment about the model being bizarre was intended to be
> viewed from the perspective of someone who *had not* seen anything
> like it before, which is LOTS of relatively new programmers, whether
> or not it might be old hat to anyone here.   The ultimate point of my
> post was not so much about whether the assignment model of Python was
> or wasn't easy to understand; it was about the idea that when someone
> doesn't understand, we should try to help them instead of making snide
> remarks about how stupid or small-minded they are.

Even if they really are small-minded or stupid I agree this wouldn't be
helpful behavior. But neither would your characterization of Python's
assignment model as "bizarre" (even ignoring that you SHOUTED IT AT US),
and I have yet to see you admit that such a characterization was, shall
we say, inappropriate.

It takes little to admit one is in the wrong even when one isn't. I've
had to learn to do it because I often *am* wrong about things. Could you
be persuaded to consider the possibility that you met with a somewhat
hostile reaction (whether or not such a reaction was useful or
necessary) because you were, in a small way, poking people in the side
with a sharp stick?

If you couldn't I might find that a *little* bizarre.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Python callback functions and static methods

2009-01-05 Thread Joris
Hello,

I'm trying to implement callback functionality in a static class.

I have a feeling that I'm doing something against the Python philosophy and
not some programming error but any help would be appreciated.

First, a piece of proof-of-concept-code:
*
class Data:

callfunc = None

@staticmethod
def setCallBack(callfunc):
Data.callfunc = callfunc

@staticmethod
def OnData(data):
Data.callfunc(data)

def DataCallback(a):
print 'I received some data: '+ a

Data.setCallBack(DataCallback)
Data.OnData('I have new data')
*

I have defined a class called Data, which I want to use as a "static" class
(i.e. I will never create an instance of it). (I come from a Java background
so forgive me calling this static)
It contains a class variable and 2 static methods.

I also defined a separate function called DataCallback, which would just
print the data it receives.

The goal of this is to use the Data class as a dispatcher of some chunk of
data to whatever function I would like, settable at run-time.

When executing this script, following error occurs:

*Traceback (most recent call last):
  File "callback.py", line 17, in 
Data.OnData('I have new data')
  File "callback.py", line 11, in OnData
Data.callfunc(data)
TypeError: unbound method DataCallback() must be called with Data instance
as first argument (got str instance instead)
*
What I don't understand is why Python is expecting me to call the
DataCallback() function with a Data instance. To my understanding, the
DataCallback() function can be called from a static method and thus does not
require any instance.

Can anyone point me in the right direction ?

Thanks,

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


Re: Tkinter - problem closing window

2009-01-05 Thread Collin D
On Jan 5, 6:25 am, "Djames Suhanko"  wrote:
> Hello!
> I'm sorry my terrible english (my native language is portuguese).
> I has a litle program that open another window. When I close de root
> window in quit button, I need clicking 2 times to close. is where the
> problem?
>
> The source:
>   1 #!/usr/bin/env python
>   2 from Tkinter import *
>   3 import sys
>   4 import random
>   5 class App:
>   6  def __init__(self, master):
>   7    frame = Frame(master)
>   8    frame.pack()
>   9    rotulo = Label(frame, text="Clique em 'Gerar' e boa
> sorte!",borderwidth=2,bg="gray",justify=C    ENTER,relief=SUNKEN)
>  10    rotulo.pack()
>  11
>  12    self.button = Button(frame, text="Sair", fg="red",
> command=frame.quit,borderwidth=1)
>  13    self.button.pack(side=LEFT)
>  14    self.hi_there = Button(frame, text="Gerar Numero",
> command=self.say_hi,borderwidth=1)
>  15    self.hi_there.pack(side=RIGHT,padx=2,pady=2)
>  16
>  17  def gera_seis(self):
>  18    a = {}
>  19    for i in range(6):
>  20       a[i] = "%02d" %  int (random.randint(0,60))
>  21    resultadoA = "%s-%s-%s-%s-%s-%s" %
> (str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5]))
>  22    return resultadoA
>  23
>  24  def say_hi(self):
>  25    resultado = self.gera_seis()
>  26    raiz = Tk()
>  27    F = Frame(raiz)
>  28    F.pack()
>  29    hello = Label(F, text=resultado)
>  30    hello.pack()
>  31    F.mainloop()
>  32
>  33 root = Tk()
>  34 root.title("$$$ Loteria $$$")
>  35 app = App(root)
>  36 root.mainloop()
>
> --
> Djames Suhanko
> LinuxUser 158.760

Also for style, you might want to group the import lines so they look
like this:

from Tkinter import *
import sys, random

A bit more pythonic. :P
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Steve Holden
Steven D'Aprano wrote:
> On Sun, 04 Jan 2009 20:03:11 -0600, Derek Martin wrote:
[...] And for that matter, it's pretty unintuitive generally.
>>> Names and objects are quite "natural" IMHO.  There are many real world
>>> objects which we attach one or more names to, or refer to in sequences
>>> like "please give me the third book on that shelve" (``shelve[2]``).
>> Indeed, but the way we assign names to them does not behave as it does
>> in Python.
> 
> It doesn't? 
> 
> Oh my, you're going to be confused in a few weeks when The President of 
> the USA ceases to be George W Bush and becomes Barack Obama. Same name 
> (or rather, title), different object (person).
> 
No, he will doubtless describe the White House as a President variable
whose value has been overwritten. There are many fine jokes to be made
about the need to garbage-collect President Bush ...
> 
> 
>> Nor does Python's assignment work like it does in algebra,
> 
> Nor does any programming language, with the possible exception of 
> computer algebra systems.
> 
I'm still waiting for an explanation of where assignment comes into
algebra in the first place.
> 
[...]
> 
>> Those interpretations came first, because, much as in the
>> evolution of any other science, that was the model which was most
>> intuitive or easily explained.
> 
> No no no no. That was the model that was most easily implemented!
> 
Agreed. In those days the von Neumann architecture was a shiny new
thing, and it was even a while before people thought of using computers
for symbolic rather than numeric operations (which is IMHO what makes
them so interesting).

> Before the named bins model of assignment was pure machine code, where 
> you didn't have bins at all, just bits, and there was no distinction 
> between code and data. And before that was *wires* -- early programmers 
> literally had to plug and unplug wires to change the state of the 
> computer. And before that were purely mechanical devices, such as the 
> Enigma Machine, old calculators, and the grand-daddy of them all, Charles 
> Babbage's difference engine and it's precursors.
> 
Aah, the old Univac 1004. Sorry, I'm rambling.
> 
> 
>> But you need not take my word for it.  Simply read the archives and see
>> for yourself how much confusion this has caused on this list. [Please
>> include the closely related behavior of parameter passing in your
>> search.]
> 
> In my opinion, the cause of that confusion is nothing to do with Python's 
> assignment model, and everything to do with the instance of some people 
> to use named bins terminology when describing the Python model. If you 
> keep the named bins terminology for describing the named bins model, 
> you're fine; and if you keep the name/object terminology for describing 
> languages with names/objects, you're fine. You only run into trouble when 
> you mix them. That's when you get people confused because "Python is Call 
> By Something, but it doesn't behave like Call By Something in language 
> Foo I've used before".
> 
> 
This really does go to show that (some) people will argue about
anything, with the major intention of proving themselves right rather
than reaching a common understanding.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Python training in Colorado, January 27-30

2009-01-05 Thread lutz
Yes, my public classes are held only in Colorado today.
Most students travel from out-of-town to attend.

Per my web page, my classes may be available in a different
location later this year (Florida is a strong possibility),
but not in Tulsa, unfortunately.

Thanks,
--Mark Lutz


-Original Message-
>From: alex goretoy 
>Sent: Jan 4, 2009 1:19 PM
>To: Mark Lutz 
>Cc: python-list@python.org
>Subject: Re: Python training in Colorado, January 27-30
>
>I'd be interested in attending if you make it to Tulsa,OK. Are your courses
>only in Colorado?
>
>-Alex Goretoy
>http://www.alexgoretoy.com
>
>
>On Sun, Jan 4, 2009 at 7:29 PM, Mark Lutz  wrote:
>
>> Python author and trainer Mark Lutz will be teaching a 4-day
>> Python class on January 27-30, in Longmont, Colorado.
>>
>> This is a public training session open to individual enrollments,
>> and covers the same topics and hands-on lab work as the onsite
>> sessions that Mark teaches.  The class provides an in-depth
>> introduction to both Python and its common applications, and
>> parallels the instructor's popular Python books.
>>
>> For more information on this session, please visit its web page:
>>
>> http://home.earthlink.net/~python-training/2009-public-classes.htm
>>
>> For additional background on the class itself, see our home page:
>>
>> http://home.earthlink.net/~python-training
>>
>> Thanks for your interest,
>> --Python Training Services
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>

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


Re: Python training in Colorado, January 27-30

2009-01-05 Thread skip

lutz> Per my web page, my classes may be available in a different
lutz> location later this year (Florida is a strong possibility), but
lutz> not in Tulsa, unfortunately.

Maybe if Tulsa had more appealing geography or weather??? ;-)

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


Re: fetch image

2009-01-05 Thread Diez B. Roggisch
asit wrote:

> import httplib
> 
> class Server:
> #server class
> def __init__(self, host):
> self.host = host
> def fetch(self, path):
> http = httplib.HTTPConnection(self.host)
> http.request("GET", path)
> r = http.getresponse()
> print str(r.status) + "  :  " + r.reason
> 
> server = Server("www.python.org")
> fp=open("phpvuln.txt")
> x=fp.readlines();
> for y in x:
>  server.fetch("/" + y);
> 
> The above code fetches only the html source of the webpage. How to get
> the image, flash animation and other stuffs 

By parsing the result, extracting img-tags and others that contain
references, and fetching these explicitly.

The keywords on this for successful search are "python" and "crawling"
or "crawler". There are some out there, e.g. here:

http://weblab.infosci.cornell.edu/documentation/webbackscript

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


Re: About PyOpenGL

2009-01-05 Thread Rob Williscroft
trueli...@gmail.com wrote in news:f8099226-a953-4598-bfe2-61ee5772ce26
@l33g2000pri.googlegroups.com in comp.lang.python:

> 
> Traceback (most recent call last):
>   File "test.py", line 36, in 
> main()
>   File "test.py", line 26, in main
> glutInit(sys.argv)
>   File "c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
> \OpenGL\GLUT\special.py", line 316, in glutInit
> _base_glutInit( ctypes.byref(count), holder )
>   File "c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
> \OpenGL\GLUT\special.py", line 57, in _base_glutInit
> return __glutInitWithExit(pargc, argv, _exitfunc)
>   File "c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
> \OpenGL\platform\baseplatform.py", line 280, in __call__
> self.__name__, self.__name__,
> OpenGL.error.NullFunctionError: Attempt to call an undefined function
> __glutInitWithExit, check for bool(__glutInitWithExit) before calling

To get you code running I needed (in addition to the PyOpenGL download)
to download. 

glut-3.7.6-bin.zip (117 KB) from http://www.xmission.com/~nate/glut.html

and put the glut32.dll where python can find it, the readme says
\system which worked, but sticking it in the same directory 
as python.exe (c:\python25 in your case) worked too.

http://pyopengl.sourceforge.net/
http://pyopengl.sourceforge.net/documentation/installation.html

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Marc 'BlackJack' Rintsch
On Sun, 04 Jan 2009 20:03:11 -0600, Derek Martin wrote:

> On Sat, Jan 03, 2009 at 10:15:51AM +, Marc 'BlackJack' Rintsch
> wrote:
>> On Fri, 02 Jan 2009 04:39:15 -0600, Derek Martin wrote:
>> 
>> What's the difference between Python and Java or C# here!?  Or are they
>> also "BIZARRE"!?
> 
> I am happily ignorant of C#.  As for Java, take the following code:
> 
>   a = 6;
>   a = 5;
> 
> In Python, when you execute the equivalent code, it causes two different
> objects to spring into existence, the first of which may be cleaned up
> by the GC (except that since we're using small integers, that's not
> likely to happen).  Unless I'm misinformed (which is very possible, my
> experience with Java has been extremely limited) in Java that's not the
> case...  the storage is allocated to the name a when you execute its
> declaration, and the *same storage* is reused upon subsequent
> assignment.
> 
> That behaves exactly like named bins.

So does the equivalent in Python.  Or to see it the other way:  In both 
languages it *behaves* like (re)binding the name `a` to two different 
objects.  So it is an implementation detail.  Even a Python 
implementation could reuse the same memory location to store the two 
numbers.

>> > And for that matter, it's pretty unintuitive generally.
>> 
>> Names and objects are quite "natural" IMHO.  There are many real world
>> objects which we attach one or more names to, or refer to in sequences
>> like "please give me the third book on that shelve" (``shelve[2]``).
> 
> Indeed, but the way we assign names to them does not behave as it does
> in Python.

In what way?

>> I think the "bin model" is more complex because you don't just have a
>> name and an object but always that indirection of the "bin".
> 
> I cheerfully disagree. :)  "Named bins" is essentially how algebra
> works,

No it isn't.  Mathematics is about binding names and not about putting 
values into bins.  And a mathematical variable can't be rebound once you 
assigned a value to it.  The "intuitive" model for people with a math 
background would be that of functional languages like Haskell, which is 
even more strange for people used to "named bins" than the Python, Java, 
Ruby, … approach.

> and how several generations of computer languages, not to mention
> the actual machine language those generated, behaved, before the current
> crop.  Those interpretations came first, because, much as in the
> evolution of any other science, that was the model which was most
> intuitive or easily explained.

In terms of the underlying machine, but that is exactly what I meant by 
the additional indirection of the bins.  You just have to drag the low 
level named bins into the explanation because it is an implementation 
detail of the languages.

And there where always languages that use a model like Python parallel to 
the "named bins languages", it is nothing new.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Marc 'BlackJack' Rintsch
On Sun, 04 Jan 2009 22:55:09 -0600, Derek Martin wrote:

> On Sun, Jan 04, 2009 at 09:30:20PM -0500, Steve Holden wrote:
>> > I'm going to go out on a limb and assert that there's NO POSSIBLE WAY
>> > a student could intuit Python's variable assignment behavior, having
>> > never been exposed to that same behavior prior.  It needs to be
>> > taught.
>> > 
>> As does assignment of any kind.
> 
> I'm not sure that's true.  Having taken algebra prior to learning Basic,
> I intuitively understood what this program would do when I executed it,
> the first time I saw the code, and before I read the explanation:
> 
> 10 let x = 10
> 20 print x

Do you really thought of `x` as a named memory location where the bit 
pattern for the floating point value 10 is stored, with just the algebra 
knowledge!?  Isn't "Ah there the name `x` is bound to the value 10." more 
likely?  As it is the technically easier and IMHO more intuitive 
explanation when you go from math to programming.

> [Well, to be honest it's been a very long time since I've programmed in
> Pet BASIC, and the syntax may be wrong.  The point is, just as I did
> then, I am positive that you intuitively understand what the above is
> intended to do, even if it is not valid BASIC syntax -- because if you
> did not, we would not be having this discussion.]

Syntax is correct.  :-)  The ``let`` is optional in Commodore BASIC.

But where is the difference to

x = 10
print x

?  Wouldn't you have guessed what this Python program will do just the 
same?

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: About PyOpenGL

2009-01-05 Thread Cousin Stanley

> 
> OpenGL.error.NullFunctionError: Attempt to call an undefined function
> __glutInitWithExit, check for bool(__glutInitWithExit) before calling
>
> Can anyone please tell me why?

  Your opengl program runs exactly as coded without error
  under Debian 5.0 Linux Lenny  

  Perhaps a required library is missing 
  from your opengl installation  

  Sorry I couldn't provide more help  


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


reflection as in Java: how to create an instance from a classname

2009-01-05 Thread guss
I cannot find a satisfying answer to this question on the web so let's
try here.

My problem is the following, I would like to instantiate some object
from a configuration file that would contain class names like for
example classname=org.common.resource.MyResource.
Here my resource is the class to instanciate and it is in the module
resource that is in a package hierachy.

In fact I would like to do something very similar to the Java:

klass = Class.forname("org.common.resource.MyResource")

instance = klass.newInstance()

The second line is easy once I have a classobj but I have some
problems to find the right recipe for getting it.

I know how to create a class from scratch with new.classobj but how do
you get a class object and then create an object ?

I would like a recipe working for all cases (whatever the module is
not the local one ...)

Maybe I should follow another idiom I don't know ?

Thanks your help

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


Re: Why not Ruby?

2009-01-05 Thread r
On Jan 5, 7:31 am, "Tim Rowe"  wrote:
> 2009/1/1 r :
>
> > I am beginning to think
> > the perfect high level language would take the best for Ruby and
> > Python. The ultimate language with speed in mind, pythons clear
> > syntax, but with shortcuts for gurus.
>
> I spent quite a few evenings looking at Ruby, and didn't find a single
> thing I liked (and I certainly didn't find it "elegant", as the
> original poster described it). What do you see in it that you think
> would be good in Python? Remember, put in too many shortcuts and
> you'll end up with code that's as unmaintainable as Perl!
>
> --
> Tim Rowe

Hello Tim,
I think mainly i was just talking out of my bum. I am forced to learn
Ruby because it is the only API available for one of my favorite
applications. I lament every day that Python was not chosen for the
API, not only for myself, but for the poor users who must deal with
Ruby's backward way of doing things. I really think Python is the best
high level language available today and teaches it's users more than
meets-the-eye. I quite enjoy writing Python code, and learned the
language very quickly despite the fact that i had no prior programming
experience, and very little computer experience in general --
indecently Ruby was the first high level language i tried :)

There were a few things initially that i -thought- i liked better
about Ruby, but after much consideration, have decided they are not
better, and are actually complete rubbish. If i had a choice i would
much rather invest my time learning Perl than Ruby. I -will- never get
over the use of "end", especially since indentation is allowed. In a
language that is as "supposedly" high level as Ruby, this is moronic-
monkey-drivel. This complete ludicrisness, coupled with archaic
thought processes, is completely redundant, bombastically asinine, and
morbidly irreprehensible. Which in turn evaluates to this plague of
human excrement we must plow through each and every day!

I could could go on and on for hours bashing Ruby, but i should
probably stop here before somebody gets upset although i am sure that
i will be viciously lambasted for what i have already said.(Pssft--
some people around here are quite touchy!) So let the tongue lashings
begin!

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


Re: why cannot assign to function call

2009-01-05 Thread Derek Martin
On Mon, Jan 05, 2009 at 01:23:04PM -0500, Steve Holden wrote:
> Even if they really are small-minded or stupid I agree this wouldn't be
> helpful behavior. But neither would your characterization of Python's
> assignment model as "bizarre" (even ignoring that you SHOUTED IT AT US),
> and I have yet to see you admit that such a characterization was, shall
> we say, inappropriate.

Actually I did, in one of my two most recent posts.  But as Steve
D'Arpano just pointed out (even though he clearly disagreed with me),
such a characterization is subjective, and as such you can't rightly
say it's inappropriate.  That's the largest part of my point in
posting in this thread.  Many folks do exactly that, very often.
Someone disagrees with you, tries to shed some light on a different
perspective, or simply fails to understand something, and some members
of this community treat them like heretics, fools, or criminals.

I understand why the assignment model works the way it does, and it's
quite sensible, *when you understand it*.  However, I do also think
that to someone who has not encountered such a model before, and who
has not had it explained to them, and/or who has not the background to
understand why it is implemented that way, it very likely might seem
"markedly unusual in appearance, style, or general character and often
involving incongruous or unexpected elements;" as dictionary.com
defines the term bizarre.  So no, I don't think that's a
mischaracterization at all. 

As for using the term in all caps, I did so precisely because it was
clear to me that many people here think that it could not be unusual,
and I wanted to emphasize the fact that other perspectives exist...
That they are not the same as yours does not invalidate them!

> It takes little to admit one is in the wrong even when one isn't. I've
> had to learn to do it because I often *am* wrong about things. Could you
> be persuaded to consider the possibility that you met with a somewhat
> hostile reaction (whether or not such a reaction was useful or
> necessary) because you were, in a small way, poking people in the side
> with a sharp stick?

I fully expected to receive a hostile reaction, because I am
criticising the behavior of the collective, and supplying a dissenting
perspective -- something I knew from the start would trigger such
hostility *because it always does*.  I have witnessed hostile
reactions time and time again in this forum, from some of the same
people who are dumping on me for suggesting that the assignment model
might be something other than obvious, and from others, for much less:
I expect it because I see it in response to nothing more than asking a
simple question, when the question displays a clear indication that
the poster has missed something critical preventing them from
understanding how to achieve their goals.  My intent was exactly to
point out this behavior, in an attempt to call to people's attention
that it is what they are doing, and thereby discourage it.  I fully
expected a negative response.  You in particular have responded quite
well, but the rest of the community by and large has sadly not failed
to live up to my expectations, even in the face of me saying that that
is exactly what they are doing.  Quite impressive.

Some of the comments from people include the idea that the assignment
model is nothing special, if you've encountered any one of a dozen
other languages.  I didn't realize programming in any of those
languages was a prerequisite for posting questions here, or for
programming with Python.  And that speaks to my ultimate point:  Some
members of the community seem to make assumptions about what people
know or should know, or have experienced, and talk down to people who
haven't met their expectations.  They meet different perspectives with
hostility.  Posts which phrase questions in terms commonly used in
other programming paradigms are generally even more likely to be met
with that same hostility, when they could simply instead explain
politely that Python behaves according to a different model than what
they are used to.  Often this happens, but too often not without
someone also letting the OP know what a mindless jerk he is...

*This* is the "common understanding" which I'd hoped could be
reached...  But you were right... it's very difficult for people to
admit that they might be wrong.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpdBC9eN0T5h.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: structuring a package?

2009-01-05 Thread Bruno Desthuilliers

Torsten Mohr a écrit :

Hi,

i have a question on how to structure a package best, would be great if
anybody could give me some hint on this:

Assuming i have a base class GraphicObject and derived from that some
classes like Square, Circle, ...

It looks natural to me to write in a code that uses the package:

import graphic
import graphic.square
import graphic.circle

That way i'd have to structure the code like this:

graphic/
  __init__,py  (GraphicObject)
  square.py (Square)
  circle.py (Circle)

Does that make sense like this?

Are there better ways to structure things in Python?




Well... Unless your Square and Circle classes are monster classes, or 
you have many many GraphicObject subclasses - that is, unless you need 
to do so for source-file size management -, there's not much reason to 
use a Java-like "one class per file" scheme[1], and it's not the common 
way to organize Python code.


Now if you do have (or just really want - well, it's your code, isn't it 
?-)) to use one-class-per-file, you may be better moving the base 
GraphicObject class in a base.py module. This would be easier to 
understand IMHO, and should make internal imports easier to manage.



[1] A package can act as a facade for submodules/subpackages (using the 
__init__.py to expose submodules/subpackages at the top level), so it's 
not a problem to refactor a single module into a package...




One thing that bothers me is that when i write in circly.py something like
"import graphic", then i can't have the test code for the Circle within
circle.py, at least it looks to me like this.


Depends on how you write your test code, but as far as I'm concerned, I 
prefer to separate source from tests (and use a unittesting framework).



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


Re: mod_python: delay in files changing after alteration

2009-01-05 Thread Stephen Chapman
I have never noticed any such delay. After making a change I just hit
F5 on my browser and its fine.  Maybe its a browser issue



On 1/5/09, psaff...@googlemail.com  wrote:
> Maybe this is an apache question, in which case apologies.
>
> I am running mod_python 3.3.1-3 on apache 2.2.9-7. It works fine, but
> I find that when I alter a source file during development, it
> sometimes takes 5 seconds or so for the changes to be seen. This might
> sound trivial, but when debugging tens of silly errors, it's annoying
> that I have to keep hitting refresh on my browser waiting for the
> change to "take". I'm guessing this is just a caching issue of some
> kind, but can't figure out how to switch it off. Any suggestions?
>
> The entry in my apache2.conf looks like this:
>
> 
>SetHandler mod_python
>PythonHandler mod_python.publisher
>PythonDebug On
> 
>
>
> Thanks,
>
> Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
Sent from Gmail for mobile | mobile.google.com
--
http://mail.python.org/mailman/listinfo/python-list


__init__.py and package help

2009-01-05 Thread TechieInsights
Ok I have read all of the tutorials and documents I could find.  I am
running Python 2.6 on windows.  The problem I am having with packages
is that they don't show up!

Simple example of what isn't working...
Structure-

pytest/ Root directory of package
__init__.py-  code: __all__ = ['folder']
folder/   Another folder in the package
__init__.py- code: __all__ = ['hello']
hello.py- code: print('Hello World')

Then I append the path to sys.path, and try and import...

>>> sys.path.append(r'E:\dev\test\pytest')
>>> from pytest.folder import hello
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named pytest.folder

What am I doing wrong!  It's driving me crazy.
Thanks in advance,
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Python stack and heap

2009-01-05 Thread vedrandekovic
Hello,

Does anybody know how can I get usage of stack or/heap memory in
Python on Windows XP?


Regards,
Vedran
--
http://mail.python.org/mailman/listinfo/python-list


Re: Switching user in a SSH connection

2009-01-05 Thread Shah Alam
On Jan 2, 2:22 pm, Tino Wildenhain  wrote:
> Shah Sultan Alam wrote:
> > Hi Group,
> >  I am trying to connect to a Linux maching using paramiko.
> >  and able to run a command like "ls -l"
>
> >  Now I want to switch user being in the connection ( eg running
> > something like "su -" )
>
> > Will you please let me know how to do that.
>
> You would for example run su - in that connection? Or sudo if
> installed and configured.
>
> What else would you need?
>
> Tino.
>
>  smime.p7s
> 4KViewDownload

I am trying to run su - on that connection..
sudo is not configured
--
http://mail.python.org/mailman/listinfo/python-list


Re: __init__.py and package help

2009-01-05 Thread TechieInsights
Ok... I figured it out... you can only import packages via the __all__
= ['subpackage/folder']... if you include a module such as hello.py,
it will fail.

Go figures I'd find this right after posting here...

Greg

TechieInsights wrote:
> Ok I have read all of the tutorials and documents I could find.  I am
> running Python 2.6 on windows.  The problem I am having with packages
> is that they don't show up!
>
> Simple example of what isn't working...
> Structure-
>
> pytest/ Root directory of package
> __init__.py-  code: __all__ = ['folder']
> folder/   Another folder in the package
> __init__.py- code: __all__ = ['hello']
> hello.py- code: print('Hello World')
>
> Then I append the path to sys.path, and try and import...
>
> >>> sys.path.append(r'E:\dev\test\pytest')
> >>> from pytest.folder import hello
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named pytest.folder
>
> What am I doing wrong!  It's driving me crazy.
> Thanks in advance,
> Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: __init__.py and package help

2009-01-05 Thread J. Cliff Dyer

On Mon, 2009-01-05 at 11:49 -0800, TechieInsights wrote:
> Ok I have read all of the tutorials and documents I could find.  I am
> running Python 2.6 on windows.  The problem I am having with packages
> is that they don't show up!
> 
> Simple example of what isn't working...
> Structure-
> 
> pytest/ Root directory of package
> __init__.py-  code: __all__ = ['folder']
> folder/   Another folder in the package
> __init__.py- code: __all__ = ['hello']
> hello.py- code: print('Hello World')
> 
> Then I append the path to sys.path, and try and import...
> 
> >>> sys.path.append(r'E:\dev\test\pytest')
> >>> from pytest.folder import hello
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named pytest.folder
> 
> What am I doing wrong!  It's driving me crazy.
> Thanks in advance,
> Greg

You want

>>> sys.path.append(r'E:\dev\test')

unless your code is in E:\dev\test\pytest\pytest\folder\hello.py


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

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


Re: Why not Ruby?

2009-01-05 Thread Tim Rowe
2009/1/1 r :
> I am beginning to think
> the perfect high level language would take the best for Ruby and
> Python. The ultimate language with speed in mind, pythons clear
> syntax, but with shortcuts for gurus.

I spent quite a few evenings looking at Ruby, and didn't find a single
thing I liked (and I certainly didn't find it "elegant", as the
original poster described it). What do you see in it that you think
would be good in Python? Remember, put in too many shortcuts and
you'll end up with code that's as unmaintainable as Perl!

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


replacement for __file__ in compiled exe

2009-01-05 Thread TechieInsights
__file__ command does not work when compiled to exe.  It makes since
because the file is now in a compressed library.  Is there a
replacement or something else you can do?  The real problem is that
when you create an exe of your program with python embedded, you can't
always guarantee that your current directory is the directory of your
program.  I guess when you could just set a registry entry on
windows... but it would be nice to have a quick fix for this (like
os.path.dirname(__file__)).

Thanks,

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


Re: f.seek() unwanted output

2009-01-05 Thread pruebauno
On Jan 5, 8:52 am, "thomasvang...@gmail.com" 
wrote:
> I'm having trouble with a script that is printing the output of f.seek
> () whereas in the documentation it is quoted not to have any output:
>
> 
> file.seek(offset[, whence])¶
>
>     Set the file’s current position, like stdio‘s fseek. The whence
> argument is optional and defaults to os.SEEK_SET or 0 (absolute file
> positioning); other values are os.SEEK_CUR or 1 (seek relative to the
> current position) and os.SEEK_END or 2 (seek relative to the file’s
> end). There is no return value.
> --
>
> I have a file in memory.
> when i try f.seek(0) #or any other value in f.tell()
> it gives me 0 as output:
>
> the following script illustrates my 'problem'>>> for a in range(10):
>
>         f.seek(a)
>
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
>
>
>
> I don't want python to produce output when setting the file pointer.
> Any help woul be appreciated.
> Kind regards,
> Thomas

You can also avoid the output by assigning the output to something:

>>> for a in range(10):
 dummy=f.seek(a)

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


Re: __init__.py and package help

2009-01-05 Thread TechieInsights
Thanks

J. Cliff Dyer wrote:
> On Mon, 2009-01-05 at 11:49 -0800, TechieInsights wrote:
> > Ok I have read all of the tutorials and documents I could find.  I am
> > running Python 2.6 on windows.  The problem I am having with packages
> > is that they don't show up!
> >
> > Simple example of what isn't working...
> > Structure-
> >
> > pytest/ Root directory of package
> > __init__.py-  code: __all__ = ['folder']
> > folder/   Another folder in the package
> > __init__.py- code: __all__ = ['hello']
> > hello.py- code: print('Hello World')
> >
> > Then I append the path to sys.path, and try and import...
> >
> > >>> sys.path.append(r'E:\dev\test\pytest')
> > >>> from pytest.folder import hello
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named pytest.folder
> >
> > What am I doing wrong!  It's driving me crazy.
> > Thanks in advance,
> > Greg
>
> You want
>
> >>> sys.path.append(r'E:\dev\test')
>
> unless your code is in E:\dev\test\pytest\pytest\folder\hello.py
>
>
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
--
http://mail.python.org/mailman/listinfo/python-list


Re: My last working day of 2007

2009-01-05 Thread Ant
On Jan 5, 9:47 am, "Jack.Chu"  wrote:
> Hello guys:
> I created a simple tool to count how I wasted my time day by day 
> ;-)http://www.flickr.com/photos/34017...@n07/3169438647/sizes/o/

Looks interesting - did you have some sort of time machine to be
spending that much time in Chrome at the end of 2007? ;-)

> I just want to get suggestions to improve it, ...

It's a bit hard to tell just from the screenshot... Do you have some
code we could look at? Would be perhaps good to sub-log each window's
title so that you could subdivide, for example, Firefox's time by the
pages you were looking at (this would work quite well for numerous
apps.)
--
http://mail.python.org/mailman/listinfo/python-list


fetch image

2009-01-05 Thread asit
import httplib

class Server:
#server class
def __init__(self, host):
self.host = host
def fetch(self, path):
http = httplib.HTTPConnection(self.host)
http.request("GET", path)
r = http.getresponse()
print str(r.status) + "  :  " + r.reason

server = Server("www.python.org")
fp=open("phpvuln.txt")
x=fp.readlines();
for y in x:
 server.fetch("/" + y);

The above code fetches only the html source of the webpage. How to get
the image, flash animation and other stuffs 
--
http://mail.python.org/mailman/listinfo/python-list


Extending Python with C or C++

2009-01-05 Thread Ryan
I've been using Python for many years now. It's a wonderful language
that I enjoy using everyday. I'm now interested in getting to know
more about the guts (C/C++) and extending it. But, extending python
still seems like a black art to me. Is there anymore docs or info on
extending it besides the standard sparse ones (http://www.python.org/
doc/2.5.2/ext/intro.html) that may give me more insight? Is there a
class available? How can I learn more about the guts of python? How
would one go about following an interest in contributing to the
development of python.

Thanks,

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


Re: Extending Python with C or C++

2009-01-05 Thread Ralf Schoenian

Ryan wrote:

I've been using Python for many years now. It's a wonderful language
that I enjoy using everyday. I'm now interested in getting to know
more about the guts (C/C++) and extending it. But, extending python
still seems like a black art to me. Is there anymore docs or info on
extending it besides the standard sparse ones (http://www.python.org/
doc/2.5.2/ext/intro.html) that may give me more insight? Is there a
class available? How can I learn more about the guts of python? How
would one go about following an interest in contributing to the
development of python.

Thanks,

Ryan


It is not exactly what you are looking for but nevertheless I am 
thinking the  article "Automatic C Library Wrapping -- Ctypes from the 
Trenches" may be interesting for you. You can find it in the latest 
Python Papers issue or simply following the link: 
http://ojs.pythonpapers.org/index.php/tpp/article/view/71


Regards,
Ralf


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


Re: structuring a package?

2009-01-05 Thread Torsten Mohr
Hello James,

>> That way i'd have to structure the code like this:
>>
>> graphic/
>>  __init__,py  (GraphicObject)
>>  square.py (Square)
>>  circle.py (Circle)
>>
>> Does that make sense like this?
> 
> This seems perfectly acceptable.

Thanks for that hint.  Do you see a way that i could write in circle.py:

circle.py:

import graphic

class Circle(graphic.GraphicObject):
.

if __name__ == '__main__':
abc = Circle()
abc.some_test_code()


Thanks for any hints,
Torsten.

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


Re: Python training in Colorado, January 27-30

2009-01-05 Thread alex goretoy
>
>   lutz> Per my web page, my classes may be available in a different
>lutz> location later this year (Florida is a strong possibility), but
>lutz> not in Tulsa, unfortunately.
>
> Maybe if Tulsa had more appealing geography or weather??? ;-)
>
> Skip

Yes, that makes sense to me. Thank you.

There's just not much going on here in Tulsa. I moved here about 3 years
ago. It's difficult with linux, PHP,python,administration,networking jobs
around here.

That's one of the reason why I want to boost the blood flow here in Tulsa. I
mainly like it here because it's quiet and the people are nice. Depends on
what you compare that too though. It's a good place for family. But if your
a linux system administrator, programmer then it's a little more difficult
for that stuff here. It's not in the market here. Everyone wants .Net this,
Microsoft that. I don't like Microsoft, but don't get me wrong I still have
to virtualize it sometimes to get certain things done. I just wish that it
were the other way around. Not that it won't be sometime in the near future.
Simply due to how things are looking for Micr0$pft. I think I heard
something about them getting in to linux/unix as base or is capable of
running linux side-by-side. Not virtualbox. Something else. But, I think
that's a rumor. Can someone verify that for me? Sorry, of topic.

That's why I want to do something to change things around. Maybe open a
small school(dream?) Monthly meetings or something. so people can hang out,
talk geek. I also want to somehow make it so more people dive into linux,
python development. The only way that I think this to be conceivable is if
people don't have to pay for it to go there. Or maybe just a small cover
charge. They learn cool s*** for fun and profit. I think one way to do this
is to bring some trainers to the area. Note I haven't done this before. But
I want t organize someway for linux, python development to boom around here
and spread all around like a virus. Kinda like organized crime only legal.
It's fun. :) Then we find a place to do this and boom. We have a 3 day event
in python development here in Tulsa. If more people are able to go then
there's a better chance for them to get into linux and python.

*Some possible room would be:*

Picking a flavor of linux, focusing on gentoo,slackware,ubuntu,centos,bsd as
> main choice for starters. Installing that flavor and using it for daily
> tasks that a person would perform in windows.
>
> Ubuntu Linux Installation and customization. Merging from windows, command
> line, tools, development starting points,best application to use,techniques,
> etc...
>
> Customizing and using c,python(pyrex),bash,php,etc...
>
> Then we could go around to some companies.Get them to goto to these
meetings. It doesn't even have to be companies. But it is preferred. Somehow
making it so that every company/person starts to invest at least 33% of
there resource/time on linux and python, for starters.

The only thing is that, I don't know where to start. to achieve this. I've
been thinking about this from a long time ago. I even bought a domain.
HackersHappenHere.com in contrast with the Microsoft launch of
HeroesHappenHere.com (Are they saying they want to find more Heroes for
there crisis they have going on?) We need more hackers.

Oh, one question. How would I get someone, say like Ubuntu to sponsor this
whole shenanigans? Or Google for that matter. This would actually,
inderictly prepare everyone for Chrome for Linux and undeniably move people
from IE.

What if there were billboards for linux in the USA? How would that effect
Microsoft? OUCH. I think someones turf gonna get jacked.

People driving by will see Ubuntu, and be like whats that? A new windows? I
gotta try it. Need a upgrade. Then they call there local computer guy,etc...

Google will definitely have more playing ground on this turf, not that there
sandbox isn't big enough as it is. I just really like google. They have a
good culture, etc... I would like this culture to spread out side of google
though. This I think would be nice.

This way there can be events to go across the USA for Hacker Happen Here.
People will truly then start seeing some of the power that linux has over
windows and how cost effective it use to use it. Not only for servers, but
as a desktop too. Most people, all they need is Firefox. Ubuntu has that.
For development it's a different story. For me linux is better for
development. I know I can do more with it. Windows I think is somewhat
restrictive to what a person can do with there computer.

Is there something like this for linux already? Am I missing out on
something? trying to duplicate some else's efforts? Certainly, I'm not
trying to do that.

This will hopefully get some of those really good .Net developers to try
python,spe,ubuntu,etc...If they haven't yet.

All I know is this. I want linux and python to own USA turf.


This will also make it so that development and new applications/tools will
come 

Re: replacement for __file__ in compiled exe

2009-01-05 Thread John Machin
On Jan 6, 7:03 am, TechieInsights  wrote:
> __file__ command does not work when compiled to exe.  It makes since
> because the file is now in a compressed library.  Is there a
> replacement or something else you can do?  The real problem is that
> when you create an exe of your program with python embedded, you can't
> always guarantee that your current directory is the directory of your
> program.

How can you *ever* guarantee that the current directory is the same as
the directory in which the program resides? This lack of guarantee is
quite independent of whether the "program" is .py, .exe, .bat, .com,
etc. Isn't the real problem how to find out which directory the
program is in?

>  I guess when you could just set a registry entry on
> windows... but it would be nice to have a quick fix for this (like
> os.path.dirname(__file__)).

if hasattr(sys, 'frozen'):
answer = os.path.split(sys.executable)[0]
else:
answer = os.path.split(sys.argv[0])[0]

(maybe) ... your question is a little unclear.

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


mod_python: delay in files changing after alteration

2009-01-05 Thread psaff...@googlemail.com
Maybe this is an apache question, in which case apologies.

I am running mod_python 3.3.1-3 on apache 2.2.9-7. It works fine, but
I find that when I alter a source file during development, it
sometimes takes 5 seconds or so for the changes to be seen. This might
sound trivial, but when debugging tens of silly errors, it's annoying
that I have to keep hitting refresh on my browser waiting for the
change to "take". I'm guessing this is just a caching issue of some
kind, but can't figure out how to switch it off. Any suggestions?

The entry in my apache2.conf looks like this:


   SetHandler mod_python
   PythonHandler mod_python.publisher
   PythonDebug On



Thanks,

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


Re: math module for Decimals

2009-01-05 Thread alex goretoy
>
> Hmm.  Maybe we shouldn't be using this syntax in from_float, if it's
> the only thing that prevents the trunk version of decimal.py from
> being used with Python 2.4.  On the other hand, from_float isn't
> going to work until 2.7 anyway, since it uses a whole bunch of
> new stuff:  as_integer_ratio and copysign (both introduced in 2.6),
> and bit_length (introduced in 2.7).
>

I so new to python that I'm not sure that anything I can say may help as
much as someone with more experience. I would leave is compatability to be
decided by what other functions it relies on.(as_integer_ratio and copysign)
Throw the rest out the window.

Since that would make this function more bulky and I don't think there will
be that many people wanting to use it with 2.4, OTOH I'm using BackTrack2
and it comes with python2.4.3

I started building my little program using ubuntu with python2.5.x, then I
started to use my other option for dual-boot. Backtrack2 is an old time
favorite and is alot faster for me to use when running X,firefox(with
anywhere from 15-100 tabs open),konqueror,etc

Ialready installed other versions of python for bt, no problem there. I'm
just wondering about this import error in decimal.py inside python2.7a0(svn
repo), don't let curiosity kill this cat.

I just wanted to let All know what decimal.py is doing on my pc. Maybe I'm
the only one getting this? This version of python2.7 is from python's svn
repo. Is the python repo considered to be unstable(wrong word?) and this is
expected?

I get this when importing decimal:

Python 2.7a0 (trunk:68339M, Jan  5 2009, 05:18:41)
[GCC 3.4.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/decimal.py", line 138, in 
import math as _math
ImportError: No module named math
>>>


Are other people seeing this as well? Just curious.
--
http://mail.python.org/mailman/listinfo/python-list


About PyOpenGL

2009-01-05 Thread trueli...@gmail.com
I follow the , write a small test:

#!/usr/bin/env python
# encoding=utf-8

import sys
from OpenGL.GL import *
from OpenGL.GLUT import *

def display():
glClear(GL_COLOR_BUFFER_BIT)
glColor(1.0, 1.0, 1.0)
glBegin(GL_POLYGON)
glVertex(0.25, 0.25, 0.0)
glVertex(0.75, 0.25, 0.0)
glVertex(0.75, 0.75, 0.0)
glVertex(0.25, 0.75, 0.0)
glEnd()
glFlush()

def init():
glClearColor(0.0, 0.0, 0.0, 0.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0)

def main():
glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB)
glutInitWindowSize(250, 250)
glutInitWindowPosition(100, 100)
glutCreateWindow('hello')
init()
glutDisplayFunc(display)
glutMainLoop()

if __name__ == '__main__':
main()

But I got an error:

Traceback (most recent call last):
  File "test.py", line 36, in 
main()
  File "test.py", line 26, in main
glutInit(sys.argv)
  File "c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
\OpenGL\GLUT\special.py", line 316, in glutInit
_base_glutInit( ctypes.byref(count), holder )
  File "c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
\OpenGL\GLUT\special.py", line 57, in _base_glutInit
return __glutInitWithExit(pargc, argv, _exitfunc)
  File "c:\python25\lib\site-packages\PyOpenGL-3.0.0b8-py2.5-win32.egg
\OpenGL\platform\baseplatform.py", line 280, in __call__
self.__name__, self.__name__,
OpenGL.error.NullFunctionError: Attempt to call an undefined function
__glutInitWithExit, check for bool(__glutInitWithExit) before calling

Can anyone please tell me why?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python return values

2009-01-05 Thread Mel
koranth...@gmail.com wrote:

> I have a newbie doubt about Python return values.
> 
> In (say) C/C++, if we try to return a value which is stored inside the
> procedure stack, we will get an error when trying to access it outside
> of that procedure.
> For example:
> function foo():
>dcl y int
>dcl x pointer to int pointing to y
>return x
> 
> 
> function bar():
>x = foo()
>...
>use x
> 
> This will error out since the memory has be taken back.
> 
> Now, in Python, we do it everytime, because all variables are
> references, and even returns just copies the references.
> function pyfoo():
>   return 786
> 
> function pyfoo1():
>   x = xclass()
>   return x
> 
> function pybar():
>   x = pyfoo()
>   y = pyfoo1()
>   ...
>   use x, y
> 
> Why doesnt it error out?

Because Python doesn't use the procedure stack that way.  Using C/C++ terms,
all objects are in the heap, and objects are deallocated automatically
after all references to them disappear.

Mel.

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


Re: threading a 10 lines out of a file

2009-01-05 Thread alex goretoy
Steve,

Are you referring to the endless GIL debate? I googled about what you said.
I'll look into it here shortly. I just know one thing, is that I need a
comparison for regular code and something about how GIL and threading fit in
the picture. It makes it easier for me to understand what is going on. Can
you post an example? something I can use to truely thread a for loop? The
example previously posted show that it works 10 times faster than original
for loop. My current program runs for 4.5 hours. I think it will be good to
minimize that by 10 times. But if It can do more/faster, than that would be
great. TIA for all your help.

-Alex Goretoy
http://www.alexgoretoy.com



On Mon, Jan 5, 2009 at 6:13 PM, Steve Holden  wrote:

> re, however, that the CPython implementation won't net you any
> benefit if all threads are CPU-bound, since due to something called the
> GIL (global interpreter lock) no two threads will run concurrently.
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading a 10 lines out of a file

2009-01-05 Thread Steve Holden
alex goretoy wrote:
> Steve,
> 
> Are you referring to the endless GIL debate? I googled about what you
> said. I'll look into it here shortly. I just know one thing, is that I
> need a comparison for regular code and something about how GIL and
> threading fit in the picture. It makes it easier for me to understand
> what is going on. Can you post an example? something I can use to truely
> thread a for loop? The example previously posted show that it works 10
> times faster than original for loop. My current program runs for 4.5
> hours. I think it will be good to minimize that by 10 times. But if It
> can do more/faster, than that would be great. TIA for all your help.
> 
Sadly my example doesn't show that. I did, once upon a time, write code
that used several hundred threads to send emails, and gave a dramatic
speed-up (because of the network-bound nature of the task). Can I
presume that your original inquiry was a toy, and that your real problem
is also IO-bound? Otherwise I am unsure how you will benefit by
threading - if your line-processing tasks don't contain any IO then
using a threaded approach will not yield any speed-up at all.

The example you quoted achieved its speed-up because a thread releases
the GIL while waiting for a network response, allowing other threads to
process. Thus it effectively ran all the pings in parallel.

Se we need to know a bit more about your 4.5-hour program before we can
determine whether threads can help. There is light at the end of the
tunnel, however, since even if threads don't work it's possible that the
multiprocessing module will (assuming you have multi-processor hardware
at your disposal).

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: threading a 10 lines out of a file

2009-01-05 Thread alex goretoy
>
> Se we need to know a bit more about your 4.5-hour program before we can
> determine whether threads can help. There is light at the end of the
> tunnel, however, since even if threads don't work it's possible that the
> multiprocessing module will (assuming you have multi-processor hardware
> at your disposal).

What my program is doing is sending each line to a function that processes
it via pycurl(with urllib fallback),mysqlDB(with _mysql fallback). It check
the mysql database to see if this line exists. If it doesn't then it sends
it either via mysql query or pycurl. Depending on the option set in the
functions. Some sections of the function  have time.sleep(6) in them.
Otherwise things won't work. This considerably slows down performance. If I
thread all lines then it will process more at the same time. So that means
there will be like 10 or set amount threads running doing all steps in the
functions. posting forms, performing queries and waiting for form postings
to process on the server, etc... I hope this adds more light at the end of
that tunnel. It currently works under my ubuntu install of python(2.5.x) and
bt's python(2.4.3). Then reason why I added a fallback to MySQLdb and pycurl
is then a person can install this on a server that is hosted elsewhere.
Where you can't install python modules, due to permissions and such. I want
it to work everywhere. There's alot more to this application, I'm not sure I
can disclose at the moment. Seeing as it can be used for good or bad. I
don't want it to get in the wrong hands if it's public. OTOH, I think I'll
make it public. That's all up in the air at the moment. One thing it that it
does make life easier for me. A lot easier. Although, I haven't made money
with it. Yet. Plus, I want to make pyGTK frontend for it. Looking into that
too. I wouldn't be against a private team assembling to create this though.
As long as I can get money out of it somehow. Cuz I'm broke. and I live with
my mom. Not sure how anyone can help me there. But I'll throw it up in the
air for all to see. Maybe somethings comes out of it. This program is an
idea I've been building inside my garage(my room) for about a year and a
half. Built in PHP and python, now.

Would something that uses pycurl,mysql be good for threading? It doesn't run
on SMP but maybe one day.

I also need to look into how to make a python package out of it. I
researched some stuff awhile ago, but I didn't quite need it then. I just
wanted to see what I'm getting into.  Any other stuff about this would be
appreciated to. Although of topic. Sorry.

By the way, I wanted to really thank everyone for all your help. It means a
lot to me.

-Alex Goretoy
http://www.alexgoretoy.com



On Mon, Jan 5, 2009 at 9:17 PM, Steve Holden  wrote:

> I did, once upon a time, write code
> that used several hundred threads to send emails, and gave a dramatic
> speed-up (because of the network-bound nature of the task). Can I
> presume that your original inquiry was a toy, and that your real problem
> is also IO-bound? Otherwise I am unsure how you will benefit by
> threading - if your line-processing tasks don't contain any IO then
> using a threaded approach will not yield any speed-up at all.
>
> The example you quoted achieved its speed-up because a thread releases
> the GIL while waiting for a network response, allowing other threads to
> process. Thus it effectively ran all the pings in parallel.
>
> Se we need to know a bit more about your 4.5-hour program before we can
> determine whether threads can help. There is light at the end of the
> tunnel, however, since even if threads don't work it's possible that the
> multiprocessing module will (assuming you have multi-processor hardware
> at your disposal).
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: My last working day of 2007

2009-01-05 Thread News123

s...@pobox.com wrote:
> Jack> It's simple, a small program running on background, logging the
> Jack> title of foreground window. A python script parses the log file
> Jack> and then generates chart by matplotlib.
> 
> Jack> I just want to get suggestions to improve it, or know the news
> Jack> that somebody had implemented a better one so I can abandon my
> Jack> toy.
> 
> For starters, you might figure out how to make it work on a real operating
> system which allows multiple active processes.

Well the computer can do things in paralell. Most human beings, and
according to stereotypes especially male human beings are only single
tasking, (like the mouse focus).
So if you want to find out what a user is busy with I guess, that the
title of the window in focus is probaly a very reasonable indicator.

Of course if you want to find out what the computer is busy with, then
you should make statistics of the processes and heir cpu loads.



bye


N

> 
> Nudge, nudge.  Wink, wink.  Say no more.  Say no more. ;-)
> 
--
http://mail.python.org/mailman/listinfo/python-list


Measuring bytes of packet sent from python application

2009-01-05 Thread Kangkook Jee

Hi, all

I'd like to measure number of bytes sent(or recv'd) from my python
application. Does anyone have any idea how can I achieve this?

I tried to do this by tracing some socket calls (send, sendto, sendAll) 
 using 'metaclass' but I could find exactly place that I can put this in.



My application runs some number of protocols (bittorrent, xmlrpc ..) in
it and will be measured for a couple of hours.

Thanks a lot for your help, in advance
/Kangkook
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-05 Thread Steven D'Aprano
On Mon, 05 Jan 2009 13:21:09 -0600, Derek Martin wrote:

> Some of the comments from people include the idea that the assignment
> model is nothing special, if you've encountered any one of a dozen other
> languages.  I didn't realize programming in any of those languages was a
> prerequisite for posting questions here, or for programming with Python.

It's not. But the tone of your argument suggests you think that matching 
the named bins assignment model of the 1970s should be a prerequisite for 
all new programming languages.


There are, in general, four types of programmers new to Python. In no 
particular order:

(1) People with no programming experience at all. They won't have any 
problems with Python's assignment model because they have no preconceived 
ideas about how assignment should work.

(2) People who are used to name binding in Ruby, Java, etc. and so will 
find Python's assignment model more or less identical.

(3) Those who come from an entirely different programming model, say, 
Forth or Haskell. For them, Python's assignment model is going to be the 
least of their worries.

(4) People who are used to the named bins model from C, Pascal or 
Fortran, who will find some unusual corner cases where Python behaves 
differently to their mental model of assignment (but not for simple 
arithmetic using numbers).

Python is accessible to *all* of the above groups, although naturally 
some will need to put in more effort in different directions than others.


The tone of reproach in your posts suggests that you believe that the 
people in group 4 are more authentic programmers whose opinions are more 
correct than those in groups 1-3. I do not think there is any good reason 
to believe that group 4 is more special than the other groups.

Nor do I believe that newly created languages (as Python was, a decade 
and a half ago) should be limited to following the named bin assignment 
model for fear that C etc programmers will be put off by the (supposed) 
bizarreness of name binding. Speaking as a former Pascal programmer, I 
think most C, Fortran and Pascal programmers are far too smart for that.


>  And that speaks to my ultimate point:  Some members of the community
> seem to make assumptions about what people know or should know, or have
> experienced, and talk down to people who haven't met their expectations.
> They meet different perspectives with hostility.

In my experience, two perspectives are likely to be met with hostility:

* those which arrogantly assume that they are the One True and Correct 
perspective and all others are inferior and wrong; and

* those which ignorantly assume that they are the only perspective 
possible.


Your first post in this topic made the extraordinarily arrogant and 
incorrect claim that:

[quote]
What the Python community often overlooks, when this discussion again
rears its ugly head (as it seems to every other hour or so), is that
its assignment model is BIZARRE, as in it's conceptually different
from virtually all other languages substantially taught in
undergraduate computer science programs.
[end quote]

We can see some pretty poor assumptions right there:

* That the Python community is capable of uniformly overlooking Python's 
differences from other languages.

* That only languages "substantially taught" in undergraduate CS courses 
matter.

It seems that you don't include in the Python community all those who use 
the term "name binding" instead of variable assignment specifically 
because it gives new users a clue that Python is not the same as C.

You've also missed out on probably twenty years of CS where Java (using 
the same assignment model as Python!) has been *the* language of choice 
for undergrad CS, not to mention those introductory courses which use 
Python.

And then you're shocked, SHOCKED!!! that people respond sharply.

How different do you think the response would have been if you had said:

"What we in the Python community should try to remember is that for those 
new to the language, there can sometimes be preconceived ideas about how 
assignment works that clashes with Python's assignment model. From my own 
perspective, I found the differences between Python's name binding model 
and the named-bins model of C/Pascal/Fortran confusing at first, and to 
be honest, I still get caught by those differences. Naturally this is a 
general problem for every language, Python is hardly unique, but please 
remember not to bite the newbies just because they are still thinking in 
some other language."


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


Re: greenlets and how they can be used

2009-01-05 Thread James Mills
On Tue, Jan 6, 2009 at 4:39 AM, Benjamin Walkenhorst  wrote:
> James Mills wrote:
>> On Sun, Jan 4, 2009 at 4:52 AM, Benjamin Walkenhorst  wrote:
>>> POE was one of the nicest software frameworks I have ever used, and I've 
>>> been continuously frustrated by the lack of something like it in other 
>>> languages such as Python or Ruby.
>>
>> It does exist :) It's called circuits.
>> Or at least circuits is a framework that I develop
>> and build which sounds very similar to POE in
>> some ways :)

(snip)
> Then, one very sad day, a Gentoo upgrade broke POE. I got it working again a 
> few months later, but by then I had somehow lost interest in Perl and 
> discovered the beauty of Python, where my search for an appropriate 
> replacement was frustrated (Twisted seemed to be the closest equivalent, but 
> it seemed overly complex to me, at least I never got the hang of it...).

It would seem to me that circuits is quite similar
to POE - I've never really used or played with Perl though
and probably will never :)

> Or, to put it briefly, I would really like to take a look at that sometime. 
> If you intend to release it in any form, I would like to hear about it.

Currently released: circuits-1.0b1

See: http://trac.softcircuit.com.au/circuits/

> Oh. I see, it already IS available. How nice!!! That is going to be an 
> interesting evening!
> Oh, and thank you very much for bringing this to my attention!!!

Your very welcome ... circuits is by no means a replacement
or competitor to Twisted - it has very different design goals
and architecture (nicer/simpler ihmo). That said though anything
that Twisted  can do, circuits can do - I've deliberately tried to
keep the Component Library as simple and straight forward
as possible.

Happy hacking!

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


Re: Extending Python with C or C++

2009-01-05 Thread Terry Reedy

Ryan wrote:

I've been using Python for many years now. It's a wonderful language
that I enjoy using everyday. I'm now interested in getting to know
more about the guts


The 'guts' of Python the language include the object model, namespaces 
(including modules), and the statement and infix-expression syntax.



(C/C++) and extending it.


Now you are asking about CPython, the leading computer implementation.


But, extending python still seems like a black art to me.

> Is there anymore docs or info on

extending it besides the standard sparse ones (http://www.python.org/
doc/2.5.2/ext/intro.html) that may give me more insight? Is there a
class available?


If you want to connect CPython to Python-oblivious code written in C, 
Swig (with C code) and Ctypes (with Python code) are the main choices. 
If you want to write new Python-aware (and specific) code, you can use 
the CPython C-API functions.  Extensions in C are written as importable 
modules.  The interface for such is not difficult; existing examples 
should be a good guide.


> How can I learn more about the guts of python?

The 'guts' of an implementation follow from the 'guts' of the language. 
 There must be a syntax parser and compiler to internal form, 
evaluation loop, and implemenations of built-in constants, functions, 
classes, and modules.  CPython's source tree begins as

http://svn.python.org/view/
You might actually want to start at
http://svn.python.org/view/python/trunk/
Note: if you click a filename, such as 'setup.py', you get the entire 
revision history with checkin messages.
If you click the displayed revision number, such as '67978', you get the 
latest checkin message and the current version of the file.



How would one go about following an interest in contributing to the
development of python.


Read
http://python.org/dev/
and start following the pydev list, mirrored to gmane.comp.python.devel 
at news.gmane.org.


Terry Jan Reedy

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


Re: Tkinter - problem closing window

2009-01-05 Thread Collin D
On Jan 5, 9:21 am, Roger  wrote:
> On Jan 5, 11:52 am, Collin D  wrote:
>
>
>
> > On Jan 5, 6:25 am, "Djames Suhanko"  wrote:
>
> > > Hello!
> > > I'm sorry my terrible english (my native language is portuguese).
> > > I has a litle program that open another window. When I close de root
> > > window in quit button, I need clicking 2 times to close. is where the
> > > problem?
>
> > > The source:
> > >   1 #!/usr/bin/env python
> > >   2 from Tkinter import *
> > >   3 import sys
> > >   4 import random
> > >   5 class App:
> > >   6  def __init__(self, master):
> > >   7    frame = Frame(master)
> > >   8    frame.pack()
> > >   9    rotulo = Label(frame, text="Clique em 'Gerar' e boa
> > > sorte!",borderwidth=2,bg="gray",justify=C    ENTER,relief=SUNKEN)
> > >  10    rotulo.pack()
> > >  11
> > >  12    self.button = Button(frame, text="Sair", fg="red",
> > > command=frame.quit,borderwidth=1)
> > >  13    self.button.pack(side=LEFT)
> > >  14    self.hi_there = Button(frame, text="Gerar Numero",
> > > command=self.say_hi,borderwidth=1)
> > >  15    self.hi_there.pack(side=RIGHT,padx=2,pady=2)
> > >  16
> > >  17  def gera_seis(self):
> > >  18    a = {}
> > >  19    for i in range(6):
> > >  20       a[i] = "%02d" %  int (random.randint(0,60))
> > >  21    resultadoA = "%s-%s-%s-%s-%s-%s" %
> > > (str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5]))
> > >  22    return resultadoA
> > >  23
> > >  24  def say_hi(self):
> > >  25    resultado = self.gera_seis()
> > >  26    raiz = Tk()
> > >  27    F = Frame(raiz)
> > >  28    F.pack()
> > >  29    hello = Label(F, text=resultado)
> > >  30    hello.pack()
> > >  31    F.mainloop()
> > >  32
> > >  33 root = Tk()
> > >  34 root.title("$$$ Loteria $$$")
> > >  35 app = App(root)
> > >  36 root.mainloop()
>
> > > --
> > > Djames Suhanko
> > > LinuxUser 158.760
>
> > Also for style, you might want to group the import lines so they look
> > like this:
>
> > from Tkinter import *
> > import sys, random
>
> > A bit more pythonic. :P
>
> In that case you probably want to take out the 'from' import and:
>
> import Tkinter, sys, random
>
> in order to avoid any namespace issues especially if you have a large
> project with lots of gui manipulations.  But that's just me being
> pedantic. ;)

I agree... you could have conflicting functions.. not fun. XD
--
http://mail.python.org/mailman/listinfo/python-list


Re: [email/quoprimime.py] AttributeError: 'tuple' object has no attribute 'lstrip'

2009-01-05 Thread Terry Reedy

Gilles Ganault wrote:

Hello

I successfully use the email package to send e-mail from Python
scripts, but this script fails when I fetch addresses from an SQLite
database where data is Unicode-encoded:

==
from email.MIMEText import MIMEText 
import smtplib,sys 
import apsw


connection=apsw.Connection("test.sqlite")
cursor=connection.cursor()
  
subject = "My subject"
f = open("message.txt", "r") 
message = f.read()

f.close()

msg = MIMEText(message) 


msg['Subject'] = subject

From = "m...@acme.com"
msg['From'] = From 

server = smtplib.SMTP("smtp.acme.com") 


sql="SELECT email FROM people WHERE email IS NOT NULL"
rows=list(cursor.execute(sql))
for email in rows:
To = email


Why is 'email' renamed 'To'?


msg['To'] = email

#print To
#(u'du...@acme.com',)


Why are these line comments?
Why is the string enclosed in a tuple?


#AttributeError: 'tuple' object has no attribute 'lstrip'


True. Only strings have lstrip method.

	#server.sendmail(From,[To],msg.as_string()) 


Ditto. This looks looks a line from a doc.
If you want help interpreting an error message,
copy and paste the *entire traceback* without editing.



server.quit

connection.close(True)
==

Does someone know what is wrong with the above?


Why do you think anything is wrong?  Post the actual error message 
separate from the code that generates the error message.


> Does email choke on Unicode?

tjr

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


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Jonathan Gardner
On Jan 5, 2:26 pm, Kangkook Jee  wrote:
> I'd like to measure number of bytes sent(or recv'd) from my python
> application. Does anyone have any idea how can I achieve this?
>
> I tried to do this by tracing some socket calls (send, sendto, sendAll)
>   using 'metaclass' but I could find exactly place that I can put this in.
>
> My application runs some number of protocols (bittorrent, xmlrpc ..) in
> it and will be measured for a couple of hours.
>

A good universal tool on the Linux platform is tcpdump. It takes some
learning, but is very useful for this kind of task. You can use a tool
like ethereal to visualize the data that tcpdump gathers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: replacement for __file__ in compiled exe

2009-01-05 Thread TechieInsights
Yes, that is my exact question.  How do you get the file path of your
script/program.  Normally in python you can use __file__ and it will
return the file path of the script you are in, however, when you
compile the script to exe py2exe (or whatever util you are using)
compresses them into a zip folder... not usually a problem, except
when you want the access the file path of the exe.

Thanks for the answer... I should have thought of that all along...
just look on the system path.  Sometimes the answer was right in front
of your face the whole time...

Greg



On Jan 5, 1:51 pm, John Machin  wrote:
> On Jan 6, 7:03 am, TechieInsights  wrote:
>
> > __file__ command does not work when compiled to exe.  It makes since
> > because the file is now in a compressed library.  Is there a
> > replacement or something else you can do?  The real problem is that
> > when you create an exe of your program with python embedded, you can't
> > always guarantee that your current directory is the directory of your
> > program.
>
> How can you *ever* guarantee that the current directory is the same as
> the directory in which the program resides? This lack of guarantee is
> quite independent of whether the "program" is .py, .exe, .bat, .com,
> etc. Isn't the real problem how to find out which directory the
> program is in?
>
> >  I guess when you could just set a registry entry on
> > windows... but it would be nice to have a quick fix for this (like
> > os.path.dirname(__file__)).
>
>     if hasattr(sys, 'frozen'):
>         answer = os.path.split(sys.executable)[0]
>     else:
>         answer = os.path.split(sys.argv[0])[0]
>
> (maybe) ... your question is a little unclear.
>
> HTH,
> John

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


Re: why cannot assign to function call

2009-01-05 Thread Rhodri James
On Mon, 05 Jan 2009 22:28:59 -, Steven D'Aprano  
 wrote:



* That only languages "substantially taught" in undergraduate CS courses
matter.


As an aside, I use only one of the languages I was taught in my Computer
Science course, and that only for poking my EMACS configuration.  Every
other language I use (yes, including C) I learned afterwards.

Moral: times change.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Kangkook Jee

Jonathan Gardner wrote:

On Jan 5, 2:26 pm, Kangkook Jee  wrote:

I'd like to measure number of bytes sent(or recv'd) from my python
application. Does anyone have any idea how can I achieve this?

I tried to do this by tracing some socket calls (send, sendto, sendAll)
  using 'metaclass' but I could find exactly place that I can put this in.

My application runs some number of protocols (bittorrent, xmlrpc ..) in
it and will be measured for a couple of hours.



A good universal tool on the Linux platform is tcpdump. It takes some
learning, but is very useful for this kind of task. You can use a tool
like ethereal to visualize the data that tcpdump gathers.


Thanks a lot Jonathan

That seems like a good solution for my issue but how can I distinguish 
traffics from my application to others?


I'm still struggling to solve it within python process since it looks 
cleaner but it doesn't seems to be easy at all.

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


Re: multiprocessing vs thread performance

2009-01-05 Thread alex goretoy
There doesn't seem to be any good examples on POSH or it's not clear to me.
For when using with a for loop like mk is doing who started this thread. How
would somethings like this be possible to do with POSH? The example show how
to share variables between processes/threads but nothing about How the
thread starts or a for loop.

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Sat, Jan 3, 2009 at 1:31 PM, Nick Craig-Wood  wrote:

> mk  wrote:
> >  After reading http://www.python.org/dev/peps/pep-0371/ I was under
> >  impression that performance of multiprocessing package is similar to
> >  that of thread / threading. However, to familiarize myself with both
> >  packages I wrote my own test of spawning and returning 100,000 empty
> >  threads or processes (while maintaining at most 100 processes / threads
> >  active at any one time), respectively.
> >
> >  The results I got are very different from the benchmark quoted in PEP
> >  371. On twin Xeon machine the threaded version executed in 5.54 secs,
> >  while multiprocessing version took over 222 secs to complete!
> >
> >  Am I doing smth wrong in code below?
>
> Yes!
>
> The problem with your code is that you never start more than one
> process at once in the multiprocessing example.  Just check ps when it
> is running and you will see.
>
> My conjecture is that this is due to the way fork() works under unix.
> I think that when the parent forks it yields the CPU to the child.
> Because you are giving the child effectively no work to do it returns
> immediately, re-awakening the parent, thus serialising your jobs.
>
> If you give the children some work to do you'll see a quite different
> result.  I gave each child time.sleep(1) to do and cut down the total
> number to 10,000.
>
> $ ./test_multiprocessing.py
> == Process 1000 working ==
> == Process 2000 working ==
> == Process 3000 working ==
> == Process 4000 working ==
> == Process 5000 working ==
> == Process 6000 working ==
> == Process 7000 working ==
> == Process 8000 working ==
> == Process 9000 working ==
> == Process 1 working ==
> === Main thread waiting for all processes to finish ===
> Total time: 101.382129192
>
> $ ./test_threading.py
> == Thread 1000 working ==
> == Thread 2000 working ==
> == Thread 3000 working ==
> == Thread 4000 working ==
> == Thread 5000 working ==
> == Thread 6000 working ==
> == Thread 7000 working ==
> == Thread 8000 working ==
> == Thread 9000 working ==
> == Thread 1 working ==
> Total time:  100.659118176
>
> So almost identical results and as expected - we ran 10,000 sleep(1)s
> in 100 seconds so we must have been running 100 simultaneously.
>
> If you replace the "time.sleep(1)" with "for _ in xrange(100):
> pass" you get this much more interesting answer on my dual core linux
> laptop, showing nicely the effect of the contention on the python
> global interpreter lock and how multiprocessing avoids it.
>
> $ ./test_multiprocessing.py
> == Process 1000 working ==
> == Process 2000 working ==
> == Process 3000 working ==
> == Process 4000 working ==
> == Process 5000 working ==
> == Process 6000 working ==
> == Process 7000 working ==
> == Process 8000 working ==
> == Process 9000 working ==
> == Process 1 working ==
> === Main thread waiting for all processes to finish ===
> Total time: 266.808327913
>
> $ ./test_threading.py
> == Thread 1000 working ==
> == Thread 2000 working ==
> == Thread 3000 working ==
> == Thread 4000 working ==
> == Thread 5000 working ==
> == Thread 6000 working ==
> == Thread 7000 working ==
> == Thread 8000 working ==
> == Thread 9000 working ==
> == Thread 1 working ==
> Total time:  834.81882
>
> --
> Nick Craig-Wood  -- http://www.craig-wood.com/nick
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Jonathan Gardner
On Jan 5, 3:23 pm, Kangkook Jee  wrote:
> Jonathan Gardner wrote:
> > A good universal tool on the Linux platform is tcpdump. It takes some
> > learning, but is very useful for this kind of task. You can use a tool
> > like ethereal to visualize the data that tcpdump gathers.
>
> That seems like a good solution for my issue but how can I distinguish
> traffics from my application to others?
>

There are a variety of ways to distinguish traffic with tcpdump and
ethereal. Usually you should have some idea of what ports or hosts
your traffic is going to. If not, then you will have some indicator
within the packets themselves. Note that tcpdump is remarkable since
it can identify TCP sessions, and not just individual packets.

> I'm still struggling to solve it within python process since it looks
> cleaner but it doesn't seems to be easy at all.

Replacing a lower-level component of a 3rd party library is difficult
at best. If you can get it to work without rewriting the library,
congratulations. At the very least, you'll probably have to do some
low-level things within the libraries themselves.
--
http://mail.python.org/mailman/listinfo/python-list


Is there a best linux distro for a python hobbyist?

2009-01-05 Thread member thudfoo
One with all the major python GUIs: pyQT, pyGtk, pyKde, wxPython, 
And so on.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread James Mills
On Tue, Jan 6, 2009 at 8:26 AM, Kangkook Jee  wrote:
> I'd like to measure number of bytes sent(or recv'd) from my python
> application. Does anyone have any idea how can I achieve this?
>
> I tried to do this by tracing some socket calls (send, sendto, sendAll)
>  using 'metaclass' but I could find exactly place that I can put this in.
>
>
> My application runs some number of protocols (bittorrent, xmlrpc ..) in
> it and will be measured for a couple of hours.
>
> Thanks a lot for your help, in advance

Something like this perhaps ? Example code
follows ... NB: This uses circuits (1)

$ ./test.py smtp-int.vision6.com.au 25
Trying smtp-int.vision6.com.au...
Connected to smtp-int.vision6.com.au
220 marvin.vision6.com.au ESMTP
EHLO localhost
250-marvin.vision6.com.au
250-AUTH LOGIN CRAM-MD5 PLAIN
250-AUTH=LOGIN CRAM-MD5 PLAIN
250-PIPELINING
250 8BITMIME
QUIT
221 marvin.vision6.com.au
Connection closed
Traffic
 In: 179 bytes
 Out: 20 bytes

-
http://codepad.org/V32fsqKt

Note the Stats component on line 60.
-

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


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread alex goretoy
Have you looked into scapy?

www.secdev.org/projects/*scapy*/

There's another one, it comes with python I think. Can't seem to remember
the name. I may be mistaken though.

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 5, 2009 at 11:23 PM, Kangkook Jee  wrote:

> Jonathan Gardner wrote:
>
>> On Jan 5, 2:26 pm, Kangkook Jee  wrote:
>>
>>> I'd like to measure number of bytes sent(or recv'd) from my python
>>> application. Does anyone have any idea how can I achieve this?
>>>
>>> I tried to do this by tracing some socket calls (send, sendto, sendAll)
>>>  using 'metaclass' but I could find exactly place that I can put this in.
>>>
>>> My application runs some number of protocols (bittorrent, xmlrpc ..) in
>>> it and will be measured for a couple of hours.
>>>
>>>
>> A good universal tool on the Linux platform is tcpdump. It takes some
>> learning, but is very useful for this kind of task. You can use a tool
>> like ethereal to visualize the data that tcpdump gathers.
>>
>
> Thanks a lot Jonathan
>
> That seems like a good solution for my issue but how can I distinguish
> traffics from my application to others?
>
> I'm still struggling to solve it within python process since it looks
> cleaner but it doesn't seems to be easy at all.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Regex Generator From Multiple Files

2009-01-05 Thread James Pruitt
I am looking for a way given a number of files, say 3, that represent
technical support tickets in the same format to generate regular expressions
for the different fields automatically.

An example from of one line from each file:
Date: 12/30/2008 Room: 457 Building: Main
Date: 12/31/2008 Room: A21 Building: Annex
Date: 1/4/2009 Room: L69 Building: Library

The program would then, possibly using the python diff library, generate the
regular expression needed to parse out different fields. In this case it
might return a tuple like
("^Date:[\w]+(.*)[\w]+Room","Room:[\w]+(.*)[\w]+Building","Building:[\w]+(.*)[\w]+$")
that would match each of the fields based on the common data and sort of
assume that what doesn't change between them is data we are looking for.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extending Python with C or C++

2009-01-05 Thread Ryan
On Jan 5, 2:37 pm, Terry Reedy  wrote:
> Ryan wrote:
> > I've been using Python for many years now. It's a wonderful language
> > that I enjoy using everyday. I'm now interested in getting to know
> > more about the guts
>
> The 'guts' of Python the language include the object model, namespaces
> (including modules), and the statement and infix-expression syntax.
>
> > (C/C++) and extending it.
>
> Now you are asking about CPython, the leading computer implementation.
>
> > But, extending python still seems like a black art to me.
>
>  > Is there anymore docs or info on
>
> > extending it besides the standard sparse ones (http://www.python.org/
> > doc/2.5.2/ext/intro.html) that may give me more insight? Is there a
> > class available?
>
> If you want to connect CPython to Python-oblivious code written in C,
> Swig (with C code) and Ctypes (with Python code) are the main choices.
> If you want to write new Python-aware (and specific) code, you can use
> the CPython C-API functions.  Extensions in C are written as importable
> modules.  The interface for such is not difficult; existing examples
> should be a good guide.
>
>  > How can I learn more about the guts of python?
>
> The 'guts' of an implementation follow from the 'guts' of the language.
>   There must be a syntax parser and compiler to internal form,
> evaluation loop, and implemenations of built-in constants, functions,
> classes, and modules.  CPython's source tree begins 
> ashttp://svn.python.org/view/
> You might actually want to start athttp://svn.python.org/view/python/trunk/
> Note: if you click a filename, such as 'setup.py', you get the entire
> revision history with checkin messages.
> If you click the displayed revision number, such as '67978', you get the
> latest checkin message and the current version of the file.
>
> > How would one go about following an interest in contributing to the
> > development of python.
>
> Readhttp://python.org/dev/
> and start following the pydev list, mirrored to gmane.comp.python.devel
> at news.gmane.org.
>
> Terry Jan Reedy

Thanks Terry! This clarifies many of the concepts that I want to get
started to dive deeper into CPython.

1. The abstract Python Language (not specific to any implementation)
2. The CPython implementation (http://svn.python.org/view/python/
trunk/)
3. Extending CPython by connecting it to Python-oblivious code written
in C with Ctypes (Ralf's suggestion is good for this)
4. Extending CPython by connecting it to Python-aware (and specific)
code using the CPython C-API functions (http://docs.python.org/c-api/)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regex Generator From Multiple Files

2009-01-05 Thread MRAB

James Pruitt wrote:
I am looking for a way given a number of files, say 3, that represent 
technical support tickets in the same format to generate regular 
expressions for the different fields automatically.


An example from of one line from each file:
Date: 12/30/2008 Room: 457 Building: Main
Date: 12/31/2008 Room: A21 Building: Annex
Date: 1/4/2009 Room: L69 Building: Library

The program would then, possibly using the python diff library, generate 
the regular expression needed to parse out different fields. In this 
case it might return a tuple like 
("^Date:[\w]+(.*)[\w]+Room","Room:[\w]+(.*)[\w]+Building","Building:[\w]+(.*)[\w]+$") 
that would match each of the fields based on the common data and sort of 
assume that what doesn't change between them is data we are looking for.


Why not just assume that each field consists of a word terminated by a 
colon, then some text, then the next field or the end of the line?

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


Re: socket send help

2009-01-05 Thread Bryan Olson

Gabriel Genellina wrote:

Bryan Olson escribió:


Gabriel Genellina wrote:

greyw...@gmail.com escribió:

[...]

A simple server:

from socket import *
myHost = ''
 Try with myHost = '127.0.0.1' instead - a firewall might be blocking 
your server.


Just a nit: I'd say the reason to use '127.0.0.1' instead of the empty 
string is that a firewall might *not* be blocking your server.


The Python sockets module interprets the empty string as INADDR_ANY, 
which means to bind to all available adapters including the loopback, 
A.K.A localhost, A.K.A '127.0.0.1'.


I thought a firewall would block an attempt to bind to any routeable 
address, but not to localhost. So using INADDR_ANY would be rejected.


So you thought this would fail at bind()?

My understanding is that firewalls block network traffic, not system calls.


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


Re: socket send help

2009-01-05 Thread James Mills
On Tue, Jan 6, 2009 at 10:49 AM, Bryan Olson  wrote:
>> I thought a firewall would block an attempt to bind to any routeable
>> address, but not to localhost. So using INADDR_ANY would be rejected.

No.

> My understanding is that firewalls block network traffic, not system calls.

This is correct. Firewalls (real firewalls) can only act on incoming
and outgoing traffic on the IP level.

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


Re: socket send help

2009-01-05 Thread James Mills
On Wed, Dec 24, 2008 at 3:59 PM, greyw...@gmail.com  wrote:
(snip)

> If I run testserver.py via the cmd prompt in Windows XP and then the
> testclient.py program, I get the following error:
>
> Traceback (most recent call last):
>  File "C:\Python30\testclient.py", line 12, in 
>s.send('Hello world')   # send the data
> TypeError: send() argument 1 must be string or buffer, not str
>
> This happens in 2.6 or 3.0 and with different example client & server
> programs from the web.  What am I missing?

I'm sorry I should have answered sooner :)
Python 3.x (and probably 2.6+) required that you use
bytes to send your data through sockets rather than
strings. This was part of the revamp for better unicode
support irrc.

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


cPickle vs pickle discrepancy

2009-01-05 Thread Zac Burns
Greetings,

I have a module that attempts to pickle classes defined in that module.

I get an error of the form:
PicklingError: Can't pickle : import
of module Module.SubModule failed
when using cPickle (protocol -1, python version 2.5.1).

The module has already been imported and is in sys.modules when the
exception is raised.

Using pickle instead of cPickle works, but the section of the code is
performance critical.

How can this be worked around?

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rich Comparisons Gotcha

2009-01-05 Thread Mark Wooding
Steven D'Aprano  wrote:

> There is nothing to blame them for. This is the correct behaviour. NaNs 
> should *not* compare equal to themselves, that's mathematically 
> incoherent.

Indeed.  The problem is a paucity of equality predicates.  This is
hardly surprising: Common Lisp has four general-purpose equality
predicates (EQ, EQL, EQUAL and EQUALP), and many more type-specific ones
(=, STRING=, STRING-EQUAL (yes, I know...), CHAR=, ...), and still
doesn't really have enough.  For example, EQUAL compares strings
case-sensitively, but other arrays are compared by address; EQUALP will
recurse into arbitrary arrays, but compares strings
case-insensitively...

For the purposes of this discussion, however, it has enough to be able
to distinguish between

  * numerical comparisons, which (as you explain later) should /not/
claim that two NaNs are equal, and

  * object comparisons, which clearly must declare an object equal to
itself.

For example, I had the following edifying conversation with SBCL.

CL-USER> ;; Return NaNs rather than signalling errors.
 (sb-int:set-floating-point-modes :traps nil)
; No value
CL-USER> (defconstant nan (/ 0.0 0.0))
NAN
CL-USER> (loop for func in '(eql equal equalp =)
   collect (list func (funcall func nan nan)))
((EQL T) (EQUAL T) (EQUALP T) (= NIL))
CL-USER>

That is, a NaN is EQL, EQUAL and EQUALP to itself, but not = to itself.
(Due to the vagaries of EQ, a NaN might or might not be EQ to itself or
other NaNs.)

Python has a much more limited selection of equality predicates -- in
fact, just == and is.  The is operator is Python's equivalent of Lisp's
EQ predicate: it compares objects by address.  I can have a similar chat
with Python.

In [12]: nan = float('nan')

In [13]: nan is nan
Out[13]: True

In [14]: nan == nan
Out[14]: False

In [16]: nan is float('nan')
Out[16]: False

Python numbers are the same as themselves reliably, unlike in Lisp.  But
there's no sensible way of asking whether something is `basically the
same as' nan, like Lisp's EQL or EQUAL.  I agree that the primary
equality predicate for numbers must be the numerical comparison, and
NaNs can't (sensibly) be numerically equal to themselves.

Address comparisons are great when you're dealing with singletons, or
when you carefully intern your objects.  In other cases, you're left
with ==.  This puts a great deal of responsibility on the programmer of
an == method to weigh carefully the potentially conflicting demands of 
compatibility (many other libraries just expect == to be an equality
operator returning a straightforward truth value, and given that there
isn't a separate dedicated equality operator, this isn't unreasonable),
and doing something more domain-specifically useful.

It's worth pointing out that numpy isn't unique in having == not return
a straightforward truth value.  The SAGE computer algebra system (and
sympy, I believe) implement the == operator on algebraic formulae so as
to construct equations.  For example, the following is syntactically and
semantically Python, with fancy libraries.

sage: var('x')  # x is now a variable
x
sage: solve(x**2 + 2*x - 4 == 1)
[x == -sqrt(6) - 1, x == sqrt(6) - 1]

(SAGE has some syntactic tweaks, such as ^ meaning the same as **, but I
didn't use them.)

I think this is an excellent use of the == operator -- but it does have
some potential to interfere with other libraries which make assumptions
about how == behaves.  The SAGE developers have been clever here,
though:

sage: 2*x + 1 == (2 + 4*x)/2
2*x + 1 == (4*x + 2)/2
sage: bool(2*x + 1 == (2 + 4*x)/2)
True
sage: bool(2*x + 1 == (2 + 4*x)/3)
False

I think Python manages surprisingly well with its limited equality
predicates.  But the keyword there is `surprisingly' -- and it may not
continue this trick forever.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a best linux distro for a python hobbyist?

2009-01-05 Thread david.lyon
Hi,

I would have to put in a vote for Ubuntu.

There seems to be a working ubuntu package for most of the things that I
have tried. Instead of having to use a pythonic package - just get one from
the os.

As for the things you mention.. give it a go

On Mon, 5 Jan 2009 15:42:00 -0800, "member thudfoo" 
wrote:
> One with all the major python GUIs: pyQT, pyGtk, pyKde, wxPython, 
> And so on.


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


Re: Is there a best linux distro for a python hobbyist?

2009-01-05 Thread alex goretoy
+1 for ubuntu

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Tue, Jan 6, 2009 at 12:39 AM,  wrote:

> Hi,
>
> I would have to put in a vote for Ubuntu.
>
> There seems to be a working ubuntu package for most of the things that I
> have tried. Instead of having to use a pythonic package - just get one from
> the os.
>
> As for the things you mention.. give it a go
>
> On Mon, 5 Jan 2009 15:42:00 -0800, "member thudfoo" 
> wrote:
> > One with all the major python GUIs: pyQT, pyGtk, pyKde, wxPython, 
> > And so on.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a best linux distro for a python hobbyist?

2009-01-05 Thread James Mills
On Tue, Jan 6, 2009 at 11:11 AM, alex goretoy
 wrote:
> +1 for ubuntu
+1 for Ubuntu also (for the novice and ex-windows user(s))

+2 for CRUX (1)

cheers
James

1. http://crux.nu/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a best linux distro for a python hobbyist?

2009-01-05 Thread Lex Hider
Probably not a big difference in most cases between debian, ubuntu,
fedora. The latter two may be more likely to have more recent
versions.

I'm pretty sure ubuntu is the only one which currently has python 3.0
in it's archives [no, it's not the default version].

On 06/01/2009, member thudfoo  wrote:
> One with all the major python GUIs: pyQT, pyGtk, pyKde, wxPython, 
> And so on.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rich Comparisons Gotcha

2009-01-05 Thread Mark Wooding
Steven D'Aprano  wrote:

> I've already mentioned NaNs. Sentinel values also sometimes need to
> compare not equal with themselves. Forcing them to compare equal will
> cause breakage.

There's a conflict between such domain-specific considerations (NaNs,
strange sentinels, SAGE's equations), and relatively natural assumptions
about an == operator, such as it being an equivalence relation.

I don't know how to resolve this conflict without introducing a new
function which is (or at least strongly encourages developers to arrange
for it to be) an equivalence relation.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Steven D'Aprano
On Mon, 05 Jan 2009 18:23:10 -0500, Kangkook Jee wrote:

> Jonathan Gardner wrote:
>> On Jan 5, 2:26 pm, Kangkook Jee  wrote:
>>> I'd like to measure number of bytes sent(or recv'd) from my python
>>> application. Does anyone have any idea how can I achieve this?
>>>
>>> I tried to do this by tracing some socket calls (send, sendto,
>>> sendAll)
>>>   using 'metaclass' but I could find exactly place that I can put this
>>>   in.
>>>
>>> My application runs some number of protocols (bittorrent, xmlrpc ..)
>>> in it and will be measured for a couple of hours.
>>>
>>>
>> A good universal tool on the Linux platform is tcpdump. It takes some
>> learning, but is very useful for this kind of task. You can use a tool
>> like ethereal to visualize the data that tcpdump gathers.
> 
> Thanks a lot Jonathan
> 
> That seems like a good solution for my issue but how can I distinguish
> traffics from my application to others?
> 
> I'm still struggling to solve it within python process since it looks
> cleaner but it doesn't seems to be easy at all.


A relatively straightforward, if not totally accurate, way of doing that 
is to create a layer between your application code and the network 
libraries, and have the layer measure the amount of data you send before 
it reaches the specific protocols being used. 

Naturally this won't give you a totally accurate count of network traffic 
sent from your application, since every protocol includes some overhead, 
but that might not matter for your use-case.



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


Re: why cannot assign to function call

2009-01-05 Thread Aaron Brady
On Jan 4, 1:28 am, Steven D'Aprano  wrote:
> I'm answering both John and Aaron's comments in the following. Mostly
> John at the start, Aaron toward the end.
>
> On Sat, 03 Jan 2009 15:42:47 -0800, Aaron Brady wrote:
> > On Jan 3, 11:25 am, John O'Hagan  wrote:
>
> [...]
>
> > > >According to this, when you replace every floorboard on a porch, one
> > > >at a time, it's still the same porch-- it's changed, it's different,
> > > >and it's the same.  However, if you haul off the porch and put a new
> > > >one in its place, it's not.  ('porch[:]=' vs. 'porch='.)  You can't
> > > >just look at the initial and final configurations of matter to
> > > >determine so.  Therefore, 'id' is an informal function.
>
> > > This analogy describes the "ontological minefield" I was referring to
> > > in a previous post in this thread (which has expired in my mail
> > > reader, so my apologies if the threading goes awry): In what sense is
> > > a porch (or list, or string) the same if all (or even some of) its
> > > parts have been exchanged?
>
> > > I think the answer is something to do with the abstraction, the
> > > "container", the instance of the class.
>
> That seems reasonable. When you say alist[:] = [1, 2, 3] the container
> remains "the same", while the contents change.
>
> > > Would it be fair to say that perhaps there are no
> > > truly mutable objects, only immutable containers whose contents (also
> > > immutable objects themselves) may be exchanged? Or to pose the
> > > question another way, are objects only mutable insofar as they are
> > > composite?
>
> That depends on what you mean by composite. Everything is composite in
> some sense, even a single bit in memory has a physical reality made of
> atoms with magnetic fields. But taken as an abstract entity, it is
> reasonable to treat a single bit as an atomic non-composite thing, and a
> single bit is mutable.
>
> In practice, actual Python objects tend to be mutable only if they are
> composite (although being composite doesn't make them mutable -- consider
> frozen sets and tuples). In principle, this is not necessary. There's no
> reason why Python couldn't expose a single bit as a data type, so you
> could write this:
>
> >>> n = bit(1)
> >>> bool(n)
> True
> >>> n.flip()
> >>> bool(n)
>
> False
>
> > > As you argue above, the planks are not the porch; I would add that
> > > it's your _decision_ to build (or tear down) a porch which makes it
> > > _that_  particular porch (or not).
>
> No, there's no such decision needed. Perhaps a hurricane comes through
> and rips the porch up. Maybe a rogue television crew comes by while
> you're at work and renovates your house without your knowledge.
>
> The lack of decision-making needed is more obvious when you consider
> something like a fast-flowing river. The specific water molecules making
> up the river at any particular instant in time flow away in a matter of
> days or weeks, but rivers have a continuity of existence measured in
> thousands of years. I trust that nobody is going to argue that the river
> makes any decisions at all?
>
> > > As you imply above (I think), you have to keep looking (or someone
> > > does, presumably the interpreter) to know whether an object is the
> > > same as or just equal to another (which starts to sound spookily like
> > > the role of "the observer" in phenomenology or quantum physics).
>
> No, I think you're introducing mysticism here that isn't needed. A bit
> like quantum mechanics, really :)
>
> In Python, every object has an identity and a value. If objects X and Y
> have the same identity, they are the same object. If X is the object with
> id 1234, and Y is the object with id 1234, then both are the same object.
> If their ids are different, then they are not.
>
> In CPython, the id is given by the memory location of the object, which
> leads to a very intuitive understanding of "same": the object with id
> 1234 is at memory location 1234, and since there can only be one object
> at a particular memory location at a time, obviously all objects with id
> 1234 must be the same object (provided they exist simultaneously).
>
> (To be pedantic, there can't actually be objects [note plural] existing
> simultaneously with the same id. There can only be multiple references to
> the one object.)
>
> In Python implementations where the id is not a memory address
> (IronPython and Jython I think?) the above remains true, even though
> there isn't the simple intuitive picture of "only one object can be at a
> specific memory address". Python guarantees that the id is *something*
> which is guaranteed to be unique over the lifetime of every object.
>
> Actually, our intuition about one thing per place at the one time is not
> strictly correct. Consider the memory address 1234, which currently has
> the value in hex of 0x58. That byte may be the numeric value 88, the
> ASCII char "X", the set of flags 1011000, or any other thing, depending
> on what interpretation we give to it.

Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Grant Edwards
On 2009-01-05, Jonathan Gardner  wrote:
> On Jan 5, 2:26 pm, Kangkook Jee  wrote:
>>
>> I'd like to measure number of bytes sent(or recv'd) from my
>> python application. Does anyone have any idea how can I
>> achieve this?
>>
>> I tried to do this by tracing some socket calls (send, sendto,
>> sendAll) using 'metaclass' but I could find exactly place that
>> I can put this in.
>>
>> My application runs some number of protocols (bittorrent,
>> xmlrpc ..) in it and will be measured for a couple of hours.
>
> A good universal tool on the Linux platform is tcpdump. It takes some
> learning, but is very useful for this kind of task. You can use a tool
> like ethereal to visualize the data that tcpdump gathers.

Ethereal has been called wireshark for quite a while now.  It
can be used to capture the traffic as well as to visualize it.

Wireshark is available for both Linux and Windows.

-- 
Grant

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


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Grant Edwards
On 2009-01-05, Kangkook Jee  wrote:
> Jonathan Gardner wrote:
>> On Jan 5, 2:26 pm, Kangkook Jee  wrote:
>>> I'd like to measure number of bytes sent(or recv'd) from my python
>>> application. Does anyone have any idea how can I achieve this?
>>>
>>> I tried to do this by tracing some socket calls (send, sendto, sendAll)
>>>   using 'metaclass' but I could find exactly place that I can put this in.
>>>
>>> My application runs some number of protocols (bittorrent, xmlrpc ..) in
>>> it and will be measured for a couple of hours.
>>>
>> 
>> A good universal tool on the Linux platform is tcpdump. It takes some
>> learning, but is very useful for this kind of task. You can use a tool
>> like ethereal to visualize the data that tcpdump gathers.
>
> Thanks a lot Jonathan
>
> That seems like a good solution for my issue but how can I distinguish 
> traffics from my application to others?

You can't predict ahead of time what hosts/ports that your
application is going to be using?

> I'm still struggling to solve it within python process since
> it looks cleaner but it doesn't seems to be easy at all.

I don't why adding bunches of code to your app would be
"cleaner" than gathering data using external programs.

-- 
Grant

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


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread Grant Edwards
On 2009-01-05, Kangkook Jee  wrote:

> I'd like to measure number of bytes sent(or recv'd) from my
> python application. Does anyone have any idea how can I
> achieve this?

Aside from tcpdump/wireshark, you can set up iptables rules to
enable accounting for traffic based on IP addresses and ports.

http://wiki.openvz.org/Traffic_accounting_with_iptables
http://www.faqs.org/docs/linux_network/x-087-2-accounting.ipfwadm.html
http://www.catonmat.net/blog/traffic-accounting-with-iptables/

-- 
Grant

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


Re: Rich Comparisons Gotcha

2009-01-05 Thread Steven D'Aprano
On Tue, 06 Jan 2009 01:24:58 +, Mark Wooding wrote:

> Steven D'Aprano  wrote:
> 
>> I've already mentioned NaNs. Sentinel values also sometimes need to
>> compare not equal with themselves. Forcing them to compare equal will
>> cause breakage.
> 
> There's a conflict between such domain-specific considerations (NaNs,
> strange sentinels, SAGE's equations), and relatively natural assumptions
> about an == operator, such as it being an equivalence relation.

Such assumptions only hold under particular domains though. You can't 
assume equality is an equivalence relation once you start thinking about 
arbitrary domains.


> I don't know how to resolve this conflict without introducing a new
> function which is (or at least strongly encourages developers to arrange
> for it to be) an equivalence relation.

But there cannot be any such function which is a domain-independent 
equivalence relation, not if we're talking about arbitrarily wacky 
domains. Even something as straight-forward as "is" can't be an 
equivalence relation under a domain where identity isn't well-defined.


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


Re: idle 3.0 unicode

2009-01-05 Thread Gabriel Genellina

En Thu, 01 Jan 2009 06:11:50 -0200, Pavel Kosina  escribió:

In 3.0 there is an error.  The same program, moved to 3.0 syntax, in  
IDLE editor :

# -*- coding: utf-8 -*-
print ("ěščřžýáíé")

prints:
ěščřžýáíé

The same program without coding declaration (but saved in utf8) :
print ("ěščřžýáíé")

even immediately destroyed my IDLE window without any error message.


There are some unicode-related errors reported for IDLE and 3.0, but I  
could not find this one. Better to file a bug report at  
http://bugs.python.org


--
Gabriel Genellina

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


Diff Across Multiple Files

2009-01-05 Thread James Pruitt
I am looking for a way to diff across multiple files; on average around 30
to 60 using python and probably the diff library so that we could see what
is common between all files and sort of ignore the differences.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-05 Thread Gabriel Genellina
En Sat, 03 Jan 2009 02:55:12 -0200, Kottiyath   
escribió:



tuples = [(1, 2), (3, 4, 5), (6, 7)]


It is a code to post some data to HTML server.
Even though usually the POST values are of type(name, value), if file
transfer is involved, then POST values change to (name, filename,
value).
My view was that since filename is a rare occurance and doesnt make
sense in a usual POST, I had not kept it as a full 3 tuple.
Since so many programmers (that too much more capable than me) are
suggesting that it is code smell, I am reviewing my decision.


What about using another data structure instead - like this:

class entry:
  filename = None

  def __init__(self, name, value, filename=None):
self.name = name
self.value = value
if filename is not None:
  self.filename = filename

[entry('name', 'Gabriel'), entry('age', 18), entry('pic', picture_data,  
'path/to/file')]


--
Gabriel Genellina

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


Re: Measuring bytes of packet sent from python application

2009-01-05 Thread alex goretoy
You can alot run "lsof -i -T -n" from popen2 to see what applications use
what port and addr they are connected to.
In order to see all jobs though it needs to be ran as root. This way you can
find out what ports and such Then perform tcp dump thru popen2 and filter
for port and addr. This is just a first shot, then I would figure out what
to do after having gotten to this point.

import popen2
#find out what ports and addrs what program is connected to
r,w,e=popen2.popen3("lsof -i -T -n") # this may need sudo prepended to lsof
r=r.readlines()
e=e.readlines()
#get tcpdump, doesn't quiet work hereneeds something more, maybe a
different way altogether.
#tcpdump to pcap file and read file periodically?
r1,w1,e1=popen2.popen3("sudo tcpdump -i eth1")
r1=r1.readlines()
e1=e1.readlines()

Something to this nature, then do regular expression on tcpdump output,
either logged to pcap output file or by other means.

-Alex Goretoy
http://www.alexgoretoy.com
somebodywhoca...@gmail.com


On Mon, Jan 5, 2009 at 8:14 PM, Grant Edwards  wrote:

> On 2009-01-05, Kangkook Jee  wrote:
>
> > I'd like to measure number of bytes sent(or recv'd) from my
> > python application. Does anyone have any idea how can I
> > achieve this?
>
> Aside from tcpdump/wireshark, you can set up iptables rules to
> enable accounting for traffic based on IP addresses and ports.
>
> http://wiki.openvz.org/Traffic_accounting_with_iptables
> http://www.faqs.org/docs/linux_network/x-087-2-accounting.ipfwadm.html
> http://www.catonmat.net/blog/traffic-accounting-with-iptables/
>
> --
> Grant
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >