[pygtk] ANNOUNCE: PyGObject 2.15.0

2008-07-15 Thread Johan Dahlin

I am pleased to announce version 2.15.0 of the Python bindings for GObject.

The new release is available from ftp.gnome.org as and its mirrors
as soon as its synced correctly:

  http://download.gnome.org/sources/pygobject/2.15/

There are two new significant features in this release, initial
bindings for GIO. Note that these are not complete, please report
missing API in Bugzilla so we know what people are missing.
Codegen has been moved from PyGTK and can now be used without
depending on GTK+, which should be useful for GObject based libraries.

What's new since PyGObject 2.14.x?
- Add GIO bindings (Johan, Mario Tagliaretti, Thomas Leonard)
- Move codegen from PyGTK (Johan, Paul Pogonyshev, #542821)
- Add more variables to the .pc files (Damien Carbery, Paul,
  Dan Winship, #486876)
- Add pyg_option_group_new to the public API (Johan)
- Add g_get_application_anme and g_get_progname (Sebastian Rittau)
- Avoid making wakeups when using Python 2.6 (Johan, Gustavo,
  Adam Olsen, Josselin Mouette, Philippe Normand, Guido Van Rossum)
- Only link against libffi when found (Ed Catmur, #496006)
- Improve gobject.property (Tomeu Vizoso, #523352)
- Improve enum comparision and warnings (Paul, Phil Dumont, #428732)
- Many gobject.Source improvements (Bryan Silverthorn)
- Apply some fixes to make pylint happier (Johan, Simon Schampijer,
  #523821)
- Fix error message in pyg_io_add_watch (Juha Sahkangas)
- Improve h2def.py (Oliver Crete, Murray Cumming, Lauro Moura)

Blurb:

GObject is a object system library used by GTK+ and GStreamer.

PyGObject provides a convenient wrapper for the GObject+ library for use
in Python programs, and takes care of many of the boring details such as
managing memory and type casting.  When combined with PyGTK, PyORBit and
gnome-python, it can be used to write full featured Gnome applications.

Like the GObject library itself PyGObject is licensed under the
GNU LGPL, so is suitable for use in both free software and proprietary
applications.  It is already in use in many applications ranging
from small single purpose scripts up to large full
featured applications.

PyGObject requires glib = 2.8.0 and Python = 2.3.5 to build.
GIO bindings require glib = 2.16.0.

--
Johan Dahlin
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-announce-list

   Support the Python Software Foundation:
   http://www.python.org/psf/donations.html


Re: Python pack and unpack question

2008-07-15 Thread Mark Tolonen


joe shoemaker [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

If you have the following:

 data = unpack('L', sock.recv(4))

Does this line of code means that incoming data is big endian and
unpack it to endianess of local machine? If local machine is little
endian, then big endian is automatically converted to little endian
format?

thank you.


Try it:


data = unpack('L','\xaa\xbb\xcc\xdd')
data

(2864434397L,)

hex(data[0])

'0xaabbccddL'

data = unpack('L','\x11\x22\x33\x44')
data

(287454020,)

hex(data[0])

'0x11223344'




Yes, it treats the incoming data as big-endian.  The Python data type 
returned varies as needed to hold the value.  You'd get the same results on 
a big-endian and little-endian local machine.  How the Python data type is 
represented internally is an implementation detail and could be anything.

--
Mark 


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


Re: new itertools functions in Python 2.6

2008-07-15 Thread Raymond Hettinger
On Jul 14, 1:26 pm, Mensanator [EMAIL PROTECTED] wrote:
 ##  Combinations with replacement
 ##  -
 ##  aaa aab aac aad aae abb abc abd abe acc acd ace
 ##  add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde
 ##  bee ccc ccd cce cdd cde cee ddd dde dee eee
 ##
 ##  actual words: 35    (m+n-1)!/(n!(m-1)!) words: 35

 Although it works, it's somewhat slow as we have to iterate
 over the entire Cartesian Product and the filter list(x)==sorted(x)
 has got to be expensive (it's slower than the nested loop algorithm).

 Is there a better way to get Combinations With Replacement
 using itertools?

There may a technique to start with the combinations without
replacement and then grow the result by repeating elements:

   result = set(combinations('abcde', 3))
   # transform 'ab ac ad ae bc bd be cd ce de' into 'aab abb aac
acc ...'
   for c in combinations('abcde', 2):
   # transform 'ab' -- 'aab abb'
   for i in range(2):
   result.add(c[:i] + c[i]*1 + c[i:])
   for c in combinations('abcde', 1):
   for i in range(1):
   # 'a' -- 'aaa'
   result.add(c[:i] + c[i]*2 + c[i:])

If you generalize the above, it may solve the problem using itertools
as a starting point.

Alternatively, it's not too hard to transform the pure python version
given in the docs to one that supports combinations with replacement:

def combinations_with_replacement(iterable, r):
pool = tuple(iterable)
n = len(pool)
indices = [0] * r
yield tuple(pool[i] for i in indices)
while 1:
for i in reversed(range(r)):
if indices[i] != n - 1:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1]
yield tuple(pool[i] for i in indices)


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


Re: Unicode confusion

2008-07-15 Thread Mark Tolonen


Jerry Hill [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
On Mon, Jul 14, 2008 at 12:40 PM, Tim Cook [EMAIL PROTECTED] 
wrote:

if I say units=unicode(°).  I get
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0:
ordinal not in range(128)

If I try x=unicode.decode(x,'utf-8'). I get
TypeError: descriptor 'decode' requires a 'unicode' object but received
a 'str'

What is the correct way to interpret these symbols that come to me as a
string?


Part of it depends on where you're getting them from.  If they are in
your source code, just define them like this:


units = u°
print units

°

print repr(units)

u'\xb0'

If they're coming from an external source, you have to know the
encoding they're being sent in.  Then you can decode them into
unicode, like this:


units = °
unicode_units = units.decode('Latin-1')
print repr(unicode_units)

u'\xb0'

print unicode_units

°

--
Jerry



Even with source code you have to know the encoding.  for pre-3.x, Python 
defaults to ascii encoding for source files:


test.py contains:
units = u°


import test

Traceback (most recent call last):
 File stdin, line 1, in module
 File test.py, line 1
SyntaxError: Non-ASCII character '\xb0' in file test.py on line 1, but no 
encoding declared; see http://www.python.org/peps/pep-0263.html for details


The encoding of the source file can be declared:

# coding: latin-1
units = u°


import test
test.units

u'\xb0'

print test.units

°

Make sure to use the correct encoding!  Here the file was saved in latin-1, 
but declared utf8:


# coding: utf8
units = u°


import test

Traceback (most recent call last):
 File stdin, line 1, in module
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 0: 
unexpected code byte




--
Mark 


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

Re: python mysteriously halts

2008-07-15 Thread Gabriel Genellina
En Mon, 07 Jul 2008 12:26:28 -0300, Todd [EMAIL PROTECTED]  
escribió:



On Jul 7, 10:17 am, Tim Golden [EMAIL PROTECTED] wrote:

Todd wrote:
 I ran a python script last night which connects to a matlab automation
 server via DCOM (using win32com).  I expected to see the results when
 I came in this morning.  But apparently, not long after I left, python
 stopped.  I hit enter in the console, and it started again.

Symptomatically, at least, this can be caused by someone starting to
select (with the mouse) an area of the screen: the process will pause
until Enter is pressed, which copies the area to the clipboard. This
only happens with a console window, but it sounds like that's what
you had running.


That might be it, although I don't recall doing that.  Fortunately/
unfortunately, it happened a few times, but it seems to have stopped
now.


You could disable that behaviour by unchecking Quick edit mode (or  
something like that) in the Default preferences for the console window.  
(It's unchecked by default on WinXP and Win2003, I think).


--
Gabriel Genellina

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


Re: trying to use sax for a very basic first xml parser

2008-07-15 Thread manu


 May I suggest you ask in the blender list?


Will do that and report back. Thank you!

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


Re: Why is there no GUI-tools like this for Windows?

2008-07-15 Thread Michael Torrie
Marcus.CM wrote:

 So python for me is for anything except GUI. It becomes self rejecting 
 notion to do GUI in python when you type in those stuff that could have 
 been handled by an IDE,
 thus for linux project i just do the web interface + php and let python 
 do all the other hard core work.

This is probably exactly backwards of how I think of it.  Python is
ideally suited for creating and driving GUIs, things that dispatch work
to libraries and routines that do the real work.  This is known as the
separation of the user interface from the backend business logic.  While
I feel python is equally good at backend processing as it as front-end
stuff, many folks feel that Python may be too slow for certain kinds of
data processing.  Therefore by that logic, python only makes sense on
the front end.

To the original poster, get yourself this package:

http://gladewin32.sourceforge.net/

Then google around for getting PyGTK working on Win32 and you're in
business.  Don't use glade's code-generation tools; they are obsolete.
Instead use the glade xml file and the libglade or GTK Builder python
bindings for GTK to load and create the GUIs on the fly.

Personally I think that designing good-looking guis in Python using
wxWidgets, PyGTK or PyQT in plain code is very fast and very easy.  In
fact I think that GUI builders are somewhat overrated as they cannot
possibly cope with a GUI that will display data dynamically, or use
custom widgets.

That said, check out PyQT (definitely available on windows) and Qt's
Designer.  It pretty much blows glade and anything else I've seen out of
the water.
--
http://mail.python.org/mailman/listinfo/python-list


Re: screencapture with PIL question

2008-07-15 Thread Gabriel Genellina

En Mon, 14 Jul 2008 12:11:55 -0300, greg [EMAIL PROTECTED] escribi�:


I am able to use the PIL module to capture a screen or specific
window.  My problem is when capturing a window (on windows XP) I can
only capture the visible portion of the window.  Is there any way to
capture the entire window?  specifically the scrolled portion of a
window that is not visible on the screen.


Camtasia Studio -a commercial product- has a few ways to do that; one is  
to send many simulated mouse clicks to the window scroll bars, capturing  
the window contents in stripes.
pywinauto would help on doing that from Python  
http://pywinauto.blogspot.com/


--
Gabriel Genellina

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

Re: Python Tiddlywiki class

2008-07-15 Thread CracKPod
On 15 Jul., 03:04, David [EMAIL PROTECTED] wrote:
 CracKPod wrote:
  Hello, I wrote a Python class to interact with the TiddlyWiki. In case
  you are interested you can find it on my blog:

 http://crackpod.bplaced.net/

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

 Thank you :)

 --
 Powered by Gentoo GNU/LINUXhttp://www.linuxcrazy.com

You're welcome!
If I may beg you, redownload it from my Blog. I had to make a small
change that's why I released 1.0.1, elsewise you won't be able to
change the tiddler content and save it afterwards.
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterator clone

2008-07-15 Thread Kay Schluehr
On 15 Jul., 08:16, Yosifov Pavel [EMAIL PROTECTED] wrote:

 cloning of iterators in this manner is bad, more good is to use one,
 single list(my_iter) instead of 
 (seehttp://aquagnu.blogspot.com/2008/07/self-repair-iterator-in-python.html).

This won't work for big iterators as mentioned by Peter Otten. With
this recipe you can't even clone generator objects ( which are
iterators ) that produce Fibonaccis in a lazy manner.

Regards, Kay

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


Re: Using Python To Launch Python

2008-07-15 Thread Gabriel Genellina
En Mon, 14 Jul 2008 21:39:20 -0300, Derek Martin [EMAIL PROTECTED]  
escribió:

On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote:



You've hit the proverbial nail with the hammer.  The problem is that my
application needs to run under both the Linux and Windows OSs, so while  
I
would love to use a nice sh, csh, or bash shell script. My hands are  
tied

because Windows does not provide such wonderful shells.


*Provides*, no... neither does it provide Python, for what that's
worth.  But you can certainly get it (bash):

  http://win-bash.sourceforge.net/


Using the standard cmd.exe, the previously posted shell script becomes:

=== begin appname.cmd ===
set INSTALLPATH=wherever app is installed
call %INSTALLPATH%\bin\python %INSTALLPATH%\APPNAME.py %*
=== end appname.cmd ===

--
Gabriel Genellina

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


Testing for Internet Connection

2008-07-15 Thread Alexnb

Hello internet.

I am wondering, is there a simple way to test for Internet connection? If
not, what is the hard way :p
-- 
View this message in context: 
http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18460572.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Testing for Internet Connection

2008-07-15 Thread Alex Marandon

Alexnb wrote:

I am wondering, is there a simple way to test for Internet connection? If
not, what is the hard way :p


Trying to fetch the homepage from a few major websites (Yahoo, Google, 
etc.)? If all of them are failing, it's very likely that the connection 
is down. You can use urllib2 [1] to accomplish that.


[1] http://docs.python.org/lib/module-urllib2.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: FOSS projects exhibiting clean/good OOP?

2008-07-15 Thread paul

Phillip B Oldham schrieb:

Thanks all - lots to go through there! :D

I'd heard previously that Trac was a nice example, or rather its core
was, but I'd also heard that there were lots of problems with it and
that they were redeveloping it from scratch?
They continually improve parts of it, but I don't know of any severe 
problems whatsoever. Yes people are moaning about lack of multi-project 
support but that was a design decision way back.


From a programming POV, I highly recommend looking at the source. The 
component model looks simple but is very powerful. It's also a good 
example how code benefits from interfaces wrt. structuring and 
documentation.


cheers
 Paul

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


Python embedding question.

2008-07-15 Thread Thomas Troeger

Hi,

Sorry I've posted a similar question some weeks ago, but I got no 
answers. I want to embed a Python application on a device with limited 
resources, esp. storage limitations. Is there a way to reduce the Python 
interpreter to a set of modules that's urgently needed? Or is there a 
method to have gzipped modules that are unzipped on the fly into memory 
when they're accessed? That would be even better.


Additionally, is there a Python module that contains all the stuff 
needed for an embedded application like graphics, sound etc. or do I 
have to use the various bindings to libraries like cairo, Qt or similar? 
Is there a site that helps with those decisions?


I've really looked at a lot of places but haven't found a suitable 
solutions yet, so I'm asking here in hope that someone has experience 
with that topic.


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


Re: Python embedding question.

2008-07-15 Thread Kay Schluehr
On 15 Jul., 11:51, Thomas Troeger [EMAIL PROTECTED]
wrote:

 I've really looked at a lot of places but haven't found a suitable
 solutions yet, so I'm asking here in hope that someone has experience
 with that topic.

Which solutions did you rule out?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python embedding question.

2008-07-15 Thread Uwe Schmitt
On 15 Jul., 12:14, Thomas Troeger [EMAIL PROTECTED]
wrote:
 Kay Schluehr wrote:
  On 15 Jul., 11:51, Thomas Troeger [EMAIL PROTECTED]
  wrote:

  I've really looked at a lot of places but haven't found a suitable
  solutions yet, so I'm asking here in hope that someone has experience
  with that topic.

  Which solutions did you rule out?

 - Python + Qt, because it's definitely overkill for my plans. I only
 need simple graphics and some sound, no widgets. Basically I'm looking
 for something really lightweight that has methods for drawing graphic
 primitives and renders fonts -- no complicated widgets, windows,
 scrollbars and the like. And, for example, the Qt library is a real
 heavyweight with approx. 10 MB for qt-3.3.8 alone.

 - The same holds for cairo/pango, I've written a test program (in C, I
 must say) that has dynamic links to 10 libraries that are all like 250kb
 in size. That's a lot for a small embedded device.

Did you try pygame ? I think it has a small footprint.

Greetings, Uwe

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


Re: Testing for Internet Connection

2008-07-15 Thread Ben Finney
Alexnb [EMAIL PROTECTED] writes:

 I am wondering, is there a simple way to test for Internet
 connection? If not, what is the hard way :p

Refine the question: What do you mean by internet? It isn't a single
entity.

Do you mean some particular internet host responding on a particular
network port?

If you can define exactly what you mean by internet connection, the
test for it becomes correspondingly easier.

-- 
 \  “Why should I care about posterity? What's posterity ever done |
  `\for me?” —Groucho Marx |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: screencapture with PIL question

2008-07-15 Thread Fredrik Lundh

greg wrote:


I am able to use the PIL module to capture a screen or specific
window.  My problem is when capturing a window (on windows XP) I can
only capture the visible portion of the window.  Is there any way to
capture the entire window?  specifically the scrolled portion of a
window that is not visible on the screen.


If we're talking arbitrary applications, that portion doesn't 
necessarily exist other than as a collection of data structures deep 
inside the application.


To fix this, your captura program needs to take repeated screenshots, 
adjust the view between every shot, and then stitch them together.  See 
Gabriel's post for a link to a nice automation tool for Windows.


There are also various browser screenshot tools around that might work 
in your case (I think I've seen Python code for that somewhere, but 
cannot find it right now).  Google can probably help.


/F

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


Re: Testing for Internet Connection

2008-07-15 Thread Thomas Troeger

Alex Marandon wrote:

Alexnb wrote:

I am wondering, is there a simple way to test for Internet connection? If
not, what is the hard way :p


Trying to fetch the homepage from a few major websites (Yahoo, Google, 
etc.)? If all of them are failing, it's very likely that the connection 
is down. You can use urllib2 [1] to accomplish that.


[1] http://docs.python.org/lib/module-urllib2.html


This seems to work and is rather fast and wastes no bandwidth:

==
#!/usr/bin/python

import socket, struct

def check_host(host, port, timeout=1):

Check for connectivity to a certain host.

# assume we have no route.
ret=False

# connect to host.
try:
# create socket.
sock=socket.socket()
# create timeval structure.
timeval=struct.pack(2I, timeout, 0)
# set socket timeout options.
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, timeval)
# connect to host.
sock.connect((host, port))
# abort communications.
sock.shutdown(SHUT_RDWR)
# we have connectivity after all.
ret=True
except:
pass

# try to close socket in any case.
try:
sock.close()
except:
pass

return ret

#  main -

if check_host(www.heise.de, 80):
print Horray!
else:
print We've lost headquarters!
==

I hope the code is ok, but there is always something you can do better. 
Comments? :)


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


Re: SAX XML Parse Python error message

2008-07-15 Thread Fredrik Lundh

goldtech wrote:


I would be grateful for support with the code I cited. It's not long
and fairly standard. I'm sure my error(s) would be glaring to more
experienced coders. I appreciated the heads-up about other options
but I would be grateful for help getting this code to run. Thanks


For comparison, here's how an experienced Python programmer might prefer 
to write your code:


import xml.etree.cElementTree as ET

description = None # most recently seen description

for event, elem in ET.parse(somefile.xml):
if elem.tag == description:
description = elem.text
elif elem.tag == coordinates:
print description.strip(), elem.text.strip()

You may want to ask yourself why you prefer to struggle with obsolete, 
error-prone, and slow technology when there are more efficient tools 
available in Python's standard library.


(the lxml library that Stefan linked to is a superset of xml.etree, in 
case you want more XML features).


/F

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


Re: why is self used in OO-Python?

2008-07-15 Thread Fredrik Lundh

ssecorp wrote:


def append(self, item):
self.stack.append(item)

I can get to see the stack with var.stack but then why even implement
append when I could do self.stack.append(x) etc.
That way you could do away with OO completely.


Umm.  Even if you were to write that, self and stack would still be 
objects, and the append would still be a method defined by the stack 
object, right?


What you seem to be referring to is the Law of Demeter, which is a 
design guideline for avoiding unnecessary coupling, not an absolute 
requirement for object-orientation:


http://en.wikipedia.org/wiki/Law_of_Demeter

As for the rest, I suspect you will have more success in using Python if 
you use it to write Python programs, not Java programs:


http://dirtsimple.org/2004/12/python-is-not-java.html

/F

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


Re: Testing for Internet Connection

2008-07-15 Thread Marc Christiansen
Alex Marandon [EMAIL PROTECTED] wrote:
 Alexnb wrote:
 I am wondering, is there a simple way to test for Internet connection? If
 not, what is the hard way :p
 
 Trying to fetch the homepage from a few major websites (Yahoo, Google, 
 etc.)? If all of them are failing, it's very likely that the connection 
 is down

or there is a mandatory proxy...

Does it count as internet connection, when only port 80 and port 443 are
accessible and those require going through a proxy (very strict firewall
policy)? Or everything requires using SOCKS?
Just some possible problems I came up with. I don't know how often some-
thing like this will happen.

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


Logging in __del__()

2008-07-15 Thread Robert Rawlins
Guys,

 

I'm trying to help trace when instances of particular classes are being
destroyed by the garbage collector and thought the cleanest way would be to
implement a logging call in __del__() on the class. However, I'm having an
issue.

 

I inject a logger instance into my class upon construction and set it to
self.logger, I then use this within the class to log actions going on
within, works fine.

 

Now, when I make the call in the __del__() method like so:

 

def __del__(self):

# Log the classes destruction.

self.logger.debug(Class Instance Destroyed)

 

I then get the following exception thrown when running my code:

 

Traceback (most recent call last):

  File /usr/lib/python2.5/logging/handlers.py, line 73, in emit

if self.shouldRollover(record):

  File /usr/lib/python2.5/logging/handlers.py, line 147, in shouldRollover

self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature

ValueError: I/O operation on closed file

 

Does anyone have any ideas as to what I'm doing wrong here? Is this a known
issue which has a neat little work around?

 

Cheers,

 

Robert

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

How can I save command prompt screen

2008-07-15 Thread Ty hensons
how can i save my command prompt screen?


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

Re: Logging in __del__()

2008-07-15 Thread Fredrik Lundh

Robert Rawlins wrote:


I then get the following exception thrown when running my code:


When the application is running, or when it is shutting down?


Traceback (most recent call last):
  File /usr/lib/python2.5/logging/handlers.py, line 73, in emit
if self.shouldRollover(record):
  File /usr/lib/python2.5/logging/handlers.py, line 147, in shouldRollover
self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
ValueError: I/O operation on closed file

Does anyone have any ideas as to what I’m doing wrong here? Is this a 
known issue which has a neat little work around?


Python makes no guarantees that it will tear down your objects before it 
tears down the library's objects (or the library itself).  See e.g.


http://www.python.org/doc/essays/cleanup/

(old and probably somewhat outdated, but you get the idea)

I'd just put a try/except around it, and ignore any exceptions that may 
occur.


/F

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


Re: Python embedding question.

2008-07-15 Thread David Lyon

Thomas Troeger wrote:
I want to embed a Python application on a device with limited 
resources, esp. storage limitations. Is there a way to reduce the 
Python interpreter to a set of modules that's urgently needed? 

Of course there is. What is the target platform ?

What can be done is to go through the python source code and comment out 
everything that *you* find unneccessary. I can't tell you what this 
would be - because I don't know exactly what you are after. But to your 
question - the answer is yes.. of course.
Or is there a method to have gzipped modules that are unzipped on the 
fly into memory when they're accessed? That would be even better.

Yes - also possible.


Additionally, is there a Python module that contains all the stuff 
needed for an embedded application like graphics, sound etc.

No. Because that depends on what hardware platform you want to run on.
or do I have to use the various bindings to libraries like cairo, Qt 
or similar? Is there a site that helps with those decisions?
I doubt it. These are decisions for you to make according to the 
limitations of your hardware.


I've really looked at a lot of places but haven't found a suitable 
solutions yet, so I'm asking here in hope that someone has experience 
with that topic.



:-)

Regards

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


Suggestion: Python global scope

2008-07-15 Thread Anonymous Bastard

I've been tossing this idea in my mind for some time now:

In Python, declaring a variable using the global statement automatically 
makes it available in all subsequent scopes.


But to me, it makes more sense to use the global statement to 'import' a 
variable from the global scope into the current scope. For instance:


[code]
global X
X = 1

def P():
X = 2
print X
global X
print X

print X
P()
print X
[code]

Currently, this will print 1, 2, 2 and 2. But if global would be limited 
to current scope, it would print 1, 2, 1, 1.


'X = 2' would work on the local version of X, 'global X' will 'import' 
the global X into the local scope, so any actions on X would reference 
the global X, rather than previous X.

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


Re: Suggestion: Python global scope

2008-07-15 Thread Gerhard Häring

Anonymous Bastard wrote:

I've been tossing this idea in my mind for some time now:

In Python, declaring a variable using the global statement automatically 
makes it available in all subsequent scopes.


But to me, it makes more sense to use the global statement to 'import' a 
variable from the global scope into the current scope. For instance:


[code]
global X
X = 1

def P():
X = 2
print X
global X
print X

print X
P()
print X
[code]

Currently, this will print 1, 2, 2 and 2. But if global would be limited 
to current scope, it would print 1, 2, 1, 1.


'X = 2' would work on the local version of X, 'global X' will 'import' 
the global X into the local scope, so any actions on X would reference 
the global X, rather than previous X.


Anything backwards incompatible like this will never happen.

-- Gerhard

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


Logging to different addressees

2008-07-15 Thread McA
Hi all,

I need a recommendation. I would to like to use the logging module to
create log messages the following way:
a) Every log message does go to  a admin sink.
b) The logging of special messages should go to the admin sink AND to
a sink specifically for
a certain addressee.
c) I don't want to write the log message to two different loggers for
that purpose. I would like to do it this way:
common_logger.log('bla')   - message to admin sink
certain_logger.log('something' - message to admin sink and addressee-
sink
d) Filtering and debug level should work as expected.

I could I achieve this in a elegant way?

Best regards
Andreas Mock
--
http://mail.python.org/mailman/listinfo/python-list


Simplify Code

2008-07-15 Thread Victor Subervi
Hi;
Forgive multiple posts in one day: online very infrequently
I set the following variables:
# Headers are kept in order to determine nesting of chapters
# They are labeled according to font size
h36 = ''
h26 = ''
h22 = ''
h18 = ''
h14 = ''
h12 = ''
header_sizes = [36, 26, 22, 18, 14, 12]
# Size is the font size of the header
size = 0

I write code that grabs the size var.
Then I have the following very laborious spaghetti code:

if size == 36:
  h36 = line
  h26 = ''
  h22 = ''
  h18 = ''
  h14 = ''
  h12 = ''
elif size == 26:
  h26 = line
  h22 = ''
  h18 = ''
  h14 = ''
  h12 = ''
elif size == 22:
  h22 = line
  h18 = ''
  h14 = ''
  h12 = ''
elif size == 18:
  h18 = line
  h14 = ''
  h12 = ''
elif size == 14:
  h14 = line
  h12 = ''
elif size == 12:
  h12 = line
else:
  # THROW ERROR!

I would like something more elegant, like this:
# del is used to determine if should reset the lower header values to ''
del = 0
for header_size in header_sizes:
  if header_size == size:
# The following line is ILLEGAL
h + string(header_size) = line
del = 1
  if del = 1
# The following line is ILLEGAL
h + string(header_size) = ''

How can I rewrite those illegal lines, such that I can create the proper
name for the variable, and write the necessary data?
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Type Problem

2008-07-15 Thread Victor Subervi
Hi;
Forgive multiple posts in one day: online very infrequently
Why am I getting this error?
import os
dir_dict = {6:36, 5:26, 4:22, 3:18, 2:14, 1:12}
cur_dir = os.getcwd()
dirs = os.path.split(cur_dir)
len = len(dirs)
type(len(dirs))
Traceback (most recent call last):
  File pyshell#11, line 1, in module
type(len(dirs))
TypeError: 'int' object is not callable

Forgot to bring it with me, but type(len) gives me an intelligent response.
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Characters Being Misread

2008-07-15 Thread Victor Subervi
Hi;
Forgive multiple posts in one day: online very infrequently
I'm having the darndest time trying to figure out how the character '\b0' is
being read in ('\x0c')
 test = re.search('(?=\\b)[0]', '\x0c0')
 test.group(0)
'0'
 type('\x0c')
type 'str'
 import binascii
 binascii.unhexlify('\x0c')
Traceback (most recent call last):
  File pyshell#643, line 1, in module
binascii.unhexlify('\x0c')
TypeError: Odd-length string

What gives here?

Here's another one:
 rtf_markup = '\viewkind4\\uc1\\pard\nowidctlpar\\qc\\i\x0c0\x0cs36'
 a = []
 a.append(re.compile('\\i').match(rtf_markup, 1))
 a
[_sre.SRE_Match object at 0x011802F8]
 a = []
 a.append(re.compile('\\qc').match(rtf_markup, 1))
[None]

What's the problem?

TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list

Re: Using McMillan Installer, PyInstall or py2exe cross-platform?

2008-07-15 Thread David Lyon

Hi Hartmut,

I can sympathise with you on this one...

There are a few options...

there is a python based bake make like program... that is useful... 
http://projects.bertram-scharpf.de/bake/bake1.html


then there is Wine... that is a windows emulator under linux... that 
might be pretty easy http://www.winehq.org/


If you want to get more heavy-weight, then get a virtual machine.

But as per your question... the above specified options might satisfy 
your requests for speed and ease of use without having to change O/S.


Regards

David




Hartmut Goebel wrote:

Hi,

has anybody used McMillan Installer, PyInstall or py2exe cross-platform?

I have a Windows partition with Python installed there, so this would 
only required working on a different directory and for a different OS.
Since I'm working on Linux, it's awful to boot Windows each time I 
want to build a new release.


Any hint in this area?



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


Re: Suggestion: Python global scope

2008-07-15 Thread Nick Dumas
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

The function of the global keyword is to 'push' local variables to the
global scope. If you want to 'import' a variable into a local scope,
pass the variable to your function/method as an argument.

Anonymous Bastard wrote:
 I've been tossing this idea in my mind for some time now:
 
 In Python, declaring a variable using the global statement automatically
 makes it available in all subsequent scopes.
 
 But to me, it makes more sense to use the global statement to 'import' a
 variable from the global scope into the current scope. For instance:
 
 [code]
 global X
 X = 1
 
 def P():
 X = 2
 print X
 global X
 print X
 
 print X
 P()
 print X
 [code]
 
 Currently, this will print 1, 2, 2 and 2. But if global would be limited
 to current scope, it would print 1, 2, 1, 1.
 
 'X = 2' would work on the local version of X, 'global X' will 'import'
 the global X into the local scope, so any actions on X would reference
 the global X, rather than previous X.
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkh8ol4ACgkQLMI5fndAv9ieGwCgi51Vs45tgj3mbom0BeM/nBzL
XwsAnjRZr9An617xXyiWp9AVBv3FQ3+z
=EFee
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


AW: Python embedding question.

2008-07-15 Thread Troeger, Thomas (ext)
Hi,

  I want to embed a Python application on a device with limited 
  resources, esp. storage limitations. Is there a way to reduce the 
  Python interpreter to a set of modules that's urgently needed? 
 Of course there is. What is the target platform ?

Thanks for your answer. The plattform is x86, so basically it's a PC
with a compact flash drive. The problem is that the compact flash is
rather limited in speed and size (there is other stuff on it too).

  Or is there a method to have gzipped modules that are unzipped on
the 
  fly into memory when they're accessed? That would be even better.
 Yes - also possible.

That sounds promising, is there a link you can give? Or do I have to
modify the module loading code for this, i.e. the interpreter? I think
that wouldn't be too much of a problem if I understand where Python
loads modules; I haven't checked the Python source yet for that one, and
searching for Python and zip or similar always yields tons of links that
use the Python zip or tar module :)

 Regards
 David

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


Re: Suggestion: Python global scope

2008-07-15 Thread John Roth
On Jul 15, 5:57 am, Anonymous Bastard [EMAIL PROTECTED] wrote:
 I've been tossing this idea in my mind for some time now:

 In Python, declaring a variable using the global statement automatically
 makes it available in all subsequent scopes.

 But to me, it makes more sense to use the global statement to 'import' a
 variable from the global scope into the current scope. For instance:

 [code]
 global X
 X = 1

 def P():
      X = 2
      print X
      global X
      print X

 print X
 P()
 print X
 [code]

 Currently, this will print 1, 2, 2 and 2. But if global would be limited
 to current scope, it would print 1, 2, 1, 1.

 'X = 2' would work on the local version of X, 'global X' will 'import'
 the global X into the local scope, so any actions on X would reference
 the global X, rather than previous X.

I suppose it could be done, but I for one would be against it on
several grounds.

First, global operates somewhat as a declaration currently.
Declarations are easier for most developers to understand than
redefinitions of a variable on the fly.

Second, following up the first point, it redefines a variable. While
this is common practice, it's unfortunate since it leads to some
amount of confusion. It also seems like it would be most useful in
large, poorly structured methods, which is exactly the wrong way to
go.

Finally, as Gerhard Haring has said, it's backward incompatible, so
the window for considering it has past: the 3.x series is pretty much
frozen.

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


[ANN} Daily pyogp coders meeting (PYthon Open Grid Protocols for virtual worlds)

2008-07-15 Thread Lawson English
pyogp is a Python-based virtual worlds test harness and client library 
being developed by Linden Lab, makers of Second Life, and members of the 
SL Architecture Working Group, in order to test the Open Grid Protocols 
that were used in the recent proof of concept demo by IBM and Linden 
Lab, that allowed avatars to teleport from one virtual world (Second 
Life) to another (Open Simulator) using standardized interoperability 
protocols.



http://www.informationweek.com/news/personal_tech/virtualworlds/showArticle.jhtml?articleID=208803274

A daily meeting within Second Life has been setup for pyogp coders and 
designers to meet, as described in the announcement below. This is the 
transcript of the first meeting:


http://wiki.secondlife.com/wiki/Pyogp/Chat_Logs/Daily_Meeting/14_jul_2008

The pyogp meetings are open to any resident of Second Life, and any 
Python person (or design expert) with a desire to contribute to the 
process is certainly welcome.




In World Meetings
We're going to start having daily meetings at infinity is full of 
stars in the Levenhall simulator in Second Life at 9:30AM SLT (Pacific 
Coast Time) each day. These meetings are for the PyOGP coders to meet 
and discuss design, process and status. In the near term, these are 
likely to be somewhat beefy meetings where design issues are discussed 
and differences hammered out. In the longer term, these will hopefully 
be more Agile Stand-Up style meetings where we discuss: a. what we've 
done in the last 24 hours, b. what we're going to do in the next 24 and 
c. what we're blocked on.




what PyOGP Coders Meeting
who PyOGP l33t C0d3rZ
whereinfinity is full of stars @ 
http://slurl.com/secondlife/Levenhall/91/208/22
when 9:30AM SLT / 12:30PM Eastern Time / 5:30PM GMT / 6:30PM Central 
European Time
why for PyOGP contributors to hash out architecture, design, test 
and deploy issues




IRC: irc://irc.freenode.com/#pyogp
Mailing list:  https://lists.secondlife.com/cgi-bin/mailman/listinfo/pyogp
wiki: http://wiki.secondlife.com/wiki/Pyogp

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


Re: Python embedding question.

2008-07-15 Thread Jerry Hill
On Tue, Jul 15, 2008 at 5:51 AM, Thomas Troeger
[EMAIL PROTECTED] wrote:
 Or is there a method to have gzipped
 modules that are unzipped on the fly into memory when they're accessed? That
 would be even better.

Yes.  See the documentation for the zipimport module, and PEP 273.

http://docs.python.org/lib/module-zipimport.html
http://www.python.org/dev/peps/pep-0273/

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


Re: AW: Python embedding question.

2008-07-15 Thread David Lyon

Troeger, Thomas (ext) wrote:

Thanks for your answer. The plattform is x86, so basically it's a PC
with a compact flash drive. The problem is that the compact flash is
rather limited in speed and size (there is other stuff on it too).
  
Oh ok. Well just keep in mind that 4GB of flash memory can be bought in 
China for about 5 euros.


Since programming time is pretty expensive you need to do your sums 
about where you want to spend the time/money.

Or is there a method to have gzipped modules that are unzipped on
  
the 
  

fly into memory when they're accessed? That would be even better.
  

Yes - also possible.



That sounds promising, is there a link you can give? Or do I have to
modify the module loading code for this, i.e. the interpreter? 

http://squashfs.sourceforge.net/

I think
that wouldn't be too much of a problem if I understand where Python
loads modules; I haven't checked the Python source yet for that one, and
searching for Python and zip or similar always yields tons of links that
use the Python zip or tar module :)
  
Python modules are byte compiled. You can usually cut out a lot/some of 
space by removing the source (.py) and leaving the compile (.pyc) modules.


There is usually a lib or a sitelib directory. You could try cleaning 
that out of unwanted modules.


My advice would be to simply buy higher capacity flash memory

Regards

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

Re: Why is there no GUI-tools like this for Windows?

2008-07-15 Thread Cromulent

On 2008-07-12 22:35:58 +0100, maestro [EMAIL PROTECTED] said:


http://www.youtube.com/watch?v=PXpwC1o5AcI

I have done some GUI-programming for windows with Python but the
Tkinter interface sucked and while it is the only one I tried I got
the impression they are all the same.

It's amazing how retarded a lot of the stuff programmers do is.
Watcing that video, that is how it should be.

I can just do the layout with my mouse and then there is a program
that writes the code for me.
GUI-programming is hard for no reason. One good program then forever
easy...

Is there not something like this for Python/Windows? Is the Linux one
only for ruby or for any language?

Oh well im switching to Linux anyway and mostly write webapps but
still...


PyQt4 is available for Windows and lets you use the Qt Designer 
application which is pretty good. Works well, you should take a look.

--
I disapprove of what you say, but I'll defend to the death your right 
to say it. - Voltaire


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


Re: Python embedding question.

2008-07-15 Thread Stephen Johnson
The Pyglet library has all the functionality of pygame, but is smaller  
and much more self-contained. Pygame requires SDL, pyglet only OpenGL.


On Jul 15, 2008, at 6:26 AM, Uwe Schmitt wrote:


On 15 Jul., 12:14, Thomas Troeger [EMAIL PROTECTED]
wrote:

Kay Schluehr wrote:

On 15 Jul., 11:51, Thomas Troeger [EMAIL PROTECTED]
wrote:



I've really looked at a lot of places but haven't found a suitable
solutions yet, so I'm asking here in hope that someone has  
experience

with that topic.



Which solutions did you rule out?


- Python + Qt, because it's definitely overkill for my plans. I only
need simple graphics and some sound, no widgets. Basically I'm  
looking

for something really lightweight that has methods for drawing graphic
primitives and renders fonts -- no complicated widgets, windows,
scrollbars and the like. And, for example, the Qt library is a real
heavyweight with approx. 10 MB for qt-3.3.8 alone.

- The same holds for cairo/pango, I've written a test program (in  
C, I
must say) that has dynamic links to 10 libraries that are all like  
250kb

in size. That's a lot for a small embedded device.


Did you try pygame ? I think it has a small footprint.

Greetings, Uwe

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


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

Re: logging via SocketHandler and TCPserver

2008-07-15 Thread Vinay Sajip
On Jul 14, 11:16 pm, Larry Bates [EMAIL PROTECTED] wrote:
 Vinay,

 Thanks for your detailed explanation, but IMHO your suggested solution is 
 almost
 the opposite (right idea wrong direction) of what I'm looking for.  
 Hypothetical
 setup:

 application1 - SocketHandlerloggingturned on
 application2 - SocketHandlerloggingturned on
 application3 - SocketHandlerloggingturned on
 .
 .
 .
 applicationN

 monitoring app - ThreadingTCPServer target that Allows user to connect to ANY
 running application and to view the real-time log messages.  After monitoring,
 it should be able to disconnect and connect to another application...  The
 clients (application1..N) never stop sending and don't ever send anything 
 short
 to disconnect themselves from the monitoring application.  The disconnect/
 reconnect is done at the monitoring app end based on input from the user.  I
 think each one would beloggingto a different port, but I never really quite
 got that far.  Perhaps there is some other way that I'm missing.  It seems 
 like
 this is something that might be able to be generalized into a robust
 monitoring application for an arbitrary number of asynchronously running
 applications.

 Each application's real-time log might be reached by clicking on a tab, menu, 
 etc.

Here's how I see it: the socket server listens, and receives logging
events from numerous applications in real time. If the server is
configured to monitor app1, then it quietly discards (or doesn't show
in the UI) all events from other apps - it only collects/shows events
from app1. When you click on a tab/menu/whatever to switch to
monitoring app2, then this information is used to tell the server to
discard (or not show) events from all apps except app2. You would of
course need to ensure the communication between UI thread and server
thread were done in a thread-safe manner.

 As to the difficulty, I might just have a mental block but two modules that 
 I've
 had a real hard time getting my mind wrapped around is yourLoggingand Twisted.
 They both have a multitude of options/ways to be used and not very many 
 working
 examples to work from.  Might be a chance to make some money on a book.  If it
 was full of examples, I'd purchase it.


But there are numerous examples in the logging docs - the script you
quoted as having put together after several hours of Googling is
pretty much the same as the (working) version in the logging docs! If
you have reviewed the logging docs and find them lacking examples,
please provide more detail about the kind of examples you think are
missing. And I can't speak for Twisted, but it does a lot more than
logging - and I don't think there's enough complexity in Python
logging to warrant a paid-for book. (No doubt people will tell me if
they disagree!)

Best regards,

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


Python internals

2008-07-15 Thread Peter Anderson
Hi!  I am slowly teaching myself Python.  I was reading David Beazley's 
excellent book Python - Essential Reference; in particular about 
variables.  Let me quote:


Python is a dynamically typed language in which names can represent 
values of different types during the execution of a program. In fact the 
names used in the program are really just labels for various quantities 
and objects. The assignment operator simply creates an association 
between a name and a value. This is different from C, for example, in 
which a name (variable) represents a fixed size and location in memory...


As an old mainframe programmer, I understand the way C does things with 
variable but this text got me wondering how Python handles this 
association between variable name and value at the lower level.  Is it 
like a fifo list?


If there is any Python guru that can help I would be most interested in 
your thoughts.


Regards,
Peter
--
Peter Anderson

There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things -- Niccolo Machiavelli, The 
Prince, ch. 6

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


Re: Logging to different addressees

2008-07-15 Thread Vinay Sajip
On Jul 15, 1:27 pm, McA [EMAIL PROTECTED] wrote:
 Hi all,

 I need a recommendation. I would to like to use theloggingmodule to
 create log messages the following way:
 a) Every log message does go to  a admin sink.
 b) Theloggingof special messages should go to the admin sink AND to
 a sink specifically for
 a certain addressee.
 c) I don't want to write the log message to two different loggers for
 that purpose. I would like to do it this way:
 common_logger.log('bla')   - message to admin sink
 certain_logger.log('something' - message to admin sink and addressee-
 sink
 d) Filtering and debug level should work as expected.

 I could I achieve this in a elegant way?

 Best regards
 Andreas Mock

Add a handler to the root logger (or common_logger) to send to the
admin sink.
Add a handler to certain_logger to send to the addressee sink.
If you added the admin sink handler to the root logger, you're done.
Otherwise, you need to ensure that certain_logger is a child of
common_logger.

Regards,

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


Re: Method behavior for user-created class instances

2008-07-15 Thread [EMAIL PROTECTED]
On 15 juil, 01:24, [EMAIL PROTECTED] wrote:
 Greetings.

 I am looking for a way to achieve method behavior for a class I
 created. That is, it has a __call__ method,  so can be called like a
 function. But I also want it to be treated as a method when it appears
 in a class body.

You need to implement the descriptor protocol the same way the
function type do.

import types

class Foo(object):
def __call__(self, instance):
print %s - %s % (self, instance)

def __get__(self, instance, cls):
return types.MethodType(self, instance, cls)

class Bar(object):
foo = Foo()

b = Bar()
b.foo()


 I know this has to do with writing the __get__
 method of foo, but I am wondering if there is perhaps some class I can
 just inherit from to get the proper __get__, which behaves identically
 to that of regular Python functions.

Extending types.FunctionType doesn't work OOTB (there's some
incompatibility wrt/ metaclasses)


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


Python internals question

2008-07-15 Thread Peter Anderson
Hi! I am slowly teaching myself Python. I was reading David Beazley's 
excellent book Python - Essential Reference; in particular about 
variables. Let me quote:


Python is a dynamically typed language in which names can represent 
values of different types during the execution of a program. In fact the 
names used in the program are really just labels for various quantities 
and objects. The assignment operator simply creates an association 
between a name and a value. This is different from C, for example, in 
which a name (variable) represents a fixed size and location in memory...


As an old mainframe programmer, I understand the way C does things with 
variable but this text got me wondering how Python handles this 
association between variable name and value at the lower level. Is it 
like a fifo list?


If there is any Python guru that can help I would be most interested in 
your thoughts.


Regards,
Peter
--

Peter Anderson

There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things — Niccolo Machiavelli, /The 
Prince/, ch. 6


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


Re: Logging in __del__()

2008-07-15 Thread Vinay Sajip
On Jul 15, 1:51 pm, Robert Rawlins
[EMAIL PROTECTED] wrote:

 Am I right in thinking that Python destroys instances of classes when it
 deems they are no longer needed? I shouldn't have to explicitly delete the
 classes, right?

Python uses reference counting with a cycle detector, but the
detector's behaviour is different if there are finalizers  (__del__) -
see

http://www.python.org/doc/ext/refcounts.html

Regards,

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


Modify a string's value

2008-07-15 Thread s0suk3
Hi everyone,

I've heard that a 'str' object is immutable. But is there *any* way to
modify a string's internal value?

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


Re: Simplify Code

2008-07-15 Thread Michiel Overtoom
Victor wrote...

# del is used to determine if should reset the lower header values to ''
del = 0

Apart from many other things that spring to mind, I already see an obvious
flaw: 'del' is a keyword, or a 'reserved word' in Python. It is used to
remove variables from the namespace. Tip: Use some other name as a variable,
eg. 'deletethisone'.

Greetings,


-- 
The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing. - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: How to package a logging.config file?

2008-07-15 Thread Matthew Wilson
On Mon 14 Jul 2008 09:25:19 AM EDT, Vinay Sajip wrote:
 Is your package a library or an application? If it's a library, you
 should avoid configuring logging using a config file - this is because
 logging configuration is process-wide, and if multiple libraries use
 fileConfig to configure their logging, you may get unexpected results.

I thought that the point of using logging.getLogger('foo.bar.baz') was
to allow each module/class/function to choose from the available
configurations.

So, I can define a really weird logger and still be a good citizen.

As long as I don't tweak the root logger, is it safe to use a config
file?

Matt

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


Re: Type Problem

2008-07-15 Thread Michiel Overtoom
Victor wrote...

len = len(dirs)

The function 'len' is a built-in function in Python. If you assign an
integer to the name 'len', that will replace the function with an int. And
you can't call an int.

My suggestion: Do not use 'len' as a variable name. Use something else, like:

directorycount=len(dirs)

Greetings,

 type(len)
type 'builtin_function_or_method'

 print len(Victor)
6

 len=42

 type(len)
type 'int'

 len(Victor)
Traceback (most recent call last):
  File pyshell#4, line 1, in module
len(Victor)
TypeError: 'int' object is not callable

-- 
The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing. - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: Modify a string's value

2008-07-15 Thread Ben Finney
[EMAIL PROTECTED] writes:

 I've heard that a 'str' object is immutable. But is there *any* way to
 modify a string's internal value?

If there were, it would not be immutable. The 'str' type has only
immutable values.

You could implement your own string type, and have it allow mutable
values. You'd have to take care of creating those values explicitly,
though.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\  Brain, but shouldn't the bat boy be wearing a cape?” —_Pinky |
_o__)   and The Brain_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Characters Being Misread

2008-07-15 Thread Michiel Overtoom
Victor wrote...

 import binascii
 binascii.unhexlify('\x0c')
TypeError: Odd-length string
What gives here?

The function unhexlify() wants an even-length string. From the online help:

 help(binascii.unhexlify)
unhexlify(...)
a2b_hex(hexstr) - s; Binary data of hexadecimal representation.
hexstr must contain an even number of hex digits (upper or lower case).
This function is also available as unhexlify()

And you use it like this:

 binascii.unhexlify(41)
'A'


You feed it data without any '0x' prefixes.

What are you trying to do? Parsing an RTF file which contains unicode
characerts, encoded as hexadecimal?

Greetings,


-- 
The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing. - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: Anyone happen to have optimization hints for this loop?

2008-07-15 Thread dp_pearce
Thank you so much for all your advice. I have learnt a lot.

In the end, the solution was perhaps self evident. Why try and build a
huge string AND THEN write it to file when you can just write it to
file? Writing this much data directly to file completed in ~1.5
seconds instead of the 3-4 seconds that any of the .join methods
produced.

Interestingly, I found that my tests agreed with Bruno. There wasn't a
huge change in speed between a lot of the other methods, other than
them looking a lot tidier.

Again, many thanks.

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


Re: Modify a string's value

2008-07-15 Thread bearophileHUGS
Sebastian:
 I've heard that a 'str' object is immutable. But is there *any* way to
 modify a string's internal value?

No, but you can use other kind of things:

 s = hello
 sl = list(s)
 sl[1] = a
 sl
['h', 'a', 'l', 'l', 'o']
 .join(sl)
'hallo'
 from array import array
 sa = array(c, s)
 sa
array('c', 'hello')
 sa[1] = a
 sa
array('c', 'hallo')
 sa.tostring()
'hallo'

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


fork after creating temporary file using NamedTemporaryFile

2008-07-15 Thread rparimi
Hello pythoners,

When I create temporary file using the tempfile module, and forkI)
later on in my program, I always see errors when the program exits. Is
this because the child process deletes temp file?
Here's a stripped down version of my script that exhibits this
problem:

#!/usr/bin/python

import os
import tempfile
import sys

cmd = []
cmd.append('/bin/ls')
cmd.append('-l')
cmd.append('/tmp')

foo = tempfile.NamedTemporaryFile(mode='w+b')

pid = os.fork()
if pid:
print 'I am parent'
else:
print 'I am child'
sys.exit(0)

$ python sub.py
I am child
I am parent
Exception exceptions.OSError: (2, 'No such file or directory', '/tmp/
tmp-mZTPq') in bound method _TemporaryFileWrapper.__del__ of closed
file 'fdopen', mode 'w+b' at 0xb7d2a578 ignored


How can these warnings be avoided? I tried to catch this exception
using try/except but it didn't work.

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


Re: logging via SocketHandler and TCPserver

2008-07-15 Thread Larry Bates

Vinay Sajip wrote:

On Jul 14, 11:16 pm, Larry Bates [EMAIL PROTECTED] wrote:

Vinay,

Thanks for your detailed explanation, but IMHO your suggested solution is almost
the opposite (right idea wrong direction) of what I'm looking for.  Hypothetical
setup:

application1 - SocketHandlerloggingturned on
application2 - SocketHandlerloggingturned on
application3 - SocketHandlerloggingturned on
.
.
.
applicationN

monitoring app - ThreadingTCPServer target that Allows user to connect to ANY
running application and to view the real-time log messages.  After monitoring,
it should be able to disconnect and connect to another application...  The
clients (application1..N) never stop sending and don't ever send anything short
to disconnect themselves from the monitoring application.  The disconnect/
reconnect is done at the monitoring app end based on input from the user.  I
think each one would beloggingto a different port, but I never really quite
got that far.  Perhaps there is some other way that I'm missing.  It seems like
this is something that might be able to be generalized into a robust
monitoring application for an arbitrary number of asynchronously running
applications.

Each application's real-time log might be reached by clicking on a tab, menu, 
etc.


Here's how I see it: the socket server listens, and receives logging
events from numerous applications in real time. If the server is
configured to monitor app1, then it quietly discards (or doesn't show
in the UI) all events from other apps - it only collects/shows events
from app1. When you click on a tab/menu/whatever to switch to
monitoring app2, then this information is used to tell the server to
discard (or not show) events from all apps except app2. You would of
course need to ensure the communication between UI thread and server
thread were done in a thread-safe manner.


As to the difficulty, I might just have a mental block but two modules that I've
had a real hard time getting my mind wrapped around is yourLoggingand Twisted.
They both have a multitude of options/ways to be used and not very many working
examples to work from.  Might be a chance to make some money on a book.  If it
was full of examples, I'd purchase it.



But there are numerous examples in the logging docs - the script you
quoted as having put together after several hours of Googling is
pretty much the same as the (working) version in the logging docs! If
you have reviewed the logging docs and find them lacking examples,
please provide more detail about the kind of examples you think are
missing. And I can't speak for Twisted, but it does a lot more than
logging - and I don't think there's enough complexity in Python
logging to warrant a paid-for book. (No doubt people will tell me if
they disagree!)

Best regards,

Vinay Sajip


Can multiple applications send SocketHandler logging records to the same socket 
server on the same port simultaneously?  If so, then I understand your answer 
completely and will go in that direction.  I guess I was trying to not use up 
bandwidth/CPU cycles on the applications that weren't being actively monitored 
by just not having the socket server connected to them.


I think you may be a 'little to close' to the (excellent) application you have 
written to understand the steep learning curve that I see.  You know the saying, 
Brain surgery is easy to a brain surgeon.  I should point out that I'm no 
newbie.  I've used PIL, ReportLab, BeautifulSoup, Mechanize, Win32 extensions, 
ElementTree and a whole host of other modules with less difficulty.  Please 
don't take this as anything more than an observation on my part.  From what I 
see, you have written (and generously donated) an extremely powerful library and 
it is greatly appreciated.  It is most likely just me.


As far as the book is concerned, I guess I'd purchase the only copy ;-).

I do appreciate your help very much.

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


Is it legal to rebuild Python.exe to include Version property tab?

2008-07-15 Thread ward . david
My company distributes a COM object that can be license and userd by
our customers. Some of my company's internal application also use the
COM object. However, for internal applications, instead of licensing
the COM object, we just make the application registered as friendly.
We accomplish this be including various information in the version
property tab of the calling EXE.

In my case, the calling EXE is Python.exe. So, my question is, can we
rebuild Python.exe to include the various version information? Is
this allowed under the Python licensing agreement?
--
http://mail.python.org/mailman/listinfo/python-list


Re: One step up from str.split()

2008-07-15 Thread Sion Arrowsmith
Joel Koltner [EMAIL PROTECTED] wrote:
I normally use str.split() for simple splitting of command line arguments, but 
I would like to support, e.g., long file names which-- under windows -- are 
typically provided as simple quoted string.  E.g.,

myapp --dosomething --loadthis my file name.fil

...and I'd like to get back a list wherein ListEntry[3]=my file name.fil , 
 [ ... ]

Hang on, let's back up here a second. You want a command line like

myapp --dosomething --loadthis my file name.fil

to be available as ['--dosomething', '--loadthis', 'my file name.fil'] ?

What's wrong with sys.argv ?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   Frankly I have no feelings towards penguins one way or the other
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python internals

2008-07-15 Thread Larry Bates

Peter Anderson wrote:
Hi!  I am slowly teaching myself Python.  I was reading David Beazley's 
excellent book Python - Essential Reference; in particular about 
variables.  Let me quote:


Python is a dynamically typed language in which names can represent 
values of different types during the execution of a program. In fact the 
names used in the program are really just labels for various quantities 
and objects. The assignment operator simply creates an association 
between a name and a value. This is different from C, for example, in 
which a name (variable) represents a fixed size and location in memory...


As an old mainframe programmer, I understand the way C does things with 
variable but this text got me wondering how Python handles this 
association between variable name and value at the lower level.  Is it 
like a fifo list?


If there is any Python guru that can help I would be most interested in 
your thoughts.


Regards,
Peter


Names are pointers in Python that point to values in memory.  Names are bound 
to these values with assignment.  Names are NOT buckets where you put values as 
is the case (or thought process) in other languages.  Example:


a = list(1,2,3)
b = a

Now a AND b point to the same list in memory

Note: if you wanted a COPY of the list you should do:

b = a[:]

Names can also point to functions, class instances, class methods or any other 
object. Example:


def foo(arg):
   print arg


bar = foo

Now you can call bar(arg) or foo(arg) and it will do exactly the same thing.

If you ever wrote assembler than you will begin to understand.  varibles are 
pointers to objects, not buckets were stuff is stored.


Hope this helps some.

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


Re: Using Python To Launch Python

2008-07-15 Thread Aquil H. Abdullah
Ack, .bat files! Yes, you are correct Windows does not ship with Python, and
there are ways to get bash (cygwin) on your Windoze system.  I am leaning
towards a solution similar to your second suggestion as it will keep me from
having to distribute .bat files for one platform and .sh files for another.
Thank you for all of your suggestions.

On Mon, Jul 14, 2008 at 8:39 PM, Derek Martin [EMAIL PROTECTED] wrote:

 On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote:
  You've hit the proverbial nail with the hammer.  The problem is that my
  application needs to run under both the Linux and Windows OSs, so while I
  would love to use a nice sh, csh, or bash shell script. My hands are tied
  because Windows does not provide such wonderful shells.

 *Provides*, no... neither does it provide Python, for what that's
 worth.  But you can certainly get it (bash):

  http://win-bash.sourceforge.net/

 I suppose it's not worth installing just for this purpose though...
 But you can provide with your application a DoS batch file that does
 exactly the same thing (in addition to a shell script).  The user
 would quite intuitively use whichever were appropriate, or follow your
 provided directions otherwise.  Or, the equivalent in (hopefully
 OS-agnostic) Python:

 import os, sys

 # I believe this gets the name of the root in all major OSes
 def root_dir(path):
if os.path.dirname(path) == path:
return path
return (root_dir(os.path.dirname(path)))

 appname = name of your python script
 root = root_dir(os.getcwd())
 install_path = os.path.join(root, usr)
 bin_path = os.path.join(install_path, bin)
 os.environ[PATH] = bin_path + os.pathsep + os.environ[PATH]
 python_path = os.path.join(bin_path, python)
 args = sys.argv[1:]
 args.insert(0, os.path.join(bin_path, appname))
 args.insert(0, python_path)
 args.insert(0, python_path)
 os.execv(python_path, args)






-- 
Aquil H. Abdullah
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Re: Using Python To Launch Python

2008-07-15 Thread Aquil H. Abdullah
Ahh, Win-BASH cool!!!

On Tue, Jul 15, 2008 at 10:41 AM, Aquil H. Abdullah 
[EMAIL PROTECTED] wrote:

 Ack, .bat files! Yes, you are correct Windows does not ship with Python,
 and there are ways to get bash (cygwin) on your Windoze system.  I am
 leaning towards a solution similar to your second suggestion as it will keep
 me from having to distribute .bat files for one platform and .sh files for
 another.  Thank you for all of your suggestions.


 On Mon, Jul 14, 2008 at 8:39 PM, Derek Martin [EMAIL PROTECTED] wrote:

 On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote:
  You've hit the proverbial nail with the hammer.  The problem is that my
  application needs to run under both the Linux and Windows OSs, so while
 I
  would love to use a nice sh, csh, or bash shell script. My hands are
 tied
  because Windows does not provide such wonderful shells.

 *Provides*, no... neither does it provide Python, for what that's
 worth.  But you can certainly get it (bash):

  http://win-bash.sourceforge.net/

 I suppose it's not worth installing just for this purpose though...
 But you can provide with your application a DoS batch file that does
 exactly the same thing (in addition to a shell script).  The user
 would quite intuitively use whichever were appropriate, or follow your
 provided directions otherwise.  Or, the equivalent in (hopefully
 OS-agnostic) Python:

 import os, sys

 # I believe this gets the name of the root in all major OSes
 def root_dir(path):
if os.path.dirname(path) == path:
return path
return (root_dir(os.path.dirname(path)))

 appname = name of your python script
 root = root_dir(os.getcwd())
 install_path = os.path.join(root, usr)
 bin_path = os.path.join(install_path, bin)
 os.environ[PATH] = bin_path + os.pathsep + os.environ[PATH]
 python_path = os.path.join(bin_path, python)
 args = sys.argv[1:]
 args.insert(0, os.path.join(bin_path, appname))
 args.insert(0, python_path)
 args.insert(0, python_path)
 os.execv(python_path, args)






 --
 Aquil H. Abdullah
 [EMAIL PROTECTED]




-- 
Aquil H. Abdullah
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Re: Suggestion: Python global scope

2008-07-15 Thread André
On Jul 15, 10:13 am, Nick Dumas [EMAIL PROTECTED] wrote:
 The function of the global keyword is to 'push' local variables to the
 global scope. If you want to 'import' a variable into a local scope,
 pass the variable to your function/method as an argument.
 Anonymous Bastard wrote:
  I've been tossing this idea in my mind for some time now:

  In Python, declaring a variable using the global statement automatically
  makes it available in all subsequent scopes.

  But to me, it makes more sense to use the global statement to 'import' a
  variable from the global scope into the current scope. For instance:

  [code]
  global X
  X = 1

  def P():
      X = 2
      print X
      global X
      print X

  print X
  P()
  print X
  [code]

  Currently, this will print 1, 2, 2 and 2. But if global would be limited
  to current scope, it would print 1, 2, 1, 1.

  'X = 2' would work on the local version of X, 'global X' will 'import'
  the global X into the local scope, so any actions on X would reference
  the global X, rather than previous X.

Alternatively, inside the function, you can have
_X = X
and use _X afterwards.  This is a lot more explicit imo.  Giving a
different meaning to global like the one you suggest would make it
extremely difficult to mimic its current behaviour - whereas what you
want to do can be done with a simple change assignment (or passing an
argument to the function).

Ask yourself: given change Y that I propose to Python, how would I
still be able to do Z which is the current behaviour and is found to
be useful by others?

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


Re: Is it legal to rebuild Python.exe to include Version property tab?

2008-07-15 Thread Michiel Overtoom
Ward wrote...

 Can we rebuild Python.exe to include the various version 
 information?

Why rebuild it? You can use a resource editor tool to add/edit/delete the
VERSIONINFO from any Windows executable, including Python.exe ;-)

Greetings,

-- 
The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing. - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


MySQL Insert

2008-07-15 Thread maestroQC
Hi,

Its one of those days. I cannot solve this. Any help would be greatly
appreciated!
When I execute this:

class Db(object):
def insertAccount(self, date, accountNumber, description,
openingBalance):
dec = decimal.Decimal(openingBalance)
db = MySQLdb.connect(host=localhost, user=dumb,
passwd=dumber, db=rdc)
cursor = db.cursor()
cursor.execute(INSERT INTO es_accounts (dateCreated,
accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d),
(date, accountNumber, description, dec))

I get this error:
Traceback (most recent call last):
  File main.py, line 59, in module
main()
  File main.py, line 40, in main
dbObj.insertAccount(dateTo, item[0], item[1], item[8])
  File C:\projects\workspace\INYR_ES_0.1\src\db.py, line 19, in
insertAccount
cursor.execute(INSERT INTO es_accounts (dateCreated,
accountNumber, description, openingBalance) VALUES (%s, %s, %s
, %d), (date, accountNumber, description, dec))
  File c:\python25\lib\site-packages\MySQLdb\cursors.py, line 151,
in execute
query = query % db.literal(args)
TypeError: int argument required

My table is defined as:
CREATE TABLE es_accounts (
id int(6) not null auto_increment,
dateCreated date DEFAULT '-00-00',
accountNumber int(6) not null,
description varchar(255) not null,
openingBalance decimal(15,8) NOT NULL DEFAULT 0.,
primary key (id)
);

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


String flags - redundant?

2008-07-15 Thread Alexandru Palade

Hi to everyone,

I'm rather a Python newbie, so I've put myself a question. Are these two 
statements (performance-wise) equal?


r Text 
and
 Text 

I mean using the raw flag speeds up things because the interpreter 
doesn't need to look after escape sequences? Or it's rather optimized? 
I'm asking you this because I want to know how my -style comments 
should be written in order not to affect the performance.


And another short question... Are there any flags to specify variables 
intercalation in a string? I mean I have x apples, how can i specify 
for the interpreter to substitute x with it's value? (in case *x* is a 
variable). And if this flag exists is it better to use I have  + x +  
apples or the above mentioned way?


Thank you for your time,
Alex.
--
http://mail.python.org/mailman/listinfo/python-list


Zipping files

2008-07-15 Thread dp_pearce
Hi all,

I have come across an error while using zipfile and I can't seem to
find somewhere that explains the problem. My script needs to be able
to take text files from one drive and add them to zip files on another
drive. The following seems to work just fine.

import zipfile

# write test file in working directory directory
folder = J:/
filename = testing.txt
fullpath = folder+filename
fout = open(fullpath, 'wt')
fout.write(str1)
fout.close()

# Add text file to zip file on same drive
zFolder = J:/
zFilename = testing.zip
zFullpath = zFolder+zFilename
zout = zipfile.ZipFile(zFullpath, w)
zout.write(fullpath)
zout.close()
print fullpath, successfully added to, zFullpath

However, if I change the drive letters to anything other than the
drive from which the Python script is saved (e.g. run script from J:
but zip to C:), I get the following warning:

Traceback (most recent call last):
File J:/test.py, line 18, in module
zout = zipfile.ZipFile(zFullpath, w)
File C:\Python25\lib\zipfile.py, line 339, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 13] Permission denied: 'C:/testing.zip'

Can anyopne shed some light on what I am missing here? If it has any
relevance to the permissions part of the error, I am currently using
Windows machines.

Thanks in advance for your time.

Dan

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


installation error on linux 64

2008-07-15 Thread Marc-André Belzile
Hi,
 
I've compiled python 2.5.2 on red hat r4 and got this installation error:
 
mtl-p1892:[Python-2.5.2] 1make install 

...
Compiling 
/BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_module.py ...
Compiling 
/BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_multibytecodec.py
 ...
Sorry: UnicodeError: (\\N escapes not supported (can't load unicodedata 
module),)
Compiling 
/BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_multibytecodec_support.py
 ...
...
make: *** [libinstall] Error 1

 
Looks like I'm missing some codec. Any idea how I can fix that ?
 
Thanks for your help.
 
-mab 
--
http://mail.python.org/mailman/listinfo/python-list

Invoking non-static methods of a non-Python object instance

2008-07-15 Thread Dobedani
Dear All,

For some time now, I have been working with the ctypes module on
Windows. First I got my hands on a library developed with Delphi 7.
That library is exporting plain functions. Internally, reference is
made to the instance of a class, which is instantiated in a kind of
initialization section. Everything works fine.
Now, I have developed a library in C#. I am able to get the result
from static methods, e.g.
public static String sayHello() {
String msg = Hello from MyLib, working in folder ;
return msg + Directory.GetCurrentDirectory();
}
To make sure that the libray can work as a Win32 library, I have added
a V-Table by disassembling and then editing the IL code then compiling
again, see: 
http://www.blong.com/Articles/DotNetInteropD8/Interop1/Win32AndDotNetInterop.htm

However, in my code I am actually exporting the methods of a class and
I added non-static methods - unlike what was the case with the DLL
developed in Delphi. Unfortunately, it appears impossible to keep a
reference to an instance of my class in the Python code. Suppose, I
remove the keyword static from the above method declaration, this
fails whatever I try:
from ctypes import *;
mylib = windll.LoadLibrary(MyLib);
mylib.getInstance.restype = ?
myInst = mylib.getInstance();
print myInst.sayHello();

Is there a way to do this? FYI: I don't want to work with win32client,
because this will require that my users install an extra extension and
I am expected to deliver something which can work without such extra
extensions. I look forward to your ideas!

Kind regards,
Dobedani

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


Re: Testing for Internet Connection

2008-07-15 Thread Alexnb



Ben Finney-2 wrote:
 
 Alexnb [EMAIL PROTECTED] writes:
 
 I am wondering, is there a simple way to test for Internet
 connection? If not, what is the hard way :p
 
 Refine the question: What do you mean by internet? It isn't a single
 entity.
 
 Do you mean some particular internet host responding on a particular
 network port?
 
 If you can define exactly what you mean by internet connection, the
 test for it becomes correspondingly easier.
 
 -- 
  \  “Why should I care about posterity? What's posterity ever done |
   `\for me?” —Groucho Marx |
 _o__)  |
 Ben Finney
 --
 http://mail.python.org/mailman/listinfo/python-list
 

Well, really I just need to figure out if I am able to connect to one site.
That site is dictionary.com.
-- 
View this message in context: 
http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18468350.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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

Re: Is it legal to rebuild Python.exe to include Version property tab?

2008-07-15 Thread ward . david
On Jul 15, 7:42 am, Michiel Overtoom [EMAIL PROTECTED] wrote:
 Why rebuild it? You can use a resource editor tool to add/edit/delete the
 VERSIONINFO from any Windows executable, including Python.exe ;-)

M,

Thanks for you suggestion. I didn't know that there was anything like
a resource editor outside of a dev IDE. You learn something new
everyday. :)

So, we've established that there is a different way to edit the
VERSIONINFO of an EXE. However, the question still remains as to
whether is is legal to edit the VERSIONINFO on Python.exe and
distribute it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python internals question

2008-07-15 Thread Helmut Jarausch

Peter Anderson wrote:
Hi! I am slowly teaching myself Python. I was reading David Beazley's 
excellent book Python - Essential Reference; in particular about 
variables. Let me quote:


Python is a dynamically typed language in which names can represent 
values of different types during the execution of a program. In fact the 
names used in the program are really just labels for various quantities 
and objects. The assignment operator simply creates an association 
between a name and a value. This is different from C, for example, in 
which a name (variable) represents a fixed size and location in memory...


As an old mainframe programmer, I understand the way C does things with 
variable but this text got me wondering how Python handles this 
association between variable name and value at the lower level. Is it 
like a fifo list?


If there is any Python guru that can help I would be most interested in 
your thoughts.




Please have a look at

http://effbot.org/zone/call-by-object.htm

and

http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/


--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
--
http://mail.python.org/mailman/listinfo/python-list


Re: String flags - redundant?

2008-07-15 Thread Marc 'BlackJack' Rintsch
On Tue, 15 Jul 2008 18:14:15 +0300, Alexandru Palade wrote:

 I'm rather a Python newbie, so I've put myself a question. Are these two 
 statements (performance-wise) equal?
 
 r Text 
 and
  Text 
 
 I mean using the raw flag speeds up things because the interpreter 
 doesn't need to look after escape sequences? Or it's rather optimized? 
 I'm asking you this because I want to know how my -style comments 
 should be written in order not to affect the performance.

*Please* stop worrying about the speed of the compilation here.  If you
have doubts about speed then measure and find the bottlenecks in your code
and iff you find hotspots *then* try to optimize.  But only iff the
program is *to slow*, not when it's fast enough anyway.  In that case you
should always favor more readable code above speed.

 And another short question... Are there any flags to specify variables 
 intercalation in a string? I mean I have x apples, how can i specify 
 for the interpreter to substitute x with it's value? (in case *x* is a 
 variable). And if this flag exists is it better to use I have  + x +  
 apples or the above mentioned way?

Maybe you should work through the tutorial in the Python documentation.

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


Re: Python internals question

2008-07-15 Thread Marc 'BlackJack' Rintsch
On Tue, 15 Jul 2008 23:54:46 +1000, Peter Anderson wrote:

 Python is a dynamically typed language in which names can represent 
 values of different types during the execution of a program. In fact the 
 names used in the program are really just labels for various quantities 
 and objects. The assignment operator simply creates an association 
 between a name and a value. This is different from C, for example, in 
 which a name (variable) represents a fixed size and location in memory...
 
 As an old mainframe programmer, I understand the way C does things with 
 variable but this text got me wondering how Python handles this 
 association between variable name and value at the lower level. Is it 
 like a fifo list?

Why a fifo list?  Names don't remember the values and types they are bound
to over time, there's just one binding at any time if a name exists. 
Internally you can think of a pointer to a struct that represents the
object.

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


Re: Testing for Internet Connection

2008-07-15 Thread Grant Edwards
 If you can define exactly what you mean by internet connection, the
 test for it becomes correspondingly easier.

 Well, really I just need to figure out if I am able to connect
 to one site. That site is dictionary.com.

Then use urllib2 to try to fetch a page from dictionary.com. If
it works, you're connected.  If it fails, you're not.  The
most straight-forward way to find out if you can do X is to try
to do X.

-- 
Grant Edwards   grante Yow! if it GLISTENS,
  at   gobble it!!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing for Internet Connection

2008-07-15 Thread Alexnb



Troeger Thomas (Ext) wrote:
 
 Alex Marandon wrote:
 Alexnb wrote:
 I am wondering, is there a simple way to test for Internet connection?
 If
 not, what is the hard way :p
 
 Trying to fetch the homepage from a few major websites (Yahoo, Google, 
 etc.)? If all of them are failing, it's very likely that the connection 
 is down. You can use urllib2 [1] to accomplish that.
 
 [1] http://docs.python.org/lib/module-urllib2.html
 
 This seems to work and is rather fast and wastes no bandwidth:
 
 ==
 #!/usr/bin/python
 
 import socket, struct
 
 def check_host(host, port, timeout=1):
   
   Check for connectivity to a certain host.
   
   # assume we have no route.
   ret=False
 
   # connect to host.
   try:
   # create socket.
   sock=socket.socket()
   # create timeval structure.
   timeval=struct.pack(2I, timeout, 0)
   # set socket timeout options.
   sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)
   sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, timeval)
   # connect to host.
   sock.connect((host, port))
   # abort communications.
   sock.shutdown(SHUT_RDWR)
   # we have connectivity after all.
   ret=True
   except:
   pass
 
   # try to close socket in any case.
   try:
   sock.close()
   except:
   pass
 
   return ret
 
 #  main -
 
 if check_host(www.heise.de, 80):
   print Horray!
 else:
   print We've lost headquarters!
 ==
 
 I hope the code is ok, but there is always something you can do better. 
 Comments? :)
 
 Cheers,
 Thomas.
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 

