Problems with subclassing enum34

2013-06-28 Thread Thomas Heller

trying out the enum34 module.

What I want to create is a subclass of enum.Enum that is also
based on ctypes.c_int so that I can better use enum instances
in ctypes api calls.

When I do this, I get a metaclass conflict:


>>> class MyEnum(ctypes.c_int, enum.Enum):
...FOOBAR = 0
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a 
(non-strict) subclass of the metaclasses of all its bases

>>>



When I do this, it does not work either:

>>> class MyEnum_meta(type(ctypes.c_int), type(enum.Enum)):
... pass
...
>>> class MyEnum(ctypes.c_int, enum.Enum):
... FOOBAR = 42
... __metaclass__ = MyEnum_meta
...
>>> MyEnum.FOOBAR
42
>>>

It should have printed ''.

Any ideas?

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


Re: Problems with subclassing enum34

2013-06-28 Thread Thomas Heller

Am 28.06.2013 17:16, schrieb Ethan Furman:

On 06/28/2013 03:48 AM, Thomas Heller wrote:

trying out the enum34 module.

What I want to create is a subclass of enum.Enum that is also based
on ctypes.c_int so that I can better use enum instances in ctypes
api calls.


Have you tried using enum.IntEnum?  If you were able to pass ints in
 before, IntEnum should work.


I'm sure that IntEnum works as expected, but I need enums that are
subclasses of ctypes.c_int (so that argument type checking and return
value conversions in ctypes api calls work).

Robert Kern:



enum.EnumMeta uses super() in its __new__() implementation but
_ctypes.PyCSimpleType doesn't. Thus, only
_ctypes.PyCSimpleType.__new__() gets a chance to run. Switching the
order of the two might work.



Robert found the problem but I'm unsure if there is a solution.
Also I'm unsure whether this is a bug in ctypes or in enum or if
they are simply incompatible.

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


Re: Problems with subclassing enum34

2013-06-28 Thread Thomas Heller

Am 28.06.2013 17:25, schrieb Thomas Heller:

Robert Kern:



enum.EnumMeta uses super() in its __new__() implementation but
_ctypes.PyCSimpleType doesn't. Thus, only
_ctypes.PyCSimpleType.__new__() gets a chance to run. Switching the
order of the two might work.



Robert found the problem but I'm unsure if there is a solution.
Also I'm unsure whether this is a bug in ctypes or in enum or if
they are simply incompatible.


I forgot to mention that switching the order of metaclasses didn't work.

Thomas

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


2to6 ?

2012-06-27 Thread Thomas Heller

Is there a tool, similar to 2to3, which converts python2 code
to code using six.py, so that it runs unchanged with python2
*and* python 3?

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


Re: 2to6 ?

2012-07-02 Thread Thomas Heller

Am 27.06.2012 20:06, schrieb Terry Reedy:

On 6/27/2012 10:36 AM, Thomas Heller wrote:

Is there a tool, similar to 2to3, which converts python2 code
to code using six.py, so that it runs unchanged with python2
*and* python 3?


Others have expressed a similar wish, but I do not know that anyone has
actually revised 2to3 to make a 2to6, or how feasible that would be.



Has nobody heard of, or even tried, modernize?

http://pypi.python.org/pypi/modernize


Thomas



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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Thomas Heller

Am 24.01.2013 16:54, schrieb rusi:

[I personally use emacs. It would be sadistic to make that into a
recommendation]


It would be truly sadistic to force a long-time emacs user to any
other editor.

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


Python launcher (PEP 397) and emacs python-mode.el

2013-01-31 Thread Thomas Heller

Has someone managed to patch python-mode.el to use
the PEP 397 python launcher when you hit C-c C-c?

It seems that emacs should parse the shebang line in the edited
python script and pass the corresponding arguments to py.exe.

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


Re: Python launcher (PEP 397) and emacs python-mode.el

2013-01-31 Thread Thomas Heller

Am 31.01.2013 12:05, schrieb Andreas Röhler:

Am 31.01.2013 10:03, schrieb Thomas Heller:

Has someone managed to patch python-mode.el to use
the PEP 397 python launcher when you hit C-c C-c?

It seems that emacs should parse the shebang line in the edited
python script and pass the corresponding arguments to py.exe.



Yes, that's the way python-mode.el acts by default.

AFAIU that launcher is implemented in Python3.3 and should not need any
patch at all.
Should it not work, please file a bug-report at

https://bugs.launchpad.net/python-mode


Well, let me make these remarks:

1. I'm on Windows, using gnu-emacs 24.2.1, and python-mode.el 6.1.0.
I do not understand how the shebang line is used by python-mode.el,
depending on what I write into it either 'python.exe' is started when
I hit C-c C-c, or I get 'Spawning child process: invalid argument'.
The latter occurs most often when the shebang string contains 'jython'.


2. I would like to use the PEP 397 python launcher to start the python
version that is specified in the shebang line.
The python launcher py.exe parses this line when I run 'py script.py',
and then starts the corresponding python interpreter version.
The launcher parses the shebang line by its own rules (see pep397 for
exact details).  One example is this:


#!/usr/bin/python3.1-32
import sys; print(sys.version)


The python launcher starts 'c:\Python31\python.exe -3.1-32 script.py'.

I would like emacs to do the same; however this would require emacs
to do the same shebang line parsing as the launcher does.

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


Re: mmap and bit wise twiddling - Raspberry Pi

2012-05-02 Thread Thomas Heller

Am 02.05.2012 19:40, schrieb Petr Jakes:

Hi,
I am trying to work with HW peripherals on Raspberry Pi
To achieve this, it is necessary read/write some values from/to the
memory directly.

I am looking for some wise way how to organize the bit twiddling.

To set some specific bit, for example, it is necessary:
 - read 4 bytes string representation (I am using mmap)
 - transform it to the corresponding integer (I am using numpy)
 - do some bit masking over this integer
 - transport integer to the string representation (numpy again)
 - write it back to the memory

In other words I mean: is there wise way to create an instrument/
machinery to define Class and then simply define all necessary objects
and set the bit values over object attributes so the whole bit-
twiddling remains under the hood.

say:
LED01 = GPIO(4)  # gpio PIN number 4 is assigned to the LED01 name
(attribute)
LED01.on()
LED01.off()
  or

gpio = GPIO()
LED01 = gpio.pin04
LED01 = 1 # led diode is shining (or gpio pin 4 is set)
LED01 = 0 # led diode is off


I have an abstract BitVector base-class that allows to get/set single
bits or several bits in a convenient way.  You must define concrete
subclasses which define a _value get/set property that actually
updates the byte or word in the hardware.  I use it to access bits
or groups of bits of I2C devices.

You would basically code like this, assuming an 8-bit GPIO port:

class GPIO(BitVector):
def __init__(self, address, value=0xFF, nbits=8):
self.address = address
super(GPIO, self).__init__(value, nbits)
def _get_value(self):
"read an 8-bit value from the hardware as 8-bit integer"
...
def _set_value(self, v):
"write the 8-bit value 'v' to the hardware"
...

then you can do:

gpio = GPIO(0x12345678)

led0 = gpio[4] # bit 4
led0.value = 1 # switch led on
print led0.value # get led status