Thomas this code did not work on google.com and I also tried it with port
443
-- 
View this message in context: 
http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18468756.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Is it legal to rebuild Python.exe to include Version property tab?

2008-07-15 Thread Victor Noagbodji
I think it is. I got a bundle of Python named EnthoughtPython and the
version string gave something different from original Python.

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


Re: Zipping files

2008-07-15 Thread Tim Golden

dp_pearce wrote:

Hi all,

I have come across an error while using zipfile and I can't seem to
find somewhere that explains the problem. My script needs to be able
to take text files from one drive and add them to zip files on another
drive. The following seems to work just fine.

import zipfile

# write test file in working directory directory
folder = J:/
filename = testing.txt
fullpath = folder+filename
fout = open(fullpath, 'wt')
fout.write(str1)
fout.close()

# Add text file to zip file on same drive
zFolder = J:/
zFilename = testing.zip
zFullpath = zFolder+zFilename
zout = zipfile.ZipFile(zFullpath, w)
zout.write(fullpath)
zout.close()
print fullpath, successfully added to, zFullpath

However, if I change the drive letters to anything other than the
drive from which the Python script is saved (e.g. run script from J:
but zip to C:), I get the following warning:

Traceback (most recent call last):
File J:/test.py, line 18, in module
zout = zipfile.ZipFile(zFullpath, w)
File C:\Python25\lib\zipfile.py, line 339, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 13] Permission denied: 'C:/testing.zip'

Can anyopne shed some light on what I am missing here? If it has any
relevance to the permissions part of the error, I am currently using
Windows machines.



Is it possible that you don't in fact have permission
to write to c:\? I seem to recall that non-power-users
on XP don't have that permission, and I bet that Vista
makes that even more restrictive.

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


Re: How can I save command prompt screen

2008-07-15 Thread Tim Golden

Ty hensons wrote:

how can i save my command prompt screen?


(Trying to be helpful here...)

What do mean by save and what do you mean
by command prompt screen? And, especially,
what platform are you running on?

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


Re: About wmi

2008-07-15 Thread Tim Golden

patrol wrote:

Situation (2):
result = new_process.terminate()
  File C:\Python25\lib\wmi.py, line 494, in __getattr__
handle_com_error (error_info)
  File C:\Python25\lib\wmi.py, line 190, in handle_com_error
raise x_wmi, \n.join (exception_string)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
14: ordinal
 not in range(128)

BTW, My windows' languange is Chinese.



Well that looks embarrassingly like a complete lack
of unicode-awareness in the wmi module. Would you
mind trying this version:

http://timgolden.me.uk/wmi-project/wmi.py

which is a copy of the svn trunk to see if that
improves the UnicodeDecode error, please? I'll
try to get an install of a non-English edition of
Windows but, as you might imagine, I normally run
the UK version so don't hit these kind of issue
myself.

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