For multiple bits use this (note that different from standard Python
practices, indexing works inclusive and uses [high_bitnum:low_bitnum]:

port = GPIO(0x12345678)
high_nibble = port[7:4]
print high_nibble.value
low_nibble = port[3:0]
low_nibble.value = 0xF

Thomas
class BitVector(object):
"""BitVector class, represents mutable integers
constricted to a certain range.

Single bits can be get/set by indexing with integers.

Slices can be used to get/set the bits in this range, as an
integer constricted to this range also.

Slices must use [MSB:LSB], and are inclusive.

>>> [x for x in BitVector(0xAA)]
[0, 1, 0, 1, 0, 1, 0, 1]
>>> [x for x in BitVector(0xFF)]
[1, 1, 1, 1, 1, 1, 1, 1]
>>>
>>> bv = BitVector(0)
>>> bv[6:3] = 0xf
>>> [x for x in bv]
[0, 0, 0, 1, 1, 1, 1, 0]
>>> bv[6:3] = -1
Traceback (most recent call last):
  ...
ValueError: value out of allowed range
>>> bv[6:3] = 16
Traceback (most recent call last):
  ...
ValueError: value out of allowed range
>>> hex(bv)
'0x78'
>>> bin(bv)
'0b000'
>>> 
"""
def __init__(self, value=0, nbits=8):
self._nbits = nbits
self._value = value

def __index__(self):
return self._value

def __hex__(self):
return hex(self._value)

def __getitem__(self, index):
if isinstance(index, slice):
return self._getslice(index)
if not 0 <= index < self._nbits:
raise IndexError("invalid index")
return int(bool(self._value & (1 << index)))

@property
def bits(self):
"""
Return some bits as an object that has a .value property.  The
.value property represents the current value of the specied
bits.

b = BitVector().bits[7:0]
b.value = ...
print b.value
"""
class Bits(object):
def __init__(self, bv):
self.bv = bv
def __getitem__(self, index):
class GetSet(object):
def __init__(self, bv):
self.bv = bv
def _get(self):
return self.bv[index]
def _set(self, value):
self.bv[index] = value
value = property(_get, _set)
return GetSet(self.bv)
return Bits(self)

def _getslice(self, index):
if index.step is not None:
raise ValueError("extended slicing not supported")
stop, start = index.stop, index.start
if start <= stop or start < 0 or stop >= self._nbits:
print "START, STOP", start, stop
raise ValueError("invalid slice range")
mask = (1 << (start+1)) - 1
return (self._value & mask) >> stop

def _setslice(self, index, value):
if index.step is not None:
raise ValueError("extended slicing not supported")
stop, start = index.stop, index.start
if start <= stop or start < 0 or stop >= se

Re: mmap and bit wise twiddling - Raspberry Pi

2012-05-02 Thread Thomas Heller

Am 02.05.2012 22:05, schrieb Thomas Heller:

class GPIO(BitVector):
def __init__(self, address, value=0xFF, nbits=8):
self.address = address
super(GPIO, self).__init__(value, nbits)
def _get_value(self):
"read an 8-bit value from the hardware as 8-bit integer"
...
def _set_value(self, v):
"write the 8-bit value 'v' to the hardware"
...


Sorry, forgot to create the property; so please add this
to the class definition:

_value = property(_get_value, _set_value)


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


Re: Problem receiving UDP broadcast packets.

2011-04-20 Thread Thomas Heller

Am 20.04.2011 00:21, schrieb Grant Edwards:

I'm have problems figuring out how to receive UDP broadcast packets on
Linux.

[...]


On the receiving machine, I've used tcpdump to verify that broadcast
packets are being seen and have a destination IP of 255.255.255.255 and
destination MAC of ff:ff:ff:ff:ff:ff

[...]

But, the receiving Python program never sees any packets unless the
_source_ IP address in the packets is on the same subnet as the
receiving machine.  In this test case, the receiving machine has an IP
address of 172.16.12.34/16.  If I change the receiving machine's IP
address to 10.0.0.123, then the receiving program sees the packets.

Even though the destination address is 255.255.255.255, the receiving
machine appears to discard the packets based on the _source_ IP.  Can
anybody provide example Python code for Linux that receives UDP
broadcast packets regardless of their source IP address?

This probably is more of a Linux networking question than a Python
question, but I'm hoping somebody has solved this problem in Python.



You must set the network interface to promiscous mode on the receiving side:

os.system("ifconfig eth0 promisc")

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


Re: List of WindowsError error codes and meanings

2011-05-26 Thread Thomas Heller

Am 20.05.2011 19:56, schrieb Andrew Berg:

This is probably somewhat off-topic, but where would I find a list of
what each error code in WindowsError means? WindowsError is so broad
that it could be difficult to decide what to do in an except clause.
Fortunately, sys.exc_info()[1][0] holds the specific error code, so I
could put in an if...elif...else clause inside the except clause if I
needed to, but I don't know what all the different errors are.


On Windows, you can use ctypes.FormatError(code) to map error codes
to strings:

>>> import ctypes
>>> ctypes.FormatError(32)
'Der Prozess kann nicht auf die Datei zugreifen, da sie von einem 
anderen Prozess verwendet wird.'

>>>

For HRESULT codes, you (unfortunately) have to subtract 2**32-1 from
the error code:

>>> ctypes.FormatError(0x80040005)
Traceback (most recent call last):
  File "", line 1, in 
OverflowError: long int too large to convert to int
>>> ctypes.FormatError(0x80040005 - (2**32-1))
'Kein Cache zum Verarbeiten vorhanden.'
>>>

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


Re: Open PDF

2005-09-23 Thread Thomas Heller
"Martin Miller" <[EMAIL PROTECTED]> writes:

> IMHO, the fact that there is no way to wait for the application to
> finish is major deficiency with os.startfile() -- and why I often
> cannot use it instead of other techniques [such as the much more
> involved but limited os.spawnv() function].
>
> I don't if if this is just a limitation of the implementation in the
> Python os module or one with the underlying OS (Windoze) -- I suspect
> the latter.

os.startfile calls ShellExecute.  AFAIK, if ShellExecuteEx were used,
this could retrieve a process handle which you could wait for os so.

With ctypes you can easily experiment with this kind of stuff.  Another
interesting feature, imo, is the 'verb' that you can pass to these
functions. With this, you could for example specify 'print' to print the
file instead of just opening it.

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


Re: Getting tired with py2exe

2005-09-26 Thread Thomas Heller
Bugs <[EMAIL PROTECTED]> writes:

> Any luck on finding anyone to take over py2exe development Thomas?
> It's a GREAT project and would be a shame to see it fall into
> obsolescence.

No, nobody stepped up (yet).

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


Re: Getting tired with py2exe

2005-09-26 Thread Thomas Heller
> Thomas Heller wrote:
>> Bugs <[EMAIL PROTECTED]> writes:
>>
>>>Any luck on finding anyone to take over py2exe development Thomas?
>>>It's a GREAT project and would be a shame to see it fall into
>>>obsolescence.
>> No, nobody stepped up (yet).
>> Thomas

Bugs <[EMAIL PROTECTED]> writes:

> What do you think of the idea of putting both py2exe AND py2app under
> the same umbrella?  I don't know what the status of py2app is or who
> maintains it but I was thinking that it would be ideal if the 2
> utilities could share code, ideas, protocols, etc.  Seems like this
> synergy and consistency would be very beneficial.  Perhaps then a
> Linux version could be developed with an identical inferface.

That's not a bad idea.  Philip Eby even suggested to put something like
py2exe's modulefinder (well, it's really Python's) and py2app's
modulegraph into his setuptools package - although I didn't respond at
that time.

Anyway, these are changes that I don't want to do myself.  Whoever wants
to start that feel free...

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


Re: Set up Windows environment with python

2005-09-29 Thread Thomas Heller
"Jim" <[EMAIL PROTECTED]> writes:

> My company resells windows machines, and we install our software, and
> do a bunch of customization to make sure that all the desktop settings
> are optimal...  we adjust the screen resolution, color depth, and
> referesh rate,  remove shadows from menus and the mouse pointer, set
> the power management options, disable the screensaver, etc... (very
> long list)
>
> I've started doing most of what I want with ctypes:
>
> def disableShadows():
> # constants taken from WinUser.h in the PlatformSDK
> SPI_SETCURSORSHADOW = 0x101B
> rv =
> ctypes.windll.user32.SystemParametersInfoA(SPI_SETCURSORSHADOW, 0,
> False, win32con.SPIF_SENDWININICHANGE)
>
> # remove shadows from menus
> SPI_SETDROPSHADOW = 0x1025
> rv = ctypes.windll.user32.SystemParametersInfoA(SPI_SETDROPSHADOW,
> 0, False, win32con.SPIF_SENDWININICHANGE)
>
> But I'm finding that none of the changes seem to be permanent.  I'm
> wondering if I need to start changing the current Explorer theme
> information instead, or go right to the registry and start changing
> values.
>
> Desktop wallpaper changes work, but they aren't permanent... rebooting
> restores the previous desktop wallpaper.
>
> Does anyone have any experience with this sort of system preperation
> scripting?

>From looking at the MSDN docs, it seems you have to add
SPIF_UPDATEINIFILE (Writes the new system-wide parameter setting to the
user profile) to the last argument.

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


Re: PyWin SendMessage

2005-09-29 Thread Thomas Heller
"g.franzkowiak" <[EMAIL PROTECTED]> writes:

> Hello everybody,
>
> I've tryed to use an interprocess communication via
> SendMessage on Windows.
> Unfortunately, nothing goes on
>
> #
> #! /usr/bin/env python
>
> import win32api, win32ui, win32con
> import struct, array
>
> """
> typedef struct tagCOPYDATASTRUCT {  // cds
> DWORD dwData;
> DWORD cbData;
> PVOID lpData;
> } COPYDATASTRUCT;
> """
>
> def packCopyData(nNum, sString):
> int_buffer  = array.array("L",[nNum])
> char_buffer = array.array('c', sString)
> int_buffer_address  = int_buffer.buffer_info()[0]
> char_buffer_address = char_buffer.buffer_info()[0]
> char_buffer_size= char_buffer.buffer_info()[1]
> copy_struct = struct.pack("pLp",# dword*, dword, char*
>   int_buffer_address,
>   char_buffer_size,
>   char_buffer)
> return copy_struct

After packCopyData(...) returns, the arrays are destroyed, which will
probably void their contents.  You must keep them alive until you don't
need the COPYDATASTRUCT instance any longer.  For this kind of stuff,
ctypes may be easier to use than pywin32.

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


Re: PyWin SendMessage

2005-09-29 Thread Thomas Heller
"g.franzkowiak" <[EMAIL PROTECTED]> writes:

> Thomas Heller schrieb:
>> "g.franzkowiak" <[EMAIL PROTECTED]> writes:
>> 
>> 
>>>Hello everybody,
>>>
>>>I've tryed to use an interprocess communication via
>>>SendMessage on Windows.
>>>Unfortunately, nothing goes on
>>>
>>>#
>>>#! /usr/bin/env python
>>>
>>>import win32api, win32ui, win32con
>>>import struct, array
>>>
>>>"""
>>>typedef struct tagCOPYDATASTRUCT {  // cds
>>>DWORD dwData;
>>>DWORD cbData;
>>>PVOID lpData;
>>>} COPYDATASTRUCT;
>>>"""
>>>
>>>def packCopyData(nNum, sString):
>>>int_buffer  = array.array("L",[nNum])
>>>char_buffer = array.array('c', sString)
>>>int_buffer_address  = int_buffer.buffer_info()[0]
>>>char_buffer_address = char_buffer.buffer_info()[0]
>>>char_buffer_size= char_buffer.buffer_info()[1]
>>>copy_struct = struct.pack("pLp",# dword*, dword, char*
>>>  int_buffer_address,
>>>  char_buffer_size,
>>>  char_buffer)
>>>return copy_struct
>> 
>> 
>> After packCopyData(...) returns, the arrays are destroyed, which will
>> probably void their contents.  You must keep them alive until you don't
>> need the COPYDATASTRUCT instance any longer.  For this kind of stuff,
>> ctypes may be easier to use than pywin32.
>> 
>> Thomas
>
> Hmm, have read something in <<http://aspn.activestate.com>>
> and the script changed to this:
>
> #-
> #! /usr/bin/env python
>
> import win32api, win32ui, win32con, win32gui
> import struct, array
> from ctypes import *
>
> """
> typedef struct tagCOPYDATASTRUCT {  // cds
> DWORD dwData;
> DWORD cbData;
> PVOID lpData;
> } COPYDATASTRUCT;
> """
>
> class COPYDATATYPE(Structure):
> _fields_ = [("nNum",   c_ulong),
> ("szData", c_char_p)]
>
> class COPYDATASTRUCT(Structure):
> _fields_ = [("dwData", c_ulong),
> ("cbData", c_ulong),
> ("lpData", POINTER(COPYDATATYPE))]
>
> # get the window handle
> hwnd = win32ui.FindWindow(None, "target window")
>
> # print just for fun
> # ##print hwnd
>
> # prepare copydata structure for sending data
> cpyData = COPYDATATYPE(1, '1')
> cds = COPYDATASTRUCT(c_ulong(1),
>  c_ulong(sizeof(cpyData)),
>  pointer(cpyData))
>
> # try to send a message
> win32api.SendMessage(hwnd,
>  win32con.WM_COPYDATA,
>  0,
>  pointer(cds))
>
> #-
> and the message for the last line is:
> ==> TypeError: an integer is required"
>
> This message comes with "pointer(cds)" and with "addressof(cds)"

That error refers to the first argument - win32ui.FindWindow returns a
PyCWnd object, which is not accepted by win32api.SendMessage.
Changing this brings you one step further.  win32api.SendMessage accepts
an integer for the last element, so addressof(cds) should work now.

win32gui.SendMessage is more tolerant in what it accepts as 4th
argument, according to the error message you get when you try it it
expects a string, a buffer, or an integer.  So you could use addressof()
or pointer(), what you like best.

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


How to prevent logging warning?

2005-10-05 Thread Thomas Heller
I'm about to add some logging calls to a library I have.  How can I
prevent that the script that uses the library prints
'No handlers could be found for logger "comtypes.client"' when the
script runs?

I would like to setup the logging so that there is no logging when
nothing is configured, and no warning messages are printed.

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


Re: How to prevent logging warning?

2005-10-05 Thread Thomas Heller
> Thomas Heller wrote:
>> I'm about to add some logging calls to a library I have.  How can I
>> prevent that the script that uses the library prints
>> 'No handlers could be found for logger "comtypes.client"' when the
>> script runs?
>> I would like to setup the logging so that there is no logging when
>> nothing is configured, and no warning messages are printed.

Maksim Kasimov <[EMAIL PROTECTED]> writes:

> may be this you will find usefull:
>
> def getLog(logName, fileName = None):
>
>  if fileName:
>  hdl = logging.FileHandler(fileName)
>  else:
>  hdl = logging.StreamHandler()
>
>  fmt = 
> logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s")
>  hdl.setFormatter(fmt)
>  log = logging.getLogger(logName)
>  log.addHandler(hdl)
>
>  return log

Not really - I know how to set up handlers, but I think it should be
optional. Assume I have

  log = logging.getLogger("comtypes.client")

and later

  log.warn("foo bar")

in the library code.

If I use the library an my script, I get the warning that I mentioned
above.  I want the script by default to be agnostic about the libraries
logging.  When I want to see the log messages, I can always do

  logging.basicConfig()

in the script to see the log messages.

I get the behaviour that I want when I add a 'NULL' handler in the
library, but is this really how logging is intended to be used?


log = logging.getLogger("comtypes.client")

class NULLHandler(logging.Handler):
def emit(self, *args):
pass

log.addHandler(NULLHandler())


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


Re: py2exe has a new maintainer

2005-10-06 Thread Thomas Heller
"Jimmy Retzlaff" <[EMAIL PROTECTED]> writes:

> I am taking over the maintenance and support of py2exe from Thomas
> Heller. As he announced a few weeks ago he is looking to focus on other
> things. py2exe has been very useful to me over the years and I look
> forward to keeping it every bit as useful in the future.

Jimmy, I'm very happy that you take over the py2exe package maintainace
and wish you all good luck with it.  Open source how it should work!

Thanks again,

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


Re: How to prevent logging warning?

2005-10-06 Thread Thomas Heller
"Vinay Sajip" <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>
>> I get the behaviour that I want when I add a 'NULL' handler in the
>> library, but is this really how logging is intended to be used?
>>
>
> The reason for the one-off message is that without it, a
> misconfiguration or a failure to configure any handlers is notified to
> a user (who is possibly not used to the logging package). I'm not sure
> which is more annoying - a one-off message which occurs when no
> handlers are configured and yet events are logged, or complete silence
> from logging when something is misconfigured, and not giving any
> feedback on what's wrong? (It's a rhetorical question - the answer is
> of course quite subjective).

I do *not* think 'no handler' is a misconfiguration. Is it possible to
differentiate between a misconfiguration and 'no configuration'?

> Certainly, I could change things so that e.g. the error is suppressed
> when logging.raiseExceptions is set to 0 (typically for production
> use).

That would be fine.  But there are also other ways - you could, for
example, print the warning only when __debug__ is False.  And you could
use the warnings module instead of blindly printing to stderr, this way
it could also be filtered out.

BTW: Since I have your attention now, is the graphical utility to
configure the logging.conf file still available somewhere, and
compatible with the current logging package (with 'current' I mean
the one included with Python 2.3.5)?

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


Re: Absolultely confused...

2005-10-06 Thread Thomas Heller
Jeremy Moles <[EMAIL PROTECTED]> writes:

> So, here is my relevant code:
>
>   PyArg_ParseTuple(args, "O!", &PyType_vector3d, &arg1)
>
> And here ismy error message:
>
>   argument 1 must be pylf.core.vector3d, not pylf.core.vector3d
>
> I know PyType_vector3d "works" (as I can use them in the interpreter all
> day long), and I know I'm passing a pylf.core.vector3d (well, apparently
> not...)
>
> I've spent hours and hours on this and I'm finally just giving up and
> asking. I've tried everything to get my program to verify that arg1 is
> really a PyType_vector3d, but to no avail.
>
> If I take out the "!" in the format string and just use "O", I can at
> least get past PyArg_ParseTuple. Then I try something like...
>
>   PyObject_TypeCheck(arg1, &PyType_vector3d)
>
> Which also fails, but I know for a fact that arg1's PyObject_Repr is
> what it should be. (pylf.core.vector3d)
>
> I guess my question is: what in the world could be causing this to fail?
> It seems like I'm just not able to use ParseType or BuildValue to create
> objects of my own type.
>
> I know I haven't provided a lot of information, but does anyone have any
> ideas or where I should start looking?

Can it be that you have TWO instances of the pylf.core.vector3d object?
Debugging should reveal it...

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


Re: Absolultely confused...

2005-10-06 Thread Thomas Heller
Jeremy Moles <[EMAIL PROTECTED]> writes:

> Thanks for the reply. :)
>
> I may be missing something critical here, but I don't exactly grok what
> you're saying; how is it even possible to have two instances of
> PyType_vector3d? It is (like all the examples show and all the extension
> modules I've done in the past) a static structure declared and assigned
> to all at once, only once.
>
> Am I misunderstanding the point? :)
>
> /me ducks
>
> On Thu, 2005-10-06 at 16:26 +0200, Thomas Heller wrote:
>> Jeremy Moles <[EMAIL PROTECTED]> writes:
>> 
>> > So, here is my relevant code:
>> >
>> >PyArg_ParseTuple(args, "O!", &PyType_vector3d, &arg1)
>> >
>> > And here ismy error message:
>> >
>> >argument 1 must be pylf.core.vector3d, not pylf.core.vector3d
>> >