Re: Logging to different addressees

2008-07-15 Thread McA
Hi Vinary,

thank you for answering. I start be proud that the author of
the logging package himself is answering.  :-)

On 15 Jul., 15:51, Vinay Sajip [EMAIL PROTECTED] wrote:
 On Jul 15, 1:27 pm, McA [EMAIL PROTECTED] wrote:




 Add a handler to the root logger (or common_logger) to send to the
 admin sink.

That's clear.

 Add a handler to certain_logger to send to the addressee sink.

That's also clear.

 If you added the admin sink handler to the root logger, you're done.

Isn't that the first thing above? What do you mean?

 Otherwise, you need to ensure that certain_logger is a child of
 common_logger.

What I want to code is something like that.
a) I know thet this is a message for the admin only:
admin_logger.log('blabla')  (admin_logger = root_logger =
logging.get_logger())

b) certain_logger.log('something'  = log to the root/admin/-sink as
well as to the
certain-sink.

Do I have to create a logger subclass where I do the multiplexing of
the logging messages?
I'm pretty sure I miss something. ;-)


 Regards,

 Vinay Sajip

Regards
Andreas Mock

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


Re: Method behavior for user-created class instances

2008-07-15 Thread crazychimp132
On Jul 15, 9:53 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 On 15 juil, 01:24, [EMAIL PROTECTED] wrote:

  Greetings.

  I am looking for a way to achieve method behavior for a class I
  created. That is, it has a __call__ method,  so can be called like a
  function. But I also want it to be treated as a method when it appears
  in a class body.

 You need to implement the descriptor protocol the same way the
 function type do.

 import types

 class Foo(object):
 def __call__(self, instance):
 print %s - %s % (self, instance)

 def __get__(self, instance, cls):
 return types.MethodType(self, instance, cls)

 class Bar(object):
 foo = Foo()

 b = Bar()
 b.foo()

  I know this has to do with writing the __get__
  method of foo, but I am wondering if there is perhaps some class I can
  just inherit from to get the proper __get__, which behaves identically
  to that of regular Python functions.

 Extending types.FunctionType doesn't work OOTB (there's some
 incompatibility wrt/ metaclasses)

Thanks, this got me started in writing it for 3.0. There are no more
unbound methods in 3.0, so a check for whether instance is None is
necessary to give the right behavior. Here is the final implementation
I came up with:

from abc import ABCMeta, abstractmethod
from functools import update_wrapper
from types import MethodType

class decorator(metaclass = ABCMeta):
def __init__(self, function):
update_wrapper(self, function)
self.function = function

def __get__(self, instance, cls):
if instance is None:
return self
return MethodType(self, instance)

@abstractmethod
def __call__(): pass

To use it, write a class that inherits decorator and overrides
__call__, probably doing something with self.function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: About wmi

2008-07-15 Thread Tim Golden

patrol wrote:

Situation (1):
result = new_process.terminate()
TypeError: 'int' object is not callable


I'm not sure exactly what's causing that
particular effect, but I would suggest that
you call the method as .Terminate (note the
initial capital). On my box, calling .terminate
simply raises an AttributeError as expected,
but I do remember encountering the situation
you're describing in some situation which
now escapes me.

At any rate, try using:

result, = new_process.Terminate ()

and note that the return value is a tuple,
not a single number. The code will work either
way, but in your case result will be a tuple
of length one; in mine, result will be a number.

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


isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread defn noob
isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?


def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

 [isPrime(y) for y in range(11)]