The only reason that I can think of for this error message is that the
type of the argument is something that has a repr of
'pylf.core.vector3d', but the type object is not the same as your
'PyType_vector3d' pointer.  As I said, use a source debugger or some
other way to find out, or use a debug build of Python and step through
the PyArg_ParseTuple code to find out why the call fails.

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


Re: Moving to Win XP as a Python developer

2005-10-14 Thread Thomas Heller
Scott David Daniels <[EMAIL PROTECTED]> writes:

> Christian Stapfer wrote:
>> "John J. Lee" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>
>>>cmd.exe can be made bearable
>>>
>>>0. Make a shortcut to cmd.exe, stick it somewhere get-at-able,
>>>  eg. quick launch toolbar

> I put it on my desktop.  Once having made it, fiddle with
> "Start in" to be your favorite python code directory (that is
> why I usually have several), and append a space and /D /X /F:ON
> to the "Target" line.

I have an elisp function bound to a key in XEmacs that starts cmd in the
directory where the current buffer is.  IMO this is very convenient.  To
access explorer from that command prompt (in the rare cases that I need
it) I use 'start .'.

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


Re: Moving to Win XP as a Python developer

2005-10-14 Thread Thomas Heller
Trent Mick <[EMAIL PROTECTED]> writes:

> [Thomas Heller wrote]
>> I have an elisp function bound to a key in XEmacs that starts cmd in the
>> directory where the current buffer is.  IMO this is very convenient.  To
>> access explorer from that command prompt (in the rare cases that I need
>> it) I use 'start .'.
>
> I kind of have the same thing with Dave's Quick Search Deskbar
> (http://www.dqsd.net/) and my little "go" script
> (http://trentm.com/projects/go/). The keystrokes to open a cmd.exe shell
> in my "src" folder is down to:
>
> # to focus in the Quick Search Deskbar textbox
> go src
>
> or to open Explorer in that dir:
>
> go -o src 
>
> or in another "tagged" dir:
>
> go ~   # open in my home dir
>
> DQSD is a fantastic tool for speeding up launching other things, too:
> mainly Google searches.

Since we are speaking of tricks here:

I have other keys defined in XEmacs for context-sensitive help on the
word under the cursor in Python's htmlhelp file (F2), and the MSDN
library (F6).  Kind of a hack which needs a small compiled C program,
though, since I did not know how to call the needed apis with elisp.

But, what I'm still missing is a function that finds and opens a Python
module.

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


__getattr__, __setattr__

2005-10-20 Thread Thomas Heller
Just wondering about this behaviour, why is it this way?

Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> object.__setattr__

>>> object.__getattr__
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: type object 'object' has no attribute '__getattr__'
>>>


Thanks,

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


Re: __getattr__, __setattr__

2005-10-20 Thread Thomas Heller
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> for new style classes  __getattribute__ is defined, see eg.
> http://www.python.org/2.2.3/descrintro.html

Steve Holden <[EMAIL PROTECTED]> writes:

>  >>> object.__getattribute__
> 
>
> Ring any bells?

Yes, of course.  Thanks ;-)

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


Re: p2exe using wine/cxoffice

2005-10-26 Thread Thomas Heller
Jon Perez <[EMAIL PROTECTED]> writes:

> James Stroud wrote:
>
>> "better". The only reason I want this functionality is to make my software
>> available to windoze users--despite their unfortunate ignorance, they are
>> people too. That's what I always say.
>
> Actually, I think it's many unix/linux users who are ignorant of just
> how nice, stable and productive Windows can be as a desktop environment.
>
> ... and I really mean that.  ;-).

I was waiting for someone to say that.

+1.

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


Re: Windows vs Linux

2005-10-26 Thread Thomas Heller
"Tim Golden" <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED]
>> But command line in Windows is in no way in the same
>> league as *nix shell. Use  for command completion and up/down
>> arrow or  to search for history.
>
> [darren kirby]
>> Try ctrl-r in bash, then type your first few letters...
>
> Thanks to both of you. But that much I already knew. It's not
> that I have *no* knowledge about readline: I did at least
> read the manuals when I got stuck! But as far as I can tell
> from my experience and from the docs -- and I'm not near a 
> Linux box at the mo -- having used ctrl-r to recall line x 
> in the history, you can't just down-arrow to recall x+1, x+2 etc. 
> Or can you?

I don't know.  When I discovered this I uninstalled the (windows)
readline module from my Python installation.

> (Sorry guys; I realise this is more stuff for comp.os.linux or
> comp.commandlineshells.bash or whatever it's called. But if
> someone *did* know the answer, I'd be really happy!)

;-)

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


Re: Windows vs Linux [was: p2exe using wine/cxoffice]

2005-10-26 Thread Thomas Heller
"Tim Golden" <[EMAIL PROTECTED]> writes:

> [Sybren Stuvel]