Traceback (most recent call last):
  File pyshell#45, line 1, in module
[isPrime(y) for y in range(11)]
  File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment


 map(isPrime, range(100))

Traceback (most recent call last):
  File pyshell#38, line 1, in module
map(isPrime, range(100))
  File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment
 isPrime(10)
False
 isPrime(11)
True



adding x=1 makes it work though:

def isPrime(nbr):
x=1
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False


 [isPrime(y) for y in range(11)]
[False, True, True, True, False, True, False, True, False, False,
False]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Zipping files

2008-07-15 Thread dp_pearce
When I saw Permission denied, this was my suspicion. And I think you
are very right. I have just gone back and tried writing to a file
outside of C:, in this case C:/output/, and it seems to work again.

Would I be right in guessing there is no way around this?

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


Re: Zipping files

2008-07-15 Thread Tim Golden

dp_pearce wrote:

When I saw Permission denied, this was my suspicion. And I think you
are very right. I have just gone back and tried writing to a file
outside of C:, in this case C:/output/, and it seems to work again.

Would I be right in guessing there is no way around this?


Well, you could (presumably) alter your own user's
groups / rights and/or the permissions on the root
of the C: drive so that you *can* zip to that location.

On the other hand, chucking random stuff into the
root of the system drive has never been considered
a brilliant idea. (Altho' I know a lot of people
who do it :) ). Why not create a suitable folder
lower down, or in your own %APPDATA% area, or using
the tempfile module, depending on your needs?

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


Re: Suggestion: Python global scope

2008-07-15 Thread Carl Banks
On Jul 15, 7:57 am, Anonymous Bastard [EMAIL PROTECTED] wrote:
 I've been tossing this idea in my mind for some time now:

 In Python, declaring a variable using the global statement automatically
 makes it available in all subsequent scopes.

 But to me, it makes more sense to use the global statement to 'import' a
 variable from the global scope into the current scope.

No way.  You'd need to find another keyword.  localize might be a
better word to use.


 For instance:

 [code]
 global X
 X = 1

 def P():
      X = 2
      print X
      global X
      print X

 print X
 P()
 print X
 [code]

 Currently, this will print 1, 2, 2 and 2. But if global would be limited
 to current scope, it would print 1, 2, 1, 1.

What would it print if you changed P to this?

def P():
 X = 2
 print X
 global X
 print X
 X = 3

Would it print 1, 2, 1, 1 or 1, 2, 1, 3?


 'X = 2' would work on the local version of X, 'global X' will 'import'
 the global X into the local scope, so any actions on X would reference
 the global X, rather than previous X.

Do you have a specific use case in mind?  Where would this sort of
thing be useful?

(The be sure, I can think of a use case for something like this,
namely optimizing away hash lookups for frequently used globals.  But
such an optimization doesn't justify new syntax, especially when you
can already do it only slightly less conveniently.)


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


need ldap windows binary and/or installation help

2008-07-15 Thread Sells, Fred
I'm running python 2.5 (or 2.4) in an XP environment.

I downloaded and installed the .dll's from 
OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in 
c:/windows/system32 as instructed

now I get this error.  Is there anyway to avoid building the python_ldap 
binaries?  Apart from being lazy, I've got a secure system policy issue if I 
start compiling apps.  I could give up and just start running in linux, but my 
xp environment is much friendlier to develop in.  I've googled a lot, but all 
the links I've found talk to Unix or to compiling from source.

Even if I build from source, will the mingw compiler mentioned in most posts 
produce something that is compatible with Python was built with Visual Studio 
2003.

c:\alleasy_install python_ldap
Searching for python-ldap
Reading http://pypi.python.org/simple/python_ldap/
Reading http://pypi.python.org/simple/python-ldap/
Reading http://python-ldap.sourceforge.net/
Reading http://python-ldap.sourceforge.net/download.shtml
Reading 
http://sourceforge.net/project/showfiles.php?group_id=2072package_id=2011
Best match: python-ldap 2.3.5
Downloading 
http://downloads.sourceforge.net/python-ldap/python-ldap-2.3.5.tar.gz?modtime=1215364319big_mirror=0
Processing python-ldap-2.3.5.tar.gz
Running python-ldap-2.3.5\setup.py -q bdist_egg --dist-dir c:\documents and 
settings\frsells\local settings\temp\easy_install-uczq5i\python-ld
extra_compile_args:
extra_objects:
include_dirs: /usr/local/openldap-2.3/include /usr/include/sasl
library_dirs: /usr/local/openldap-2.3/lib
libs: ldap_r lber sasl2 ssl crypto
file Lib\ldap.py (for module ldap) not found
file Lib\ldap\schema.py (for module ldap.schema) not found
warning: no files found matching 'Makefile'
warning: no files found matching 'Modules\LICENSE'
file Lib\ldap.py (for module ldap) not found
file Lib\ldap\schema.py (for module ldap.schema) not found
file Lib\ldap.py (for module ldap) not found
file Lib\ldap\schema.py (for module ldap.schema) not found
error: Setup script exited with error: Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible binaries.
Visual Studio 2003 was not found on this system. If you have Cygwin installed,
you can try compiling with MingW32, by passing -c mingw32 to setup.py.

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread norseman


defn noob wrote:

isPrime works when just calling a nbr but not when iterating on a
list, why? adding x=1 makes it work though but why do I have to add
it?
Is there a cleaner way to do it?


def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False


[isPrime(y) for y in range(11)]


Traceback (most recent call last):
  File pyshell#45, line 1, in module
[isPrime(y) for y in range(11)]
  File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment



map(isPrime, range(100))


Traceback (most recent call last):
  File pyshell#38, line 1, in module
map(isPrime, range(100))
  File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
if x == nbr:
UnboundLocalError: local variable 'x' referenced before assignment

isPrime(10)

False

isPrime(11)

True



adding x=1 makes it work though:

def isPrime(nbr):
x=1
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False



[isPrime(y) for y in range(11)]

[False, True, True, True, False, True, False, True, False, False,
False]
--
http://mail.python.org/mailman/listinfo/python-list




Yep - local variable 'x' referenced before assignment is correct.
You state: for x in range... but x doesn't exist until initialized.
  To save a loop, initialize x=2 (the minimum value) and loop executes
  on pass one.
In a straight 'C' program
  (  for (x=1, x=(nbr+1), x++)  etc...  )
  the x is initialized and forceably incremented.
  seems Python does not auto initialize but does auto increment.


Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Measure class, precision, significant digits, and divmod()

2008-07-15 Thread Ethan Furman

Hey all.

My thanks to all who have responded so far with my other questions.  It 
is much appreciated.


Some background on what I'm doing (a good explanation can be found at 
http://www.hazelwood.k12.mo.us/~grichert/sciweb/phys8.htm):  When 
measuring, there is some uncertainty as to the *exact* value; so, when 
doing calculations with these measured numbers, one should not present 
an answer that seems more accurate than the source.  For addition and 
subtraction this means the final answer cannot be more precise than the 
least precise input:  5.0 + 21.23 = 26.2 (first number only measured to 
the tenths, so answer only good to the tenths); for multiplication and 
division this means the answer cannot have more significant digits than 
the input with the fewest significant digits:  231 * 0.25 = 58 (0.25 
only has two significant digits, so answer only has two significant 
digits).  Important point -- counting is not subject to precision error.


As I have mentioned before, I am making this Measure class for two 
reasons:  experience with unit testing, I like playing with numbers, I 
am unaware of anything like this having yet been done (okay, three 
reasons ;).


So far, I have the init, add, sub, mul, div, cmp, neg, pos, and abs 
done, and I'm ready to tackle floordiv, mod, and divmod... okay, maybe 
'ready' is too strong a word -- one of the obstacle's I'm facing is that 
I, myself, don't have any real use for this class, so I'm stuck on 
deciding how floordiv, mod, and divmod should function.  As mentioned 
above, counting is precise... so should divmod (a // b, a % b), which 
returns the count of times b goes into a, and the remainder, be an exact 
number, or should it behave like floor(a / b), and preserve the inherent 
inaccury present in the measured value a?  Should I have floordiv 
preserve inaccuracy, and divmod be exact?


Any and all feedback welcome, particularly from anyone who might 
actually use the Measure class.  ;)


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


Re: need ldap windows binary and/or installation help

2008-07-15 Thread Tim Golden

Sells, Fred wrote:

I'm running python 2.5 (or 2.4) in an XP environment.




I downloaded and installed the .dll's from 
OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in 
c:/windows/system32 as instructed

now I get this error.  Is there anyway to avoid building the python_ldap 
binaries?  Apart from being lazy, I've got a secure system policy issue if I 
start compiling apps.  I could give up and just start running in linux, but my 
xp environment is much friendlier to develop in.  I've googled a lot, but all 
the links I've found talk to Unix or to compiling from source.