>> You can't resize it horizontally
>
> Well, peculiarly, you can do this (as you're probably aware) from
> the Properties menu and it'll work immediately, albeit without
> advising the running programs that it's resized, so only new
> lines will take advantage of the new width. Now, why they didn't
> let you do the same thing by grabbing the border and pulling, I
> don't know!

FYI, if you don't know this already: You also can resize the console without
going through the properties menu with 'mode con cols=... lines=...'.

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


Re: How can I package a python script and modules into a single script?

2005-11-03 Thread Thomas Heller
"Noah" <[EMAIL PROTECTED]> writes:

> I would like to package my main script and all the
> modules it imports into a single script that will
> run just as the collection would. It should not
> need to package standard Python lib modules -- just
> my local modules. This is not the same question
> that would be answered with py2exe or py2app. I
> don't need to package the script into a binary
> along with Python. I expect Python to be installed.
> I also don't want to use distutils to install the
> script. The script will always run on Unix.
>
> I thought that there might be some way to run a
> script package from a tar file. One way would be to
> have the package script  untar itself into a temp
> directory; run the main script; then  delete the
> temporary package directory when done. That sounds
> clunky and prone to leave around trash if someone
> does a 'kill -9'. However, this might be an
> acceptable compromise. I'm sure that I've seen a
> tool around like this, but I can't find it anymore.

Wasn't this named 'squeeze'?

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


Re: Can bdist_wininst built installer require minimum python version?

2005-11-23 Thread Thomas Heller
"SPE - Stani's Python Editor" <[EMAIL PROTECTED]> writes:

> A SPE user reported this:
>
> http://developer.berlios.de/bugs/?func=detailbug&bug_id=4878&group_id=4161
>>SPE Installer gives option for installing for python22 (i have
>>python22, 23, and 24 installed) I thought that spe requried 2.3+ (ie
>>it should allow for 23, 24 but not 22).
>
> Is there anyway that SPE can require a minimum version (eg python 23)?

No.  Although you could build installers requiring a specific Python
version, even if only pure Python modules are included, with the
--target-version command line switch.  Of course, then you have to build
separate installers for each version.

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


Re: Reading binary data

2005-11-23 Thread Thomas Heller
"David M" <[EMAIL PROTECTED]> writes:

> Thanks but the C Struct describing the data doesn't match up with the
> list on the module-struct page.
>
> this is the acct.h file
[...]

Tooting my ctypes horn (sorry for that):

[EMAIL PROTECTED]:~/ctypes> locate acct.h
/usr/include/linux/acct.h
/usr/include/sys/acct.h
[EMAIL PROTECTED]:~/ctypes> python ctypes/wrap/h2xml.py sys/acct.h -o acct.xml
creating xml output file ...
running: gccxml /tmp/tmpSWogJs.cpp -fxml=acct.xml
[EMAIL PROTECTED]:~/ctypes> python ctypes/wrap/xml2py.py acct.xml -o acct.py  
[EMAIL PROTECTED]:~/ctypes> python
Python 2.4.1a0 (#1, Oct 23 2004, 15:48:15) 
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import acct
>>> acct.acct

>>> acct.AFORK
1
>>> acct.ASU
2
>>> acct.acct.ac_comm

>>> acct.acct.ac_utime

>>> from ctypes import sizeof
>>> sizeof(acct.acct) 
64
>>> acct.acct.ac_flag

>>> 
[EMAIL PROTECTED]:~/ctypes> 

But it won't help you to decode/encode the comp_t fields into floats.
Note that the h2xml.py script requires gccxml.

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


Re: Distutils postinstall script: useless?

2005-11-30 Thread Thomas Heller
Mardy <[EMAIL PROTECTED]> writes:

> Le die Wed, 30 Nov 2005 15:46:43 +, Mardy ha scribite:
>>   the bdist_wininst command of distutils allows me to specify a script to
>> be executed at the end of the installation. That's great, but how can I
>> know the installation path from inside the script?
>
> Answering to myself, sys.prefix combined with the dictionary
> INSTALL_SCHEMES from distutils.commands.install might do the work.

See also the functions in distutils.sysconfig.

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


Re: ANN: Louie-1.0b2 - Signal dispatching mechanism

2005-12-01 Thread Thomas Heller
[EMAIL PROTECTED] writes:

> Louie 1.0b2 is available:
>
> 
>
> Louie provides Python programmers with a straightforward way to
> dispatch signals between objects in a wide variety of contexts. It is
> based on PyDispatcher_, which in turn was based on a highly-rated
> recipe_ in the Python Cookbook.
>
> .. _PyDispatcher: http://pydispatcher.sf.net/
>
> .. _recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87056
>
>
> For more information, visit the Louie project site:
> 
>
> Patrick K. O'Brien and contributors
> <[EMAIL PROTECTED]>

What is the difference between PyDispatcher and Louie?
(I'm still using a hacked version of the original cookbook recipe...)

Thanks,

Thomas


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


Re: ANN: Louie-1.0b2 - Signal dispatching mechanism

2005-12-02 Thread Thomas Heller
"Pat" <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>>
>> What is the difference between PyDispatcher and Louie?
>> (I'm still using a hacked version of the original cookbook recipe...)
>
> Not too much at this point, but the general differences are listed on
> this page:
>
> http://louie.berlios.de/changes.html
>
> Matt and I plan to experiment with other changes for Nufox, PyQt,
> Schevo and other things that we are working on.

Ok, so I won't need it (yet).

Thanks (and also for the original dispatcher module, of which I'm a very
happy user).

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


Re: How to wake up the jython list moderator

2005-12-06 Thread Thomas Heller
"Anton Vredegoor" <[EMAIL PROTECTED]> writes:

> I'm trying to post messages to the jython mailing list via gmane. I
> this possible? I've got all kinds of messages confirming that I exist
> and that my message has arrived and will be either approved or rejected
> with an explanation, but since then nothing but silence and my message
> doesn't show up either.

That's the behaviour of most mailing lists on gmane.org that require
membership to accept posts. The last message you got did probably say
that the list admin would have to review the message and decide if it is
posted or not.

The easiest solution for this is to join the mailing list (with the
email address that you use to post), disable list delivery, and repost
your message via gmane.

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


Re: Proposal: Inline Import

2005-12-10 Thread Thomas Heller
Shane Hathaway <[EMAIL PROTECTED]> writes:

> Xavier Morel wrote:
>> Shane Hathaway wrote:
>>
>>>Thoughts?
>>  >>> import re; name_expr = re.compile('[a-zA-Z]+')
>>  >>> name_expr
>> <_sre.SRE_Pattern object at 0x00F9D338>
>>  >>>
>> the import statement can be called anywhere in the code, why would
>> you add strange syntactic sugar that doesn't actually bring anything?
>
> That syntax is verbose and avoided by most coders because of the speed
> penalty.  It doesn't replace the idiom of importing everything at the
> top of the module.
>
> What's really got me down is the level of effort required to move code
> between modules.  After I cut 100 lines from a 500 line module and
> paste them to a different 500 line module, I have to examine every
> import in both modules as well as examine the code I moved for missing
> imports. And I still miss a lot of cases.  My test suite catches a lot
> of the mistakes, but it can't catch everything.

I understand this use case.

You can use pychecker to find NameErrors without actually running the
code.  Unfortunately, it doesn't (at least not always) find imports
which are not needed.

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread Thomas Heller
Skip Montanaro <[EMAIL PROTECTED]> writes:

> michele> BTW what's the difference between .encode and .decode ?
>
> I started to answer, then got confused when I read the docstrings for
> unicode.encode and unicode.decode:
>
> >>> help(u"\xe4".decode)
> Help on built-in function decode:
>
> decode(...)
> S.decode([encoding[,errors]]) -> string or unicode
>
> Decodes S using the codec registered for encoding. encoding defaults
> to the default encoding. errors may be given to set a different error
> handling scheme. Default is 'strict' meaning that encoding errors 
> raise
> a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
> as well as any other name registerd with codecs.register_error that is
> able to handle UnicodeDecodeErrors.
>
> >>> help(u"\xe4".encode)
> Help on built-in function encode:
>
> encode(...)
> S.encode([encoding[,errors]]) -> string or unicode
>
> Encodes S using the codec registered for encoding. encoding defaults
> to the default encoding. errors may be given to set a different error
> handling scheme. Default is 'strict' meaning that encoding errors 
> raise
> a UnicodeEncodeError. Other possible values are 'ignore', 'replace' 
> and
> 'xmlcharrefreplace' as well as any other name registered with
> codecs.register_error that can handle UnicodeEncodeErrors.
>
> It probably makes sense to one who knows, but for the feeble-minded like
> myself, they seem about the same.

It seems also the error messages aren't too helpful:

>>> "ä".encode("latin-1")
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal 
not in range(128)
>>>

Hm, why does the 'encode' call complain about decoding?

Why do string objects have an encode method, and why do unicode objects
have a decode method, and what does this error message want to tell me:

>>> u"ä".decode("latin-1")
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: 
ordinal not in range(128)
>>>

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread Thomas Heller
Max M <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>
>> It seems also the error messages aren't too helpful:
>>
>>>>>"ä".encode("latin-1")
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: 
>> ordinal not in range(128)
>> Hm, why does the 'encode' call complain about decoding?
>
> Because it tries to print it out to your console and fail. While
> writing to the console it tries to convert to ascii.

Wrong, same error without trying to print something:

>>> x = "ä".encode("latin-1")
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal 
not in range(128)
>>>

>
> Beside, you should write:
>
> u"ä".encode("latin-1") to get a latin-1 encoded string.

I know, but the question was: why does a unicode string has a encode
method, and why does it complain about decoding (which has already been
answered in the meantime).

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


Re: [Hack] Import binary extensions from zipfiles, windows only

2005-01-04 Thread Thomas Heller
"PJDM" <[EMAIL PROTECTED]> writes:

> I'm trying to make ZopeX3 start faster by zipping up the "zope"
> directory. (Because this will be stored on a CD, having less data to
> read will make it quicker to start.)
>
> The standard python zipimporter won't work with the ZopeX3 .pyd files,
> so zipextimporter came along at just the right time. However, it
> doesn't seem to work for me (Python 2.3.4 (#53, May 25 2004, 21:17:02)
> [MSC v.1200 32 bit (Intel)] on win32, Windows XP SP2).
>
> Sample script:
> 
> import zipextimporter
> zipextimporter.install()
>
> import sys
> print 'Hooks:\n', sys.path_hooks
>
> sys.path.append(r'C:\tmp\zope.zip')
> print 'Path:\n', sys.path
>
> # Try an innocuous import first to make sure we have the path correct.
> import zope.server
> print 'Server file:\n', zope.server.__file__
>
> # Now try a .pyd import.
> import zope.thread._zope_thread
> print 'Thread file:\n', zope.thread._zope_thread.__file__
> 
>
> Output:
> 
> Hooks:
> [,  'zipimport.zipimporter'>]
> Path:
> ['C:\\tmp', 'C:\\WINDOWS\\system32\\python23.zip', 'C:\\tmp',
> 'C:\\opt\\Python23\\DLLs', 'C:\\opt\\Python23\\lib',
> 'C:\\opt\\Python23\\lib\\plat-win', 'C:\\opt\\Python23\\lib\\lib-tk',
> 'C:\\opt\\Python23', 'C:\\opt\\Python23\\lib\\site-packages',
> 'C:\\tmp\\zope.zip']
> Server file:
> C:\tmp\zope.zip\zope\server\__init__.py
> Traceback (most recent call last):
> File "zei.py", line 15, in ?
> import zope.thread._zope_thread
> ImportError: No module named _zope_thread
> 
>
> The zope.zip file contains zope.thread:
> 
> $ unzip -l zope.zip |grep zope/thread
> 0  11-08-04 11:00   zope/thread/
> 0  07-03-04 04:34   zope/thread/DEPENDENCIES.cfg
> 65  07-28-04 22:52   zope/thread/SETUP.cfg
> 994  07-03-04 04:34   zope/thread/tests.py
> 748  11-08-04 11:00   zope/thread/tests.pyc
> 748  11-08-04 11:00   zope/thread/tests.pyo
> 20480  11-07-04 00:54   zope/thread/_zope_thread.pyd
> 7838  08-17-04 17:20   zope/thread/__init__.py
> 7808  11-08-04 11:00   zope/thread/__init__.pyc
> 7808  11-08-04 11:00   zope/thread/__init__.pyo
> 

zipextimporter, as published, doesn't handle extensions in packages.
The patch I attached at the end, may fix this - I tested it with PIL.

It may work with zope, or may not - depends on how the extensions are
structured.  If there are extensions/pyds that link to other
extensions/pyds, then it will most certainly not work.

If it doesn't work, you could still try the py2exe approach:
py2exe bundles the .py modules in a zip file, and also inserts loaders
for extensions into the zip file.  The loaders load the .pyd extensions
from the file system.

Thomas


Index: zipextimporter.py
===
RCS file: /cvsroot/py2exe/py2exe/hacks/memimp/zipextimporter.py,v
retrieving revision 1.2
diff -c -r1.2 zipextimporter.py
*** zipextimporter.py   16 Dec 2004 09:29:42 -  1.2
--- zipextimporter.py   4 Jan 2005 20:08:08 -
***
*** 50,55 
--- 50,56 
  if result:
  return result
  
+ fullname = fullname.replace(".", "\\")
  for s in self._suffixes:
  if (fullname + s) in self._files:
  return self
***
*** 60,72 
  return zipimport.zipimporter.load_module(self, fullname)
  except zipimport.ZipImportError:
  pass
  for s in self._suffixes:
  path = fullname + s
  if path in self._files:
  # XXX should check sys.modules first ? See PEP302 on reload
  # XXX maybe in C code...
  code = self.get_data(path)
! mod = _memimporter.import_module(code, "init" + fullname)
  mod.__file__ = "%s\\%s" % (self.archive, path)
  mod.__loader__ = self
  if _memimporter.get_verbose_flag():
--- 61,75 
  return zipimport.zipimporter.load_module(self, fullname)
  except zipimport.ZipImportError:
  pass
+ initname = fullname.split(".")[-1]
+ fullname = fullname.replace(".", "\\")
  for s in self._suffixes:
  path = fullname + s
  if path in self._files:
  # XXX should check sys.modules first ? See PEP302 on reload
  # XXX maybe in C code...
  code = self.get_data(path)
! mod = _memimporter.import_module(code, "init" + initname)
  mod.__file__ = "%s\\%s" % (self.archive, path)
  mod.__loader__ = self
  if _memimporter.get_verbose_flag():

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


Re: Is there any way/where to subscribe for automated PEP status emails?

2005-01-05 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> I find that threads sometimes mention PEPs that I wasn't aware of,
> or that an interesting one has been updated without my noticing.
>
> I should perhaps check the PEP site more regularly, but ISTM it shouldn't
> be that hard to implement an automated notification of PEP status changes
> by email. A cron job could just monitor the PEP source directory and
> watch for new files and last-mod changes, for starters. Maybe that would
> be sufficient, without going into classifying the changes in more detail.
>
> Subscription/unsubscription could be like an ordinary read-only mail list.
> You could just bounce replies with some advice as to where to go ;-)

You could probably subscribe to python-checkins, and filter it.
Or read it via gmane.

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


Re: Is there any way/where to subscribe for automated PEP status emails?

2005-01-06 Thread Thomas Heller
Nick Coghlan <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>> You could probably subscribe to python-checkins, and filter it.
>> Or read it via gmane.
>
> Hmm - can SF be used to setup a mailing list just for checkins to a
> single directory in the source tree?

Yes.  You should suggest this on python-dev.

> If so, that would seem to be an easy way to provide a
> python-pep-updates mailing list.
>
> Cheers,
> Nick.

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


appending data to an xml file

2005-01-11 Thread Thomas Heller
I want to append/insert additional data to an xml file.

Context: I use gccxml to parse C header files. gccxml creates an xml
file containing all the definitions from the header files.  The xml
files may be somewhat largish, for 'windows.h' it has more than 5 MB.

Since the xml does not contain #define statements, I want to run gccxml
again with the --preprocess and -dM flags, which dumps out the #define'd
symbols.

I want this information also to be in the same file, but simply
appending it to the xml smells hackish, and I don't know if the latter
xml parsing stage can get this additional data with an error handler, or
somehow else.  Maybe I can find the end of the xml data myself, before
giving it to the sax parser.

Better, imo, would be to add the dumped info into a proper xml tag, and
inject it into the original file.  Is that (efficiently) possible?

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


Re: Windows GUIs from Python

2005-01-11 Thread Thomas Heller
Luke Skywalker <[EMAIL PROTECTED]> writes:

> On Tue, 11 Jan 2005 12:55:42 -0600, Doug Holton <[EMAIL PROTECTED]> wrote:
>>You might also be interested in PyGUI although it doesn't have a native 
>>Windows implementation yet: 
>>http://nz.cosc.canterbury.ac.nz/~greg/python_gui/
>
> Generally speaking, appart from MFC-style programming with Python32,
> what are the non-alpha alternatives to write purely Windows apps in
> Python today, ie. without the weight of extra bagage like wxWidgets? 
>
> I'm not looking at fancy options, since the apps I write would be fine
> with just the core Windows widgets along with a few add-ons like a
> grid and the extended Win95 widgets.

Well, venster.  Although it is most certainly alpha.  But with some
work...

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


Re: from __future__ import decorators

2005-01-13 Thread Thomas Heller
Jacek Generowicz <[EMAIL PROTECTED]> writes:

> I have some code, which makes copious use of the @decorator syntax
> which was introduced in Python2.4. Now I find myself in a situation
> where I have to run the code under Python 2.3. However, I would like
> to keep developing the code with the new syntax.
>
> How could I best automate the process of making the syntax digestible
> by Python2.3 ?

The only way that I know of is this, although you have to rewrite your
code somewhat:

http://dirtsimple.org/2004/11/using-24-decorators-with-22-and-23.html

Thomas

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


Re: MemoryError with parser.suite and wrong encoding declaration

2005-01-18 Thread Thomas Heller
Sylvain Thenault <[EMAIL PROTECTED]> writes:

> Hi there !
> I've noticed the following problem with python >= 2.3 (actually 2.3.4 and
> 2.4):
>
> [EMAIL PROTECTED]:test$ python
> Python 2.3.4 (#2, Sep 24 2004, 08:39:09)
> [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import parser
 parser.suite('# -*- coding: IBO-8859-1 -*-')
> Traceback (most recent call last):
>   File "", line 1, in ?
> MemoryError
 parser.suite('# -*- coding: ISO-8859-1 -*-')
> 
>
> Shouldn't parser.suite just ignore the wrong encoding declaration, or at
> least raise a more appropriate exception. IMHO the first solution
> would be better, since that's the behaviour of the (C) python interpreter.

Ignore the wrong declaration?  All Python's that I have (on windows,
at least) raise a SyntaxError:

  File "x.py", line 1
SyntaxError: 'unknown encoding: IBO-8859-1'

See also:

http://www.python.org/sf/979739

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


Re: Installer made with bdist_wininst segfaulting...

2005-01-25 Thread Thomas Heller
Fernando Perez <[EMAIL PROTECTED]> writes:

> Hi all,
>
> I am seeking advice/help from those with more win32 experience than myself.  I
> am trying to build a proper win32 installer for IPython, after a user did most
> of the hard work.  For the most part, it's working very well, but I am running
> into a nasty problem, which took me a few hours to finally understand.  This
> smells to me like a python  bug, but I could be wrong.  Much googling didn't
> turn up anything relevant.
>
> Here is a brief summary: if the installer file is run from a windows drive 
> which
> is different from the one where python resides (and hence where ipython will
> end up), the installer segfaults.  No traceback, nothing, just a segfault
> (well, one of those Windows dialogs asking me to send a binary traceback to
> Redmond, but not a proper Python traceback).

There are a couple of known bugs in bdist_wininst, and you just reported
another one.  All these bugs are related to using the
post_install_script, and show up when either (thats what I currently
remember):

- the installer is run from a readonly location,
- the installer is run from a different drive (as you reported)
- the installer installs for Python 2.4

I will fix these issues in Python 2.3.5, which will probably be out as a
release candidate this week, and in Python 2.4.1.

I urge everyone to install this release candidate, rebuild the
installer with it, and test them thoroughly.

Thanks,

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


Re: py2exe problem

2005-01-26 Thread Thomas Heller
Harald Massa <[EMAIL PROTECTED]> writes:

> Grant Edwards 
>
>> LookupError: no codec search functions registered: can't find encoding
>> Googling for the error message will find you the answer.  
>
> http://starship.python.net/crew/theller/moin.cgi/Py2Exe
>
> carries within "encodings" and "encodings again" receipes to get it 
> working.
>
> A software development system which REALLY solves the encodings problem 
> WITHOUT creating a swarm of new ones could would challange even my 
> devotedness to Python :

AFAIK, McMillan Installer solves this by including all the encodings
stuff by default, and it has a --ascii flag to override this behaviour.
Would that be a solution?

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


Re: py2exe problem

2005-01-26 Thread Thomas Heller
Harald Massa <[EMAIL PROTECTED]> writes:

> Thomas Heller <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
>
>>>
>>> A software development system which REALLY solves the encodings
>>> problem WITHOUT creating a swarm of new ones could would challange
>>> even my devotedness to Python :
>> 
>> AFAIK, McMillan Installer solves this by including all the encodings
>> stuff by default, and it has a --ascii flag to override this
>> behaviour. Would that be a solution?
>
> Thomas,
>
> I solved the headaches with py2exe and encodings, again and again ...
> even documented some of these steps within the wiki. 

Much appreciated!

> But encodings still give me new pain any day: storing filenames to
> databases, displaying filenames in windows-controls, sending
> database-extracts to excel or word ... time on time encodings and/or
> unicode errors pop up and cause me misery. 
>
> So my cryout is for a solution for all encoding-problems like the python
> for-loop or list-comprehensions: elegant, simple, robust, flexible. Easy
> to use, easy to implement. 

Armin,

Would the above (include all encodings stuff by default) be a good
solution, or do you have other ideas?

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


Re: Forcing interactive interpreter without (-i)

2005-02-01 Thread Thomas Heller
Miki Tebeka <[EMAIL PROTECTED]> writes:

> Hello All,
>
> If there a way a script can tell Python to enter interactive mode even if
> the -i command line switch was not given?
>
> I want py2exe to create an interactive session, without writing my own
> REPL.

IIRC, in newer Python versions, you can set the PYTHONINSPECT env var inside
your script.

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


Re: Where are list methods documented?

2005-02-01 Thread Thomas Heller
Grant Edwards <[EMAIL PROTECTED]> writes:

> On 2005-02-01, Brian van den Broek <[EMAIL PROTECTED]> wrote:
>
>> I'm not positive I understand what you are looking for, but do these 
>> help?:
>>
>>
>>
>>
>
> Yes, that last page was the one I was looking for.  I didn't
> know enough to spell list as "mutable sequence type".
>
> -- 
> Grant Edwards   grante Yow!  I think my CAREER
>   at   is RUINED!!
>visi.com

You could also have typed 'sort' in the box here:

http://starship.python.net/crew/theller/pyhelp.cgi

This search is also available in Mark Hammond's Mozilla Python sidebar.

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


Re: Python for S60 mentioned in a mainstream Finnish e-news website

2005-02-02 Thread Thomas Heller
Ville Vainio <[EMAIL PROTECTED]> writes:

> Of course there is the whole hog and more in the official Nokia press
> release, this time in English:
>
> http://press.nokia.com/PR/200501/978226_5.html
>
> It also paints an accurate and quite positive picture of Python. Now
> we just need ctypes or Symbianic Swig and world domination will be
> ours ;-).
>
> (Yeah, ctypes will probably be a problem because of the way Symbian
> handles DLLs)

How *does* symbian handle DLLs?

Curious,

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


Re: pyFMOD problem

2005-02-03 Thread Thomas Heller
[EMAIL PROTECTED] (Tian) writes:

> I am trying to use pyfmod in python to manipulate sound.
> i have installed pyfmod, ctype, numarray (if they are necessary), i
> also copied fmod.dll to python/DLLs as well as windows/system32, but

First, you should copy fmod.dll to a directory somewhere where
LoadLibrary can find it.  That includes directories on PATH, plus the
directory where the executable is.  python/DLLs does probably not work.

> when i tried
>
>import pyFMOD
>
> I got:
>
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> import pyFMOD
>   File "C:\Python24\Lib\site-packages\pyFMOD.py", line 177, in
> -toplevel-
> _FSOUND_Sample_Load = getattr(fmod, "[EMAIL PROTECTED]")
>   File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 323,
> in __getattr__
> func = self._StdcallFuncPtr(name, self)
> AttributeError: function '[EMAIL PROTECTED]' not found
> -
> How can I deal with this?
> Thanks!

The fmod.dll that I just downloaded has a function named
'[EMAIL PROTECTED]', which indicates an api change (the number of
the '@' sign indicates how many bytes are needed as parameters).

Probably pyFMOD needs an older version of fmod.dll, or pyFMOD should be
updated?

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


Re: Where is WSAEnumNetworkEvents???

2005-02-03 Thread Thomas Heller
Dave Brueck <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] wrote:
>> I was trying to write an asyncronous TCP server for win32 using
>> WSAEventSelect (which lives if win32file). Such events require
>> WaitForMultipleObjects (which lives if win32event) and
>> WSAEnumNetworkEvents WHICH IS NOT EXPOSED. This makes WSAEventSelect
>> useless. Does somebody know how to add the WSAEnumNetworkEvents and
>> WSANetwotkEvents structure win32file?
>>  Maybe I'm missing something?
>
> You could both build the structures and call the functions in ctypes
> (http://starship.python.net/crew/theller/ctypes/)
>
> [untested code follows]
>
> from ctypes import *
> class WSANETWORKEVENTS(Structure):
>  _fields_ = [('lNetworkEvents', c_long),
>  ('iErrorCode', c_int * 10) # 10 = FD_MAX_EVENTS
> ]
>
> You'd access the API via windll.ws2_32.WSAEnumNetworkEvents, e.g.
>
> networkEvents = WSANETWORKEVENTS()
> i = windll.ws2_32.WSAEnumNetworkEvents(s, hEventObject, byref(networkEvents))
> if i != 0:
>  # Handle an error

Yes. And the day is not too far away (hopefully), that you'll be able to
generate the wrapper code automatically:


  c:\sf\ctypes\sandbox\tools\codegen>h2xml winsock2.h -o winsock2.xml -q
  skipped #define SNDMSG ::SendMessage FunctionType
  c:\sf\ctypes\sandbox\tools\codegen>xml2py winsock2.xml -q -w -d -s 
WSAEnumNetworkEvents
  # generated by 'xml2py'
  # flags 'winsock2.xml -w -d -s WSAEnumNetworkEvents'
  from ctypes import *
  from ctypes import decorators
  
  class _WSANETWORKEVENTS(Structure):
  # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/winsock2.h 1041
  pass
  ws2_32 = CDLL('ws2_32')
  
  @ decorators.stdcall(c_int, ws2_32, [c_uint, c_void_p, 
POINTER(_WSANETWORKEVENTS)])
  def WSAEnumNetworkEvents(p1, p2, p3):
  # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/winsock2.h 2706
  return WSAEnumNetworkEvents._api_(p1, p2, p3)
  
  _WSANETWORKEVENTS._fields_ = [
  # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/winsock2.h 1041
  ('lNetworkEvents', c_long),
  ('iErrorCode', c_int * 10),
  ]
  assert sizeof(_WSANETWORKEVENTS) == 44, sizeof(_WSANETWORKEVENTS)
  assert alignment(_WSANETWORKEVENTS) == 4, alignment(_WSANETWORKEVENTS)
  
  c:\sf\ctypes\sandbox\tools\codegen>



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


Re: Python API to manipulate CAB files.

2005-06-23 Thread Thomas Heller
Konstantin Veretennicov <[EMAIL PROTECTED]> writes:

> On 6/22/05, Peter Maas <[EMAIL PROTECTED]> wrote:
>> Isaac Rodriguez schrieb:
>> > Does anyone know of a Python API to manipulate CAB files?
>
> I guess you'll have to interface with setupapi.dll
> (SetupIterateCabinet) via ctypes, or with Microsoft Cabinet utilities
> via subprocess module. Neither is what people call fun...
>
> - kv
Probably not what you mean with 'manipulate CAB files', but it may give
a start with ctypes and cab:

http://starship.python.net/crew/theller/moin.cgi/CreateCab

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


Re: List of all installed applications (XP)?

2005-06-23 Thread Thomas Heller
"Guy Lateur" <[EMAIL PROTECTED]> writes:

> | What -- from your point of view -- is an "application"?
>
> Good question. Let me try to elaborate: I would like to know if people in 
> our company (building techniques) are using non-licensed software (eg 
> Photoshop, Office, AutoCad). So I guess by 'application' I mean commercial 
> software packages like those.
>
> Is it safe to assume those apps get listed in AppPath? I don't think my 
> users are cunning enough to mess with the registry, so I guess we're talking 
> about the 'standard' installation.
>
>
>
> | Neither does every app have an Add/Remove Program
> | entry. (And some things have entries which aren't apps).
>
> Just out of curiosity: can one read the info/list one gets in Add/Remove 
> Programs? It's not a problem I get results that aren't actually apps, but it 
> is important I get all apps.
>

I think it's this registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

Maybe you should try HKEY_CURRENT_USER\.. or HKEY_USERS\..\.. as well.

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


Re: PEP 304 - is anyone really interested?

2005-06-23 Thread Thomas Heller
Thomas Guettler <[EMAIL PROTECTED]> writes:

> Am Wed, 22 Jun 2005 18:01:51 -0500 schrieb Skip Montanaro:
>
>> 
>> I wrote PEP 304, "Controlling Generation of Bytecode Files":
>> 
>> http://www.python.org/peps/pep-0304.html
>> 
>
> ...
>
> Hi,
>
> I am interested in a small subset: I want to import a file without
> a '.pyc' being generated. 
>
> Background: I sometimes missuse python for config files. For example

Although I was not interested originally, I think that's a use case I
also have.  Optional config files, which should not be compiled to .pyc
or .pyo.  Only removing the .py file doesn't have the expected effect
if a .pyc and/or .pyo if is left.

I don't think the PEP supports such a use case.

BTW: While I'me reading the PEP to check the above, I encountered this:

  Add a new environment variable, PYTHONBYTECODEBASE, to the mix of
  environment variables which Python understands. PYTHONBYTECODEBASE is
  interpreted as follows:

  If not defined, Python bytecode is generated in exactly the same
  way as is currently done. sys.bytecodebase is set to the root
  directory (either / on Unix and Mac OSX or the root directory of
  the startup (installation???) drive -- typically C:\ -- on
  Windows).

  If defined and it refers to an existing directory to which the
  user has write permission, sys.bytecodebase is set to that
  directory and bytecode files are written into a directory
  structure rooted at that location.

  If defined but empty, sys.bytecodebase is set to None and
  generation of bytecode files is suppressed altogether.

AFAIK, it is not possible to define empty env vars on Windows.

  c:\>set PYTHONCODEBASE=

would remove this env var instead of setting it to an empty value.

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


Re: Modules for inclusion in standard library?

2005-06-27 Thread Thomas Heller
Reinhold Birkenfeld <[EMAIL PROTECTED]> writes:

> Hello,
>
> at the moment python-dev is discussing including Jason Orendorff's path module
> into the standard library.

I have never used the path module before, although I've heard good
things about it.  But, it seems to have problems with unicode pathnames,
at least on windows:

C:\>mkdir späm

C:\späm>py24
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from path import path
>>> path.getcwd()
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\TSS5\components\_Pythonlib\path.py", line 97, in getcwd
return path(os.getcwd())
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 5: ordinal 
not in range(128)
>>>

Although it seems this could be fixed by adding this constructor to the
path class:

def __new__(cls, init=u""):
if isinstance(init, unicode):
return _base.__new__(cls, init)
return _base.__new__(cls, init, sys.getfilesystemencoding())

I would really appreciate if Python's unicode support would be better
;-), and maybe it's easier to add this to the path module than to
os.path.

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


Re: whois like functionality on Windows?

2005-06-28 Thread Thomas Heller
Gerrit Muller <[EMAIL PROTECTED]> writes:

> I am migrating a website from a UNIX based machine to an Windows
> machine. In the logfiles I got from the old machine I mostly got
> domain names and sometimes only IP addresses. The Windows machine
> seems to produce only IP addresses.
>
> Somehow I cannot find a windows solution to translate an IP address
> back into a domain-name. Searching with Google shows that more people
> have been wrestling with this problem.
>
> I did find working whois scripts, but unfortunately:
> - the verbose whois registrar information often forbids automated access
> - the information is rather distributed, so you have to somehow access
> sufficient servers
> - you still have to find the domain name in the sea of details returned
>
> I also found socket based solutions, but these solutions crash with
> the message "host not found" :-(
>
> Anyone suggestions?

This?

C:\>py23
Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostbyaddr("194.109.137.226")
('fang.python.org', [], ['194.109.137.226'])
>>>

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


Re: COM problem .py versus .exe

2005-06-29 Thread Thomas Heller
"Tim Golden" <[EMAIL PROTECTED]> writes:

> [Greg Miller]
> | Hello again, I put the executable on the "virgin" PC today.  
> | I am using
> | the wmi(b) that you gave me.  The error that I am receiving now is:
> | 
> | File "autoStart.pyc", line 241, in test
> | File "wmib.pyc", line 157, in ?
> | File "win32com\client\__init__.pyc", line 73, in GetObject
> | File "win32com\client\__init__.pyc", line 88, in Moniker
> | com_error: (-2147221020, 'Invalid syntax', None, None)
> | 
> | any thoughts on this error?  Thanks again for the help.
>
> Well that's a real pain!

Doesn't this look like the WMI service (or how it's called) is not
installed?

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


Re: Modules for inclusion in standard library?

2005-06-29 Thread Thomas Heller
Simon Brunning <[EMAIL PROTECTED]> writes:

> On 6/28/05, John Roth <[EMAIL PROTECTED]> wrote:
>> I'd definitely like to see ctypes. I can agree with the segfault
>> issue, but I think that some design work would eliminate that.
>
> I'm not sure that it would. Ctypes allows you, as one colleague
> memorably put it, to "poke the operating system with a stick". You are
> always going to be able to use ctypes to provoke spectacular crashes
> of the kind that you can never get with 'ordinary' Python.

Right.

> Having said that, I'd like to see ctypes in the standard library
> anyway, with a suitably intimidating warning in the docs about the
> trouble you can get yourself into with it.

To me, this sounds that *at least* a PEP would be needed to convince
Guido.  Or, to record the reasoning why it cannot be included.

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


Re: Controlling WinAMP (WM_COPYDATA problem)

2005-06-30 Thread Thomas Heller
"The Collector" <[EMAIL PROTECTED]> writes:

> Hi,
>
> I've been looking for almost two full days now to get full control of
> WinAMP using python. Simple play/stop functions are no problem. It's
> the WM_COPYDATA that's used by IPC_PLAYFILE (=add a file to the
> playlist) that's giving me troubles big time!
>
> My latest test code:
> ---
[reformatted the packData function]

def packData( dwData, lpData ):
# calculate the pointer address for the lpData
lpData_ad = array.array('c', lpData).buffer_info()[0]
# calculate the length of the lpData (=cbData)
cbData = array.array('c', lpData).buffer_info()[1]
# pack dwData, cbData and lpData into a copyDataStruct
cds = struct.pack("IIP", dwData, cbData, lpData_ad)
# find the pointer address of the copyDataStruct
cds_ad = array.array('c', cds).buffer_info()[0]
# return the copyDataStruct pointer-address
return cds_ad

>From a quick inspection of the packData function:

You need to keep the array instances alive!  You only retrieve the
addresses, and the array instances itself are deleted immediately, so
the addresses are no longer valid.

(Hint: ctypes might also be a solution for you - it allows flexible
creation of C compatible data structures)

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


Re:

2005-07-01 Thread Thomas Heller
"Adriaan Renting" <[EMAIL PROTECTED]> writes:

> I'm not a very experienced Python programmer yet, so I might be
> mistaken, but there are a few things that would make me prefer C++ over
> Python for large (over 500.000 LOC) projects.
> - namespaces
> - templates
> - strong type checking
> - data hiding
> - more available libraries and more advanced developement tools.
>
> I'm talking about managing the code, not the programmers, the project or
> schedules or what have you. Those are independent from the chosen
> programming language.