Disclaimer. I know nothing about python-ldap. I simply
Googled for it and came to:

  http://python-ldap.sourceforge.net/download.shtml

which led me to

  http://www.osuch.org/python-ldap

from which I downloaded and ran the .msi

  http://www.osuch.org/python-ldap-2.3.5.win32-py2.5.msi

and Bob was at that point my uncle.

Was there some obstacle to your doing this? (It wasn't
clear whether some policy required you to compile from
source).

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


Re: fork after creating temporary file using NamedTemporaryFile

2008-07-15 Thread Sebastian lunar Wiesner
[EMAIL PROTECTED] [EMAIL PROTECTED]:

 When I create temporary file using the tempfile module, and forkI)
 later on in my program, I always see errors when the program exits. Is
 this because the child process deletes temp file?
 Here's a stripped down version of my script that exhibits this
 problem:
 
 #!/usr/bin/python
 
 import os
 import tempfile
 import sys
 
 cmd = []
 cmd.append('/bin/ls')
 cmd.append('-l')
 cmd.append('/tmp')
 
 foo = tempfile.NamedTemporaryFile(mode='w+b')
 
 pid = os.fork()
 if pid:
 print 'I am parent'
 else:
 print 'I am child'
 sys.exit(0)
 
 $ python sub.py
 I am child
 I am parent
 Exception exceptions.OSError: (2, 'No such file or directory', '/tmp/
 tmp-mZTPq') in bound method _TemporaryFileWrapper.__del__ of closed
 file 'fdopen', mode 'w+b' at 0xb7d2a578 ignored

NamedTemporaryFile attempts to delete the file, when close is invoked
(which is done by the destructor in this case, because you're senselessly
not closing that file explicitly).  A fork() clones the whole process
memory, after fork() is done, there are *two* NamedTemporaryFile objects,
pointing to the *same* file, existing in two separate process (one in the
parent, the other, cloned one, in the child).  When the first process
exists, the file is removed cleanly, the second process can't remove
anything anymore, since there's nothing left to remove.

Since the order of process execution is not deterministic and completely up
to the systems scheduler, you can *never* say, which one will exit first.  

You should replace NamedTempraryFile with mkstemp and take care of
deletion yourself.  You could for instance call os.wait to wait for the
child's termination in the parent process and thus delete the temporary
file, once the child has gone.

Of course, you could also catch the exception, if you properly close the
file object (what you should be doing anyway!), but I'd consider this a not
very robust solution.  If one of the two processes exit unexpectedly early,
the directory entry is gone, though it might still be needed by the parent
process.

 How can these warnings be avoided? I tried to catch this exception
 using try/except but it didn't work.

If you want to catch that exception, you should properly close the named
temporary file and wrap the close call inside a try-except statement. 
Beginning with Python 2.5 you might also want to use the with-statement
here.  Relying on the destructor is *always* a bad idea, you should always
close files explicitly!

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


File Locking Forced? Newbie question.

2008-07-15 Thread Sparky
Hello! I am writing some software that will have many users accessing
the same file resource at once for reading purposes only. I am
programming on (Ubuntu) Linux and my question is in Windows, can I
have it so that the same file can be open in read mode by more than
one person or could Window's file locking system get in the way?

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


RE: isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread Andreas Tawn
defn noob wrote:
 isPrime works when just calling a nbr but not when iterating on a
 list, why? adding x=1 makes it work though but why do I have to add
 it?
 Is there a cleaner way to do it?
 
 
 def isPrime(nbr):
 for x in range(2, nbr + 1):
 if nbr % x == 0:
 break
 if x == nbr:
 return True
 else:
 return False
 
 [isPrime(y) for y in range(11)]
 
 Traceback (most recent call last):
   File pyshell#45, line 1, in module
 [isPrime(y) for y in range(11)]
   File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
 if x == nbr:
 UnboundLocalError: local variable 'x' referenced before assignment
 
 
 map(isPrime, range(100))
 
 Traceback (most recent call last):
   File pyshell#38, line 1, in module
 map(isPrime, range(100))
   File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
 if x == nbr:
 UnboundLocalError: local variable 'x' referenced before assignment
 isPrime(10)
 False
 isPrime(11)
 True
 
 
 
 adding x=1 makes it work though:
 
 def isPrime(nbr):
 x=1
 for x in range(2, nbr + 1):
 if nbr % x == 0:
 break
 if x == nbr:
 return True
 else:
 return False
 
 
 [isPrime(y) for y in range(11)]
 [False, True, True, True, False, True, False, True, False, False,
 False]
 --
 http://mail.python.org/mailman/listinfo/python-list
 


Yep - local variable 'x' referenced before assignment is correct.
You state: for x in range... but x doesn't exist until initialized.
   To save a loop, initialize x=2 (the minimum value) and loop executes
   on pass one.
In a straight 'C' program
   (  for (x=1, x=(nbr+1), x++)  etc...  )
   the x is initialized and forceably incremented.
   seems Python does not auto initialize but does auto increment.

I think a better explanation is that in your original function, x only
existed while the for loop was running. As soon as execution hit the
break statement, x ceased to exist. When you attempted to reference it
in the next line, Python has no variable called x so it complains that x
hasn't been initialised.

A more idiomatic way to write it...

def isPrime(nbr):
if nbr = 1:
return False
for x in xrange(2, nbr+1):
if not nbr % x:
return x == nbr

Cheers,

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


Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread Mensanator
On Jul 15, 11:26 am, defn noob [EMAIL PROTECTED] wrote:
 isPrime works when just calling a nbr but not when iterating on a
 list, why? adding x=1 makes it work though but why do I have to add
 it?
 Is there a cleaner way to do it?

 def isPrime(nbr):
     for x in range(2, nbr + 1):
         if nbr % x == 0:
             break
     if x == nbr:
         return True
     else:
         return False

  [isPrime(y) for y in range(11)]

 Traceback (most recent call last):
   File pyshell#45, line 1, in module
     [isPrime(y) for y in range(11)]
   File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
     if x == nbr:
 UnboundLocalError: local variable 'x' referenced before assignment

  map(isPrime, range(100))

 Traceback (most recent call last):
   File pyshell#38, line 1, in module
     map(isPrime, range(100))
   File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
     if x == nbr:
 UnboundLocalError: local variable 'x' referenced before assignment 
 isPrime(10)
 False
  isPrime(11)

 True

 adding x=1 makes it work though:

 def isPrime(nbr):
     x=1
     for x in range(2, nbr + 1):
         if nbr % x == 0:
             break
     if x == nbr:
         return True
     else:
         return False

  [isPrime(y) for y in range(11)]

 [False, True, True, True, False, True, False, True, False, False,
 False]

No, it doesn't. You are falsely reporting that 1 is prime.

And instead of making the fake variable x, shouldn't you
instead test that nbr+1 is greater than 2? Or call it with
range(3,11) instead of range(11)? x isn't initialized
because if nbr+1 is =2, the for loop has an invalid range
and doesn't even execute.
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Insert

2008-07-15 Thread Carsten Haese

maestroQC wrote:

cursor.execute(INSERT INTO es_accounts (dateCreated,
accountNumber, description, openingBalance) VALUES (%s, %s, %s
, %d), (date, accountNumber, description, dec))
  File c:\python25\lib\site-packages\MySQLdb\cursors.py, line 151,
in execute
query = query % db.literal(args)
TypeError: int argument required


The placeholder for query parameters in MySQLdb is always %s, regardless 
of the data type the actual value might have.


HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Locking Forced? Newbie question.

2008-07-15 Thread Tim Golden

Sparky wrote:

Hello! I am writing some software that will have many users accessing
the same file resource at once for reading purposes only. I am
programming on (Ubuntu) Linux and my question is in Windows, can I
have it so that the same file can be open in read mode by more than
one person or could Window's file locking system get in the way?


Assuming your question is: can processes A, B  C read
from the same file at the same time, then: Yes. (You
can try it out yourself fairly easily if you want. Just
open a clutch of interpreter windows and do some
open (abc.txt, r).read () stuff in each one).

But I'm surprised you think that anything might get
in the way of that. It would be a fairly limiting file
system which prevented multiple simultaneous readers.

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


Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread defn noob
On Jul 15, 7:28 pm, Mensanator [EMAIL PROTECTED] wrote:
 On Jul 15, 11:26 am, defn noob [EMAIL PROTECTED] wrote:



  isPrime works when just calling a nbr but not when iterating on a
  list, why? adding x=1 makes it work though but why do I have to add
  it?
  Is there a cleaner way to do it?

  def isPrime(nbr):
      for x in range(2, nbr + 1):
          if nbr % x == 0:
              break
      if x == nbr:
          return True
      else:
          return False

   [isPrime(y) for y in range(11)]

  Traceback (most recent call last):
    File pyshell#45, line 1, in module
      [isPrime(y) for y in range(11)]
    File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
      if x == nbr:
  UnboundLocalError: local variable 'x' referenced before assignment

   map(isPrime, range(100))

  Traceback (most recent call last):
    File pyshell#38, line 1, in module
      map(isPrime, range(100))
    File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
      if x == nbr:
  UnboundLocalError: local variable 'x' referenced before assignment 
  isPrime(10)
  False
   isPrime(11)

  True

  adding x=1 makes it work though:

  def isPrime(nbr):
      x=1
      for x in range(2, nbr + 1):
          if nbr % x == 0:
              break
      if x == nbr:
          return True
      else:
          return False

   [isPrime(y) for y in range(11)]

  [False, True, True, True, False, True, False, True, False, False,
  False]

 No, it doesn't. You are falsely reporting that 1 is prime.

 And instead of making the fake variable x, shouldn't you
 instead test that nbr+1 is greater than 2? Or call it with
 range(3,11) instead of range(11)? x isn't initialized
 because if nbr+1 is =2, the for loop has an invalid range
 and doesn't even execute.


def isPrime(nbr):
for x in range(2, nbr + 1):
if nbr % x == 0:
break
if x == nbr:
return True
else:
return False

this works for all primes, if i want to not include 1 i just do if
nbr=1 return false

you are answering the wrong question.


anyway here is a clear one:
def isPrime(nbr):
if nbr  2:
return False
for x in range(2, nbr + 1):
if nbr % x == 0:
return nbr == x
--
http://mail.python.org/mailman/listinfo/python-list


Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-15 Thread Mensanator
On Jul 15, 12:28 pm, Andreas Tawn [EMAIL PROTECTED] wrote:
 defn noob wrote:
  isPrime works when just calling a nbr but not when iterating on a
  list, why? adding x=1 makes it work though but why do I have to add
  it?
  Is there a cleaner way to do it?

  def isPrime(nbr):
      for x in range(2, nbr + 1):
          if nbr % x == 0:
              break
      if x == nbr:
          return True
      else:
          return False

  [isPrime(y) for y in range(11)]

  Traceback (most recent call last):
    File pyshell#45, line 1, in module
      [isPrime(y) for y in range(11)]
    File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
      if x == nbr:
  UnboundLocalError: local variable 'x' referenced before assignment

  map(isPrime, range(100))

  Traceback (most recent call last):
    File pyshell#38, line 1, in module
      map(isPrime, range(100))
    File C:\Python25\Progs\blandat\myMath.py, line 9, in isPrime
      if x == nbr:
  UnboundLocalError: local variable 'x' referenced before assignment
  isPrime(10)
  False
  isPrime(11)
  True

  adding x=1 makes it work though:

  def isPrime(nbr):
      x=1
      for x in range(2, nbr + 1):
          if nbr % x == 0:
              break
      if x == nbr:
          return True
      else:
          return False

  [isPrime(y) for y in range(11)]
  [False, True, True, True, False, True, False, True, False, False,
  False]
  --
 http://mail.python.org/mailman/listinfo/python-list

 
 Yep - local variable 'x' referenced before assignment is correct.
 You state: for x in range... but x doesn't exist until initialized.
    To save a loop, initialize x=2 (the minimum value) and loop executes
    on pass one.
 In a straight 'C' program
    (  for (x=1, x=(nbr+1), x++)  etc...  )
    the x is initialized and forceably incremented.
    seems Python does not auto initialize but does auto increment.

 I think a better explanation is that in your original function, x only
 existed while the for loop was running.

The for loop never ran.

 As soon as execution hit the break statement,

It never hit the break statement, the first call from
[isPrime(y) for y in range(11)]
attempted to do for x in range(2,1).

 x ceased to exist.

Something has to exist before it can cease to exist.

 When you attempted to reference it
 in the next line, Python has no variable called x so it complains that x
 hasn't been initialised.

Right conlusion but false premise.


 A more idiomatic way to write it...

 def isPrime(nbr):
     if nbr = 1:
         return False
     for x in xrange(2, nbr+1):
         if not nbr % x:
             return x == nbr

 Cheers,

 Drea

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


  1   2   3   >