Just a single datapoint: Implementing a trivial COM object in Python
requires, let's guess, about 10 or 20 lines of source code.

When I do the same in MSVC6, the wizard creates 10 files, with nearly
400 lines of code.  Sure, I didn't have to write these code lines, but
I'm required to understand and manage them as well.

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


Re:

2005-07-01 Thread Thomas Heller
Thomas Heller <[EMAIL PROTECTED]> writes:

> "Adriaan Renting" <[EMAIL PROTECTED]> writes:
>
>> I'm not a very experienced Python programmer yet, so I might be
>> mistaken, but there are a few things that would make me prefer C++ over
>> Python for large (over 500.000 LOC) projects.
>> - namespaces
>> - templates
>> - strong type checking
>> - data hiding
>> - more available libraries and more advanced developement tools.
>>
>> I'm talking about managing the code, not the programmers, the project or
>> schedules or what have you. Those are independent from the chosen
>> programming language.
>
> Just a single datapoint: Implementing a trivial COM object in Python
> requires, let's guess, about 10 or 20 lines of source code.
>
> When I do the same in MSVC6, the wizard creates 10 files, with nearly
> 400 lines of code.  Sure, I didn't have to write these code lines, but
> I'm required to understand and manage them as well.

Sorry, I forgot to include the .dsw and .dsp files in the above figure.
Including them brings the LOC count up to 750 for the C++ project -
although, to be fair, on the Python side a setup.py script for py2exe
would also have to be written.  In simple cases, this is another 10
lines.

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


Re: importing pyc from memory?

2005-07-04 Thread Thomas Heller
"Derek van Vliet" <[EMAIL PROTECTED]> writes:

> The second method you describe sounds like it is along the lines of
> what I need to do. Is there a way to do this using the Python/C API?
>
> For instance, if I have the contents of a pyc file loaded entirely into
> memory, and I have a pointer to the beginning of the file and the size
> in bytes at my disposal, can I import that by any means?

The .pyc file format is sort of 'documented' in lib/py_compile.py.
IIRC, it is a magic number, a timestamp, plus a marshalled code
object.

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


Re: Py2Exe and the log file...

2005-07-05 Thread Thomas Heller
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Hi !
>
> 1. Thanx for your answer in the theme of Unicode, and other things.
> 2. The problem:
> I need to create an application that not need Python libs to install.
> Py2Exe is good for that, but I need to copy the "dist" to the network
> drive what mapped readonly.
> This is a protection.
>
> So: in this time I have been use same applications, but they are
> created by Delphi.
> These apps make logs into user's temp to avoid the log merging, and
> log creation problems (in readonly drive).
>
> Py2Exe have an exception catcher "module", that log the errors in the
> log file that created in app dir.
> This is problem, because the log file creation have been failed in RO drive.
>
> How to I redirect this log file, or can I do anything to aviod the log
> file creation error ?
>
> Thanx for your help: ft

The code that creates the logfile is in 
"Lib/site-packages/py2exe/boot_common.py".
This code is executed before the main script is started.

You can override it by assigning another object to sys.stderr, at the
start of your main script, which has a write method doing what YOU want.

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


Re: Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

2005-07-05 Thread Thomas Heller
[EMAIL PROTECTED] writes:

> Ralf W. Grosse-Kunstleve wrote:
>> I often find myself writing::
>>
>> class grouping:
>>
>> def __init__(self, x, y, z):
>> self.x = x
>> self.y = y
>> self.z = z
>> # real code, finally
>>
>> This becomes a serious nuisance in complex applications with long
>> argument lists
>
> Yes... indeed it does. This is so common that there is a standard
> idiom for handling it:
>
> def __init__(self, x, y, z):
> self.__dict__.update(locals())
>
> sometimes with modifications to avoid setting self.self.

>> I am actually using a simple trick::
>>
>> adopt_init_args(self, locals())
>
> If the implementation is only 3-4 lines long (and a simpler
> implementation can be), then is can simply be included inline with
> every script that needs to use it.
>
>>   - The ``adopt_init_args(self, locals())`` incantation is hard to
>> remember and difficult to explain to new-comers.
>
> A better name would help with this. The need for locals() is
> unavoidable.

Ahem - sys._getframe()

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


Re: Favorite non-python language trick?

2005-07-06 Thread Thomas Heller
Edvard Majakari <[EMAIL PROTECTED]> writes:

> (sorry, my NUA had lost the original article)
>>
>>> I'm curious -- what is everyone's favorite trick from a non-python
>>> language? And -- why isn't it in Python?
>
> Ability to tag some methods 'deprecated' as in Java (from 1.5
> onwards?). However, Python interpreter doesn't have to do it: pydoc and
> similar tools could detect, say, '@deprecated' in method comment string and
> warn user about it.

I don't see what's wrong with this code, and if one wanted, one could
also implement a decorator which calls warnings.warn when the function
is called:

def c_buffer(init, size=None):
"deprecated, use create_string_buffer instead"
import warnings
warnings.warn("c_buffer is deprecated, use create_string_buffer instead",
  DeprecationWarning, stacklevel=2)
return create_string_buffer(init, size)

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


Conditionally implementing __iter__ in new style classes

2005-07-06 Thread Thomas Heller
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
Hope that makes sense, if not, this code should be clearer:

class Base:
def __getattr__(self, name):
if name == "__iter__" and hasattr(self, "Iterator"):
return self.Iterator
raise AttributeError, name

class Concrete(Base):
def Iterator(self):
yield 1
yield 2
yield 3

The idea is that if a subclass of Base defines an 'Iterator' method,
instances are iterable.  They are not iterable otherwise.

The above gives the expected behaviour: iter(Base()) raises a
"TypeError: iteration over non-sequence", and iter(Concrete()) returns a
generator.

If, however, I make Base a newstyle class, this will not work any
longer.  __getattr__ is never called for "__iter__" (neither is
__getattribute__, btw).  Probably this has to do with data descriptors
and non-data descriptors, but I'm too tired at the moment to think
further about this.

Is there any way I could make the above code work with new style
classes?

Thanks,

Thomas

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


Re: Conditionally implementing __iter__ in new style classes

2005-07-06 Thread Thomas Heller
Thomas Heller <[EMAIL PROTECTED]> writes:

> I'm trying to implement __iter__ on an abstract base class while I don't
> know whether subclasses support that or not.
> Hope that makes sense, if not, this code should be clearer:
>
> class Base:
> def __getattr__(self, name):
> if name == "__iter__" and hasattr(self, "Iterator"):
> return self.Iterator
> raise AttributeError, name
>
> class Concrete(Base):
> def Iterator(self):
> yield 1
> yield 2
> yield 3
>
> The idea is that if a subclass of Base defines an 'Iterator' method,
> instances are iterable.  They are not iterable otherwise.
>
> The above gives the expected behaviour: iter(Base()) raises a
> "TypeError: iteration over non-sequence", and iter(Concrete()) returns a
> generator.
>
> If, however, I make Base a newstyle class, this will not work any
> longer.  __getattr__ is never called for "__iter__" (neither is
> __getattribute__, btw).  Probably this has to do with data descriptors
> and non-data descriptors, but I'm too tired at the moment to think
> further about this.
>
> Is there any way I could make the above code work with new style
> classes?

I forgot to mention this: The Base class also implements a __getitem__
method which should be used for iteration if the .Iterator method in the
subclass is not available.  So it seems impossible to raise an exception
in the __iter__ method if .Iterator is not found - __iter__ MUST return
an iterator if present.

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


Re: The GIL, callbacks, and GPFs

2005-07-06 Thread Thomas Heller
Francois De Serres <[EMAIL PROTECTED]> writes:

> Hello,
>
> I'm chasing a GPF in the interpreter when running my extension module.
> It's not very elaborated, but uses a system (threaded) callback, and
> therefore the GIL.
> Help would be mucho appreciated. Here's the rough picture:
>

> static void external_callback(const Bag * const bag) {   if
> (my_callback && (my_callback != Py_None)) {
> PyObject * arglist = NULL;
> PyObject * result = NULL;
> arglist = Py_BuildValue("(s#)", bag->data, bag->size);
>   /* do it */
> PyGILState_STATE gil = PyGILState_Ensure();

You're calling Py_BuildValue without holding the GIL.  Not sure if
that's the reason for your problems, but I don't think its ok.

> result = PyEval_CallObject(my_callback, arglist);
> PyGILState_Release(gil);
>   Py_DECREF(arglist);
> Py_DECREF(result);  }
> }

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


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>
>>I'm trying to implement __iter__ on an abstract base class while I don't
>>know whether subclasses support that or not.

> Will a property or custom descriptor do what you want? E.g.
>
>  >>> class Base(object):
>  ... def __getIter(self):
>  ... if hasattr(self, "Iterator"):
>  ... return self.Iterator
>  ... raise AttributeError, name
>  ... __iter__ = property(__getIter)
>  ...
>  >>> class Concrete(Base):
>  ... def Iterator(self):
>  ... yield 1
>  ... yield 2
>  ... yield 3
>  ...
>  >>> iter(Base())
>  Traceback (most recent call last):
>File "", line 1, in ?
>  TypeError: iteration over non-sequence
>  >>> iter(Concrete())
>  
>  >>> list(iter(Concrete()))
>  [1, 2, 3]

Yep, that's exactly what I need - thanks.

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


Re: Windows Cmd.exe Window

2005-07-07 Thread Thomas Heller
"Giles Brown" <[EMAIL PROTECTED]> writes:

> Nah.  You're missing my point.  I only want the command window not to
> be closed if there is an *exception*.  Picky I know, but there you go.

I find it useful to set an sys.excepthook which calls the debugger
pdb.pm().  This way I not only see the traceback, but I can also poke
around in the environment to find the problem.

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


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>
>>[EMAIL PROTECTED] (Bengt Richter) writes:
>>
>>> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>>>
>>>>I'm trying to implement __iter__ on an abstract base class while I don't
>>>>know whether subclasses support that or not.
>>
>>> Will a property or custom descriptor do what you want? E.g.
>>>
>>>  >>> class Base(object):
>>>  ... def __getIter(self):
>>>  ... if hasattr(self, "Iterator"):
>>>  ... return self.Iterator
>>>  ... raise AttributeError, name
>>>  ... __iter__ = property(__getIter)
> [...]
>>
>>Yep, that's exactly what I need - thanks.
>>
> BTW, I forgot to mention that you could use property as a decorator
> in the above single-argument case:
>
>  >>> class Base(object):
>  ... @property
>  ... def __iter__(self):
>  ... if hasattr(self, "Iterator"):
>  ... return self.Iterator
>  ... raise AttributeError, name

Of course.  I didn't spot this, but I cannot use this anyway for 2.3
compatibility.

>  ...
>  >>> class Concrete(Base):
>  ... def Iterator(self):
>  ... yield 1
>  ... yield 2
>  ... yield 3
>  ...
>  >>> iter(Base())
>  Traceback (most recent call last):
>File "", line 1, in ?
>  TypeError: iteration over non-sequence
>  >>> iter(Concrete())
>  
>  >>> list(iter(Concrete()))
>  [1, 2, 3]
>
> Hope there isn't a gotcha for your use case in the way an instance attribute
> of the same name is allowed. A custom descriptor could eliminate that.
>
>  >>> inst = Concrete()
>  >>> list(iter(inst))
>  [1, 2, 3]
>  >>> inst.__init__ = 'abc'
>  >>> list(iter(inst))
>  [1, 2, 3]
>  >>> inst.__init__
>  'abc'

I don't understand what you mean here.  A __iter__ instance attribute?

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


Re: PEP on path module for standard library

2005-07-22 Thread Thomas Heller
[EMAIL PROTECTED] writes:

> I really love Jason's 'path' module.  Sadly, I've encountered a serious
> problem with using it.  When you try to 'freeze' an application module,
> and Jason's 'path' module is present in any of the directories that are
> looked at by freeze's module finder (your app doesn't have to import
> it), freeze goes into an infinite loop of imports, eventually getting a
> 'maximum recursion depth' exception.  This seems to be related to
> freeze getting confused between 'os.path' and Jason's 'path'.
>
> I encountered this using Jason's latest 'path' module and Python 2.3.2.
>  I was able to solve it for my use by renaming path.py to newpath.py
> and using 'from newpath import path' in my modules.
>
> I've just notified Jason about this.  I presume a solution like mine
> will be used, and look forward to seeing Jason's module in stdlib.

That was a bug in modulefinder, which was fixed in Python 2.4 and 2.3.4.
See http://www.python.org/sf/876278.

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


Re: showing help(M) when running module M standalone

2005-07-30 Thread Thomas Heller
Chris <[EMAIL PROTECTED]> writes:

> hello,
> I have a small module which only contains some utility functions. when
> running this standalone I would like to show the module docs and each
> function docs, as if doing
>
>   import M
>   help(M)
>
> I came up with the following but I reckon there is a much simpler way?
>
> if __name__ == '__main__':
>  print __doc__
>  print "\nFUNCTIONS:\n"
>  for x in __all__:
>  print x
>  exec "print " + x + ".__doc__"
>
> Works but does not seem right using exec for such a task.
>
> any hint would be great!

if __name__ == "__main__":
help("__main__")

The only downside is that the module name is printed as '__main__'.

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


Re: Metaclasses and class variables

2005-08-04 Thread Thomas Heller
Jan-Ole Esleben <[EMAIL PROTECTED]> writes:

> Hi!
>
> I am new to this list, and maybe this is a stupid question, but I
> can't seem to find _any_ kind of answer anywhere.
>
> What I want to do is the following:
> I want to insert a class variable into a class upon definition and
> actually use it during definition.
>
> Manually, that is possible, e.g.:
>
> class A:
>   classvar = []
>   classvar.append(1)
>   classvar.append(2)
>
> I don't want to explicitly set the variable, though. My idea was to
> write the following:
>
> class Meta(type):
>   def __new__(cls, name, bases, d):
> d['classvar'] = []
> return type.__new__(cls, name, bases, d)
>
> class Test:
>   __metaclass__ = Meta
>
>   classvar.append(1)
>   classvar.append(2)
>
> However, Python complains that the variable isn't defined; it can be
> found in the class dictionary _after_ definition, though, and then it
> can also be used. But where's the conceptual difference (to the manual
> approach)?

classvar is defined AFTER the class has been created.  So, this should
work:

class Test:
__metaclass__ = Meta

Test.classvar.append(1)

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


Re: Do I need to have site.py available or not ?

2005-08-06 Thread Thomas Heller
Reinhold Birkenfeld <[EMAIL PROTECTED]> writes:

> Terry Reedy wrote:
>> <[EMAIL PROTECTED]> wrote in message 
>> news:[EMAIL PROTECTED]
>>> Hi,
>>> on startup my embedded python comes up with "import site failed use
>>> -v". Later python crashes on Pyrun_file(). This is the first time I
>>> have used python and I would like to know does it require site.py to be
>>> read in, and has anyone got an idea how to pass in the -v without using
>>> the python -v command, ie the embedded way. Thanks very much.
>> 
>> If by embedded you mean embedded in a C/C++ program, I would look to the 
>> doc for the C API function that you use to start it up to see whether there 
>> is a way to pass in argv flags or to have the same effect.
>
> Also note that '-v' doesn't do what you want here, it merely activates verbose
> mode so that you can find the cause for above error. You want '-S'.

I would say that "import site failed" means that something is wrong.
The '-v' flag helps to find out what and why.  The PYTHONVERBOSE
environment variable does the same.

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


Re: Determining win32 dll dependency

2005-08-15 Thread Thomas Heller
Robin Becker <[EMAIL PROTECTED]> writes:

> A client requested that I send MSVCR71.DLL along with the rest of an
> application as it wasn't present on his machine.
>
> That is allowed as
>
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_c_run.2d.time_libraries.asp
>
> seems to explicitly allow for this.

For a discussion about the rights (or not) to distribute msvcr71.dll you
could read the py2exe-users lists archive.

> I would like to automate my build script to include this file, but
> cannot think of an automatic way to determine which of msvcr70/71.dlls
>  are needed.

py2exe contains an extension module that determines binary dependencies:

>>> from py2exe.py2exe_util import depends
>>> impport pprint
>>> pprint.pprint(depends(r"c:\windows\system32\notepad.exe").keys())
['C:\\WINDOWS\\system32\\USER32.dll',
 'C:\\WINDOWS\\system32\\SHELL32.dll',
 'C:\\WINDOWS\\system32\\comdlg32.dll',
 
'C:\\WINDOWS\\WinSxS\\X86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.2180_x-ww_a84f1ff9\\COMCTL32.dll',
 'C:\\WINDOWS\\system32\\ADVAPI32.dll',
 'C:\\WINDOWS\\system32\\msvcrt.dll',
 'C:\\WINDOWS\\system32\\WINSPOOL.DRV',
 'C:\\WINDOWS\\system32\\GDI32.dll',
 'C:\\WINDOWS\\system32\\KERNEL32.dll']
>>>

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


Re: Database of non standard library modules...

2005-08-19 Thread Thomas Heller
Steve Holden <[EMAIL PROTECTED]> writes:

> Robert Kern wrote:
>> Jon Hewer wrote:
>>
>>>Is there an online database of non standard library modules for Python?
>> http://cheeseshop.python.org/pypi
>>
> While cheeseshop might resonate with the Monty Python fans I have to
> say I think the name sucks in terms of explaining what to expect. If I
> ask someone where I can find a piece of code and the direct me to the
> cheese shop, I might look for another language.

+1

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


Re: pythonXX.dll size: please split CJK codecs out

2005-08-21 Thread Thomas Heller
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:

> Ron Adam wrote:
>> I would put the starting minimum boundary as:
>> 
>>1. "The minimum required to start the python interpreter with no
>> additional required files."
>> 
>> Currently python 2.4 (on windows) does not yet meet that guideline, so
>> it seems some modules still need to be added while other modules, (I
>> haven't checked which), are probably not needed to meet that guideline.
>
> I'm not sure, either, but I *think* python24 won't load any .pyd file
> on interactive startup.

That seems to be true.  But it will need zlib.pyd as soon if you try to
import from compressed zips.  So, zlib can be thought as part of the
modules required for bootstrap.

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


Re: Revised PEP 349: Allow str() to return unicode strings

2005-08-23 Thread Thomas Heller
Neil Schemenauer <[EMAIL PROTECTED]> writes:

> [Please mail followups to [EMAIL PROTECTED]
>
> The PEP has been rewritten based on a suggestion by Guido to change
> str() rather than adding a new built-in function.  Based on my
> testing, I believe the idea is feasible.  It would be helpful if
> people could test the patched Python with their own applications and
> report any incompatibilities.
>

I like the fact that currently unicode(x) is guarateed to return a
unicode instance, or raises a UnicodeDecodeError.  Same for str(x),
which is guaranteed to return a (byte) string instance or raise an
error.

Wouldn't also a new function make the intent clearer?

So I think I'm +1 on the text() built-in, and -0 on changing str.

Thomas

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


Re: Unix diff command under Window.

2005-08-24 Thread Thomas Heller
"TonyHa" <[EMAIL PROTECTED]> writes:

> Hello,
>
> Does any one have using Python to write a Unix "diff" command for
> Window?
>
> Tony Ha.

Yes.  There's a script in your Python distribution:
Tools/scripts/diff.py

See also the docs for the 'difflib' standard library module.

I do not know whether the Tools directory is installed by default or
not.

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


Re: Unix diff command under Window.

2005-08-25 Thread Thomas Heller
Trent Mick <[EMAIL PROTECTED]> writes:

> [Neil Hodgson wrote]
>> Thomas Heller:
>> 
>> > Yes.  There's a script in your Python distribution:
>> > Tools/scripts/diff.py
>> > 
>> > See also the docs for the 'difflib' standard library module.
>> 
>> Is the opposite code, a Python equivalent to 'patch' available? I 
>> have endless trouble receiving patch files that assume one of Windows or 
>> Unix (in terms of path names and line end characters) which then fail to 
>> apply on the other platform. I would like to have a version I could hack on.
>
> So would I! I also have problems with the available patch.exe binaries
> hanging or crashing occassionally on Windows.

The only slightly related thing that I know of is the 'Perl Power Tools'
Unix reconstruction project.  Seems they have a 'patch' command
implemented in perl:

http://ppt.perl.org/commands/patch/

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


Re: py2exe and output executable name

2005-09-01 Thread Thomas Heller
Miki Tebeka <[EMAIL PROTECTED]> writes:

> Hello All,
>
> Is there a way to tell py2exe to create an executable with arbirary name?
> Currently the executable name is the script name with .exe suffix.

See the advanced sample in lib/site-packages/py2exe/samples/advanced.
The executable name is defined by the 'dest_base' attribute of the
Target class.  This sample uses it to build a console *and* a gui
version at the same time from the small wxPython script, with different
names.

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


Re: Python C module questions

2005-09-01 Thread Thomas Heller
Robert Kern <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] wrote:
>> Hi,
>> 
>> I'm rather new to Python, and I've just written my first Python C
>> module.  I was wondering if some more experience Pythonista would look
>> over what I've written and given me some pointers (or find some bugs).
>> I had a few questions while writing this as well.
>> 
>> Also, I know that there are much better ways to compute nearest
>> neighbors than the brute force n^2 method, but this is plenty fast for
>> this application (at least the C version is).

You should give up C with a dumb algorithm running at fast speed.
Implement a better algorithm in Python, maybe you can even outperform
the dumb code.

>> 1.  How do I add docstrings to my module?
>
> You mean a docstring on the module object itself? In initmodule() make a
> string object with the contents of the docstring and assign it to
> module.__doc__ . There might be a more idiomatic way, but I can't think
> of it without trawling through the docs.

Use Py_InitModule3() instead.

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


Re: Python C module questions

2005-09-01 Thread Thomas Heller
[EMAIL PROTECTED] writes:

[...]
> /* convert sequences to tuples if necessary */
> ra1 = PySequence_Fast(ra1, "ra1 must be iterable");
> if (ra1 == NULL) {
> return NULL;
> }
>
> dec1 = PySequence_Fast(dec1, "dec1 must be iterable");
> if (dec1 == NULL) {
> return NULL;
> }

You leak a refcount to ra1 here in the case the the second
PySequence_Fast fails.

[...]
> /* allocate memory for C arrays */
> r1 = (double *) malloc(len1 * sizeof(double));
> if (r1 == NULL) {
> Py_DECREF(ra1);
> Py_DECREF(dec1);
> Py_DECREF(ra2);
> Py_DECREF(dec2);
> return PyErr_NoMemory();
> }
>
> d1 = (double *) malloc(len1 * sizeof(double));
> if (d1 == NULL) {
> Py_DECREF(ra1);
> Py_DECREF(dec1);
> Py_DECREF(ra2);
> Py_DECREF(dec2);
> return PyErr_NoMemory();
> }
and so on, and so on.

You should probably better start your code initializing all local vars
to NULL, like this:

PyObject *ra1 = NULL, *dec1 = NULL, ...
char *r1 = NULL, char *d1 = NULL, ...;

Then in the body of the function

d1 = (double *) malloc(len1 * sizeof(double));
if (d1 == NULL) {
PyErr_NoMemory();
goto error;
}

and have a cleanup section at the end:

  error:
if (d1) free(d1);

Py_XDECREF(ra1);
Py_XDECREF(dec1);
return NULL;
}

Reading the sources for a few builtin modules of the Python sources
itself should give you also an idea.

> I also find it hard to believe that there's no
> standard Python function for converting sequences of one object to
> arrays in C (a friend mentioned that Ruby's C API has this).

The builtin array module does help with this, you can build the
C-compatible arrays in Python, pass them to your extension, and access
them using the buffer api.

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


py2exe 0.6.1 released

2005-09-05 Thread Thomas Heller

py2exe 0.6.1 released
=

py2exe is a Python distutils extension which converts python scripts
into executable windows programs, able to run without requiring a
python installation.  Console and Windows (GUI) applications, windows
NT services, exe and dll COM servers are supported.

Changes in this release:

* py2exe can now bundle binary extensions and dlls into the
  library-archive or the executable itself.  This allows to
  finally build real single-file executables.

  The bundled dlls and pyds are loaded at runtime by some special
  code that emulates the Windows LoadLibrary function - they are
  never unpacked to the file system.

  This part of the code is distributed under the MPL 1.1, so this
  license is now pulled in by py2exe.
  
* By default py2exe now includes the codecs module and the
  encodings package.
  
* Several other fixes.

Homepage:



Download from the usual location:



Enjoy,

Thomas

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


Re: py2exe 0.6.1 released

2005-09-05 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> On Mon, 05 Sep 2005 21:55:19 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>
>>* py2exe can now bundle binary extensions and dlls into the
>>  library-archive or the executable itself.  This allows to
>>  finally build real single-file executables.
>>
>>  The bundled dlls and pyds are loaded at runtime by some special
>>  code that emulates the Windows LoadLibrary function - they are
>>  never unpacked to the file system.
> 
> So py2exe is windows-only (like exe ;-) or is there a py2elf or
> py2coff or such?

py2exe is windows only.  But, there are also (in no particular order)
PyInstaller, cx_Freeze, py2app, exemaker, freeze.

>
>>
>>  This part of the code is distributed under the MPL 1.1, so this
>>  license is now pulled in by py2exe.
> Mozilla?

Has nothing to do with Mozilla directly, it is just that parts of the
code are licensed under the Mozilla Public License Version 1.1.

I'm not too happy with this, but I have other things to do than to
rewrite software relased under the MPL just to release it under a more
liberal license (although I have considered that, and I certainly would
not reject a contribution ;-).

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


Re: py2exe 0.6.1 released

2005-09-05 Thread Thomas Heller
Bugs <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>> Changes in this release:
>> * py2exe can now bundle binary extensions and dlls into the
>>   library-archive or the executable itself.  This allows to
>>   finally build real single-file executables.
>>   The bundled dlls and pyds are loaded at runtime by some special
>>   code that emulates the Windows LoadLibrary function - they are
>>   never unpacked to the file system.
>>
>
> Wow, that is fantastic Thomas, congratulations!
>
> So far, I've only seen where Thinstall has been able to accomplish
> this and at STEEP licensing cost, not free and open-source like py2exe!

At least there is (or was) a shareware tool named PEBundle, which
promised to do something similar.  Haven't used it myself, though.

> Can this technology be applied to other platforms?

Hehe.  No idea - I don't know enough about shared libraries.

> Could this all be modified in such a way that other scripting
> languages could take advantage of your bundling technology?

Maybe, but I don't use other scripting languages.  But doesn't tcl have
a pretty advanced packer?  And perl?

> Thanks!

You're welcome,

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


Re: py2exe 0.6.1 released

2005-09-06 Thread Thomas Heller
"Giovanni Bajo" <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>
>> * py2exe can now bundle binary extensions and dlls into the
>>   library-archive or the executable itself.  This allows to
>>   finally build real single-file executables.
>>
>>   The bundled dlls and pyds are loaded at runtime by some special
>>   code that emulates the Windows LoadLibrary function - they are
>>   never unpacked to the file system.
>
>
> Cute!
>
> I tried it using the wx singlefile example, but unfortunately the resulting
> executable segfaults at startup (using Python 2.3.3 on Windows 2000, with
> latest wxWindows).

Yes, I can reproduce that.  I'm still using wxPython 2.4.2.4 for Python
2.3.5, and that combo works.  I have done a few tests, and wxPython
2.5.1.5 also works, while 2.5.5.1 crashes.

> How can I debug it?

I'll assume that's a serious question.
There is no simple answer.  First, the py2exe'd app responds to a
PY2EXE_VERBOSE environment variable, if you set it to '1', the exe will
reports imports (just as PYTHONVERBOSE does for python scripts).  Of
course you have to change the sample so that it is built as console app
to be able to see the messages.

Then, you can throw some additional prints into
lib\site-packages\zipextimporter.py, to see what it does.

I've done all this, and it seems it is crashing when trying to import
_gdi.pyd.  Next would be to debug through _memimported.pyd, but I don't
have a debug build of wxPython.

That's all I can say now.

I'll ask on the wxPython mailing list if they have an idea.

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


Re: py2exe 0.6.1 released

2005-09-06 Thread Thomas Heller
[EMAIL PROTECTED] writes:

> First: Thank you Thomas for the good work with py2exe. The single-file
> option is something I have been waiting for :-)
> Will it also be possible to build independent files (such as
> my_app_data.zip) into the executable?

Depends on how you want to access them at runtime.

What you can do is to include them as win32 resources, see the advanced
example - it puts the winXP manifest file as resource into the exe.

test_wx = Target(
   ...
   other_resources = [(resource_type, resource_id, resource_data)],
   )

resource_type and resource_id must be integers, resource_data
must be the data itself as a string.

At runtime you can access them with a win32api.LoadResource() call.

>> > I tried it using the wx singlefile example, but unfortunately the
>> > resulting executable segfaults at startup (using Python 2.3.3 on
>> > Windows 2000, with latest wxWindows).
>>
>> Yes, I can reproduce that.  I'm still using wxPython 2.4.2.4 for Python
>> 2.3.5, and that combo works.  I have done a few tests, and wxPython
>> 2.5.1.5 also works, while 2.5.5.1 crashes.
>>
>
> I have tried two more combinations for this example
> (samples/singlefile/gui/test_wx.py), both giving segfault on WindowsXP
> / SP2:
> 1. Python 2.3.3 with wxPython 2.6.1.0 unicode
> 2. Python 2.4.1 with wxPython 2.6.1.0 unicode
>
> However, the combinations
>   Python 2.4.1 with wxPython 2.4.5.1 ansi

You probably mean 2.5.5.1 ?

>   Python 2.4.1 with wxPython 2.6.1.0 ansi
> do not cause segfault, but shows a dialog box pointing to a log file,
> the contents of which is:
>
> Traceback (most recent call last):
>   File "test_wx.py", line 1, in ?
>   File "zipextimporter.pyo", line 78, in load_module
>   File "wxPython\__init__.pyo", line 10, in ?
>   File "zipextimporter.pyo", line 78, in load_module
>   File "wxPython\_wx.pyo", line 3, in ?
>   File "zipextimporter.pyo", line 78, in load_module
>   File "wxPython\_core.pyo", line 15, in ?
>   File "zipextimporter.pyo", line 78, in load_module
>   File "wx\__init__.pyo", line 42, in ?
>   File "zipextimporter.pyo", line 78, in load_module
>   File "wx\_core.pyo", line 4, in ?
>   File "zipextimporter.pyo", line 89, in load_module
> ImportError: MemoryLoadLibrary failed loading _core_.pyd
>
> Maybe this could help localizing the problem?

I hope.  Thanks for these,

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


Re: py2exe 0.6.1 released

2005-09-06 Thread Thomas Heller
"cmkl" <[EMAIL PROTECTED]> writes:

> Hi,
>
> I didnt succeed to bundle vpython-3.2.3 with py2exe-0.6.1 - regardless
> if its build as single file or not:
>
> "This application has requested the Runtime to terminate it in an
> unusual way"  and so on...
>
> This error message seems not generated by py2exe. At least I could not
> find a reference to it in the sources of py2exe.

Often this is caused by py2exe not including some needed pyds, together
with 'sloppy' programming in the extensions themselves.

Let me explain: Sometimes, extensions depend on other extensions.  Since
they cannot directly import functions from each other, Python has an API
for that: PyCObject_Import(module_name, cobject_name).  This returns an
opaque pointer, which often points to a table of functions.  Or NULL, in
case there's an error.

Normally, this import will never fail (because all the extensions are
available), so often the return value is *not* checked.  Calling one of
these functions when the import has failed will then crash the
application.

In other cases the extension programmers see no other way to report the
error except calling PyFatal_Error() when the import failed, which would
then give what you see.

For py2exe, it may help to use include more modules or the whole package
in question and try to build again.

Of course, it can also be that py2exe 0.6 has a bug that 0.5.4 did not
have, can you try that version?

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


Re: py2exe uses __init__ for class names when logging

2005-09-06 Thread Thomas Heller
flupke <[EMAIL PROTECTED]> writes:

> Hi,
>
> when i run my program and use the logging component, i see this:
>
> 2005-09-02 17:07:48,193 INFO windowmain 97 Main window created
> 2005-09-02 17:07:49,020 DEBUG windowmain 103 Frame  proxy of C++ wxFrame instance at _b8dd9401_p_wxFrame>
> 2005-09-02 17:07:49,145 INFO firebird 195 Starting up the database
>
> However when i run py2exe on my app and run it then i don't see the
> file name anymore. Instead it says __init__:
>
> 2005-09-06 16:01:17,098 INFO __init__ 1032 Main window created
> 2005-09-06 16:01:17,615 DEBUG __init__ 1032 Frame  proxy of C++ wxFrame instance at _d8057f01_p_wxFrame>
> 2005-09-06 16:01:17,677 INFO __init__ 1032 Starting up the database
>
> Any ideas on how to solve this?

This has been discussed on the py2exe-users lists, and a fix was found
by David Hess.  Fortunately he added it to the wiki:

http://starship.python.net/crew/theller/moin.cgi/LoggingModule

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


py2exe 0.6.2 released

2005-09-07 Thread Thomas Heller
This is a bugfix release for py2exe 0.6.1.

py2exe 0.6.2 released
=

py2exe is a Python distutils extension which converts python scripts
into executable windows programs, able to run without requiring a
python installation.  Console and Windows (GUI) applications, windows
NT services, exe and dll COM servers are supported.

Changes in 0.6.2:

* Several important bugfixes:

  - bundled extensions in packages did not work correctly, this
made the wxPython single-file sample fail with newer wxPython
versions.

  - occasionally dlls/pyds were loaded twice, with very strange
effects.

  - the source distribution was not complete.

  - it is now possible to build a debug version of py2exe.

Changes in 0.6.1:

* py2exe can now bundle binary extensions and dlls into the
  library-archive or the executable itself.  This allows to
  finally build real single-file executables.

  The bundled dlls and pyds are loaded at runtime by some special
  code that emulates the Windows LoadLibrary function - they are
  never unpacked to the file system.

  This part of the code is distributed under the MPL 1.1, so this
  license is now pulled in by py2exe.
  
* By default py2exe now includes the codecs module and the
  encodings package.
  
* Several other fixes.

Homepage:



Download from the usual location:



Enjoy,

Thomas

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


Re: py2exe 0.6.1 released

2005-09-07 Thread Thomas Heller
"Giovanni Bajo" <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>
>>> I tried it using the wx singlefile example, but unfortunately the
>>> resulting executable segfaults at startup (using Python 2.3.3 on
>>> Windows 2000, with latest wxWindows).
>>
>> Yes, I can reproduce that.  I'm still using wxPython 2.4.2.4 for
>> Python
>> 2.3.5, and that combo works.  I have done a few tests, and wxPython
>> 2.5.1.5 also works, while 2.5.5.1 crashes.
>
> Ah that's fine, then. I thought it was one of those "only in my computer" kind
> of issue :)
>
>>> How can I debug it?
>>
>> I'll assume that's a serious question.
>
> Of course it was, I'm not sure why you should doubt it. I was just trying to
> being helpful to you, thinking that it could have been hard to reproduce.
> Luckily, you can look into it yourself.

I wasn't offended ;-).  Debugging the bundled executables is difficult -
because the source file debug info is lost (or at least MSVC isn't able
to access it).  So you end up steppiung through the disassembly.

>> I've done all this, and it seems it is crashing when trying to import
>> _gdi.pyd.  Next would be to debug through _memimported.pyd, but I
>> don't have a debug build of wxPython.
>
> OK. Do you believe that _memimported.pyd can eventually converge to something
> stable? Emulating LoadLibrary for all versions of Windows is not an easy task
> after all. Wine might provide some insights.

Currently there's no platform specific code in this emulation.  But I
have to admit I don't use win98 any more.
I hope that _memimporter.pyd eventually becomes stable, the new 0.6.2
release contains some important fixes.

For the original problem: the code to load extensions contained in
packages was buggy.  With 0.6.2 the wxPython singlefile sample at least
works wit wxPython 2.4.2.4 + python 2.3.5, and wxPython 2.6.1.0 + Python
2.4.1.

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


Re: py2exe 0.6.1 released

2005-09-07 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> If you have a place in the program where output should never happen
> except when you would want a console window to see it in, you can
> call AllocConsole [1] safely even in multiple such places, just before
> the printing, and the first such call will create the console and hook
> up stdout and stderr ready to print. Subsequent calls to AllocConsole
> are effectively ignored, so all the output goes to the same console
> no matter which code section executed first. IMO this should be
> built into at least the windows wpython to trigger at the first
> attempt at stdout or stderr output. There could be an option to
> override that default and thus ignore stdout/stderr output, but I
> think it would be a useful default. Plus it would tell people early
> that they had usesless prints going in their wpython programs.
>

IMO that would be a nice addition to pythonw.exe, but I have no time to
care about this myself.  For py2exe, I'm still unsure how debugging
output from a frozen gui program should be handled.

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


Re: Using Python with COM to communicate with proprietary Windows software

2005-09-08 Thread Thomas Heller
Joakim Persson <[EMAIL PROTECTED]> writes:

[...]
> This means that I must come up with a way to interface Python with
> this log tool. After some investigations, I have run inte problems --
> my inital approach was to use Python + win32com to communicate with
> the COM interface. Unfortunately, it seems as if win32com, even if I
> makepy the log tool executable (which gives me the full range of
> available functions of the interface, just as expected), cannot be
> used, since the interface is not a simple IDispatch interface. Also, I
> discovered that the Python client must also implement a COM server to
> receive the log information as it is generated by the embedded device,
> passed into the log tool and then sent by the log tool COM server. 
>
> I have a rather bloated C++ client prototype which "works", so I
> should have all the code needed to invoke the interface, but this
> client is of course rather bloated in itself and not suitable for my
> experimental programming approach. Am I right in believing that the
> COM interface I am trying to use is of what is called a "custom" type,
> that I cannot access using Python + win32com?

Sounds like a perfect job for comtypes, which is a COM library
implemented in pure Python, based on ctypes.  comtypes should make it
easy to access custom (non-dispatch derived) com interfaces, or the
vtable based part of dual interfaces - it would be good however, if you
have a type library for the interfaces.

http://sourceforge.net/projects/comtypes/

No docs yet, but there are tests included which should get you started.

(I have released and announced this 3 weeks ago, but haven't got a
single feedback.  So it seems the need to access custom interfaces is
very low.)

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


  1   2   3   4   5   >