how easily can glob.glob say Unix bash `echo *`

2007-11-03 Thread p . lavarre
http://wiki.python.org/moin/glob now mentions:

The glob module lists names in folders that match Unix shell patterns.

If the elemental function emulating Unix bash `echo *` really is
missing from the 2.5 Python batteries included, then here's a brief
clear way of adding that function to Python.

Mind you, to date I've never written an elemental function for Python
that I haven't eventually found well-buried somewhere, e.g.,
os.urandom.

P.S. glob.glob bash and glob.glob rm have no hits yet, said Google
Groups.

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


Re: platform system may be Windows or Microsoft since Vista

2007-09-07 Thread p . lavarre
  Log a bug @ bugs.python.org

 http://bugs.python.org/issue1082
 TITLE ... platform system may be Windows or Microsoft since Vista

Six days gone with no feedback. Something wrong with the input?

Maybe the blank Priority field?

I agree Severity Major.

I'm thinking no priority because there is no fixing this. We now
choose between two wrong ways to change the Python Msi installer of
Windows:

1. Hide that many people now and for months or years to come will
continue to need both halves of the (platform.system() in ('Windows',
'Microsoft') guard.

2. Leave unchanged to require many more people to need both halves in
future.

I find neither choice inspiring.

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


Re: platform system may be Windows or Microsoft since Vista

2007-09-01 Thread p . lavarre
  suppose you get Python for Vista Windows today
  if platform.system() in ('Windows', 'Microsoft'):
  if not (platform.system() in ('Windows', 'Microsoft')):

 Good analysis.

Yes I am sane!! Thank you for saying.

 Log a bug @ bugs.python.org

Glad to hear I can help. I created:

http://bugs.python.org/issue1082
TITLE = (no priority set) platform system may be Windows or Microsoft
since Vista
CREATOR = [EMAIL PROTECTED]

The Search Tracker there now finds this bug within: platform system
Windows Microsoft

Thanks again for clueing me in promptly,

P.S. http://bugs.python.org/issue1082 now includes the musings:

NOTES:

There is no fixing all of this?

Cross-platform scripts actually will misbehave across the large
population that is 2.5 Python in Vista unless those scripts change to
implement something like the suggested workaround, that's now an
accomplished fact.

Question: Is it better to leave this feature as is, so that everyone
eventually learns to workaround it, or is it better to fix it late now
in 2007-09, so that many people never have to learn to workaround it?

Question: Why are we screen-scraping the Ver command, instead of
calling Win kernel32.getVersionEx? And how can any code for screen-
scraping the Ver command be in doubt about whether the platform.system
underneath is 'Windows'?

P.P.S.

http://wiki.python.org/moin/SubmittingBugs
is the page that newbie Python bug reporters should read first, I
guess

My path to that page was as follows ...

 Log a bug @ bugs.python.org

Indeed the Search Tracker finds no hits at: platform system Windows
Microsoft

Vaguely feels like e-mail registration required? Ick. Ok. Ah, the
Issues  Create New menu item appears after login, good.

Those bug Types are labeled in English but otherwise undefined. (Later
I see I could contribute my guess of definitions at
http://wiki.python.org/moin/TrackerDocs/.) I guess surprising result
values like I'm seeing count as 'Behavior' else 'RFE' else 'Security',
but not in ('Crash', 'Compile', 'Resource Usage'). I guess by RFE we
mean a wish, i.e., a Request For Enhancement.

Ok then:

TITLE: platform system may be Windows or Microsoft since Vista
TYPE: Behavior
SEVERITY: Major (not Critical, Urgent, Normal, Minor)
COMPONENTS: Windows

All the process fields I guess I should leave blank. Somehow there
is no place to describe the bug in detail??? I guess I Submit New
entry anyhow ... Oh no, not actually. There is online help of Wiki
quality!!

Clicking thru that online help eventually explains:


Change Note: describe the problem in detail, including what you
expected to happen and what did happen. Be sure to include whether any
extension modules were involved, and what hardware and software
platform you were using (including version information as
appropriate).


Thus, I wrote ...

SUMMARY:

'Microsoft' is the platform.system() of Vista Windows, whereas
'Windows' was the platform.system() of XP Windows, whoops.

STEPS TO REPRODUCE  ACTUAL RESULTS:

Run 2.5.1 Python in a Vista and see:

 import platform
 platform.system()

'Microsoft'


EXPECTED RESULTS:

 import platform
 platform.system()
'Windows'


WORKAROUND:

Write new Python source code like:

if platform.system() in ('Windows', 'Microsoft'):
if not (platform.system() in ('Windows', 'Microsoft')):

in place of obsolete Python source code like:

if platform.system() == 'Windows': # Microsoft
if platform.system() != 'Windows': # Microsoft

REGRESSION/ ISOLATION:

Seen by me in an Enterprise Vista. Indexed by Google as reported by
Martin v. Löwis (loewis) circa 2007-05-29 07:11 as:

http://mail.python.org/pipermail/patches/2007-June/022947.html
...

Patches item #1726668, was opened at 2007-05-28 03:23

On Microsoft Vista platform.system() returns 'Microsoft' and
platform.release() returns 'Windows'

Under Microsoft Windows XP SP2 platform.system() returns 'Windows' and
platform.release() returns 'XP'.

This is problem was caused by a change in the output of the ver
command. In Windows XP SP2 ver outputted 'Microsoft Windows XP
[Version 5.1.2600]'  In Microsoft Vista ver outputted 'Microsoft
Windows [Version 6.0.6000]'. The lack of the 3rd word before version
causes _syscmd_ver(...) in platform.py to return 'Microsoft' for
system instead of 'Microsoft Windows'. This causes uname() to return
the incorrect values. Both system() and release() call uname().

NOTES:

[as above]

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

platform system may be Windows or Microsoft since Vista

2007-08-31 Thread p . lavarre
Let's suppose you get Python for Vista Windows today from
http://www.python.org/download/.

Should you then conclude that the tests:

if platform.system() in ('Windows', 'Microsoft'):
if not (platform.system() in ('Windows', 'Microsoft')):

are now exactly what you should write for that 2.5.1 Python, when you
must resort to os-specific tools like DeviceIoControl, in place of the
slightly simpler tests that worked before:

if platform.system() == 'Windows': # Microsoft
if platform.system() != 'Windows': # Microsoft

?

Curiously yours, thanks in advance,

P.S. Groups search assures me clp hasn't previously reviewed: platform
system Windows Microsoft

P.P.S. I ask because this August I rediscovered this 28 May Python
uname vs. Win kernel32.getVersionEx issue indexed by Google as
follows:

http://mail.python.org/pipermail/patches/2007-June/022947.html
...
 
Patches item #1726668, was opened at 2007-05-28 03:23
 
On Microsoft Vista platform.system() returns 'Microsoft' and
platform.release() returns 'Windows'
 
Under Microsoft Windows XP SP2 platform.system() returns 'Windows' and
platform.release() returns 'XP'.
 
This is problem was caused by a change in the output of the ver
command. In Windows XP SP2 ver outputted 'Microsoft Windows XP
[Version 5.1.2600]'  In Microsoft Vista ver outputted 'Microsoft
Windows [Version 6.0.6000]'. The lack of the 3rd word before version
causes _syscmd_ver(...) in platform.py to return 'Microsoft' for
system instead of 'Microsoft Windows'. This causes uname() to return
the incorrect values. Both system() and release() call uname().

...

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


CTypes FAQs - buffer memmove offsetof uchar ((void *) -1) etc.

2007-07-13 Thread p . lavarre
http://wiki.python.org/moin/ctypes now tries to answer:

'''FAQ: How do I copy bytes to Python from a ctypes.Structure?'''
'''FAQ: How do I copy bytes to a ctypes.Structure from Python?'''
'''FAQ: Why should I fear using ctypes.memmove?'''
'''FAQ: How do I change the byte length of a ctypes.Structure?'''
'''FAQ: How do I say memcpy?'''
'''FAQ: How do I say offsetof?'''
'''FAQ: How do I say uchar?'''
'''FAQ: How do I say ((void *) -1)?'''
'''FAQ: How do I contribute to this CTypes FAQ?'''
'''FAQ: How do I learn Python CTypes, after learning C and Python?'''

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


Abort trap - Fatal Python error: GC object already tracked

2007-07-10 Thread p . lavarre
Is this interesting Python output?

$ gc-object-already-tracked.py

**
File /Users/admin/Desktop/lxio/gc-object-already-tracked.py, line
770, in __main__.REDACTED
Failed example:
nqzhexes(self.send())
Expected:
'... [redacted] ...'z
Got:
'... [redacted] ...'
Fatal Python error: GC object already tracked
Abort trap
$
$ /usr/bin/env python --version
Python 2.5.1
$ uname
Darwin
$

I can just avoid it, I don't need to solve it, but tell me I can help
by solving it, and I'll look more closely.

I can't just share all this source with you - I wrote a simulation for
pay under c*nfidentiality - but if I find I can throw away most of the
source and still produce the error, I could share that.

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


Re: Abort trap - Fatal Python error: GC object already tracked

2007-07-10 Thread p . lavarre
 Is this interesting Python output? ...

 Fatal Python error: GC object already tracked
 Abort trap

 ... tell me I can help by solving it, and
 I'll look more closely.

Sorry, never mind, not interesting after all.

Newbie me did somehow forget the fact that ctypes.memmove doesn't
bounds-check, e.g. there is no error raised by overwriting memory not
owned, which then naturally degrades the stability of the GC etc.

 import ctypes

 bytes = (3 * ctypes.c_ubyte)()
 bytes[0], bytes[1], bytes[2]
(0, 0, 0)
 CP = ctypes.POINTER
 ctypes.cast(ctypes.addressof(bytes) + 3, CP(ctypes.c_ubyte)).contents.value
0

 result = ctypes.memmove(ctypes.addressof(bytes), '\1\3\5\7', 4)
 bytes[0], bytes[1], bytes[2]
(1, 3, 5)
 ctypes.cast(ctypes.addressof(bytes) + 3, CP(ctypes.c_ubyte)).contents.value
7


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


Re: FAQ: how to vary the byte offset of a field of a ctypes.Structure

2007-06-04 Thread p . lavarre
  http://docs.python.org/lib/module-pickle.html
  ... concise Python ways of pickling and unpickling
  the (0xFF ** N) possible ways of
  packing N strings of byte lengths of 0..xFE together ...

Aye, looks like an exercise left open for the student to complete:

 pickle.dumps()
S''\np0\n.

 pickle.dumps(abc)
S'abc'\np0\n.

 pickle.loads(pickle.dumps(abc))
'abc'

 pickle.dumps(ctypes.c_ubyte(0))
...
TypeError: abstract class


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


Re: FAQ: how to vary the byte offset of a field of a ctypes.Structure

2007-06-01 Thread p . lavarre
 Often it helps to ask yourself the question: How would I do this in C? ...

 *Not* by using a structure. A structure is fine if the definition is fixed,
 or at most has *one* variable sized field at the very end.

http://docs.python.org/lib/module-pickle.html
might be near where I'll find concise Python ways of pickling and
unpickling the (0xFF ** N) possible ways of packing N strings of byte
lengths of 0..xFE together ...

I notice by now I need what ctypes does well often enough that I have
to make my corrupt copy of a subset of ctypes coexist with ctypes per
se. So I have two different BYTE definitions. One is the
ctypes.c_ubyte. The other is my corrupt copy. And likewise for a big-
endian BIG_WORD and so on. So I end up naming the one BYTE and the
other BITE, the one BIG_WORD and the other BIG_WURD, yuck.

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


FAQ: how to vary the byte offset of a field of a ctypes.Structure

2007-05-31 Thread p . lavarre
How do I vary the byte offset of a field of a ctypes.Structure?

How do I use the dynamic nature of Python, and (re-)define the data
type after the required size is already known, on a case by case
basis?

\\\

For example, suppose sometimes I receive the value '\x03hi' + \x04bye'
for the struct:

class Struct34(ctypes.Structure):
_pack_ = 1
_fields_ = [('first', 3 * ctypes.c_ubyte),
('second', 4 * ctypes.c_ubyte)]

but then sometimes instead I receive the value '\x05left' + \x06right'
for the struct:

class Struct56(ctypes.Structure):
_pack_ = 1
_fields_ = [('first', 5 * ctypes.c_ubyte),
('second', 6 * ctypes.c_ubyte)]

Thus in general I receive (0xFF ** 2) possible combinations of field
lengths.

///

How do I declare all those hugely many simply regular combinations as
one CTypes.structure?

I also need to do series of 3 or 4 or 5 strings, not just 2 strings.
But always the byte offsets of the subsequent fields vary when the
byte sizes of the preceding fields vary. The byte size of the
enclosing packed struct varies as the length of the packed bytes it
contains.

The errors I get as I try techniques that don't work include:

AttributeError: '_fields_' must be a sequence of pairs
AttributeError: _fields_ is final
ValueError: Memory cannot be resized because this object doesn't own
it
TypeError: incompatible types, c_ubyte_Array_2 instance instead of
c_ubyte_Array_1 instance

How do I change the offset of a field of a ctypes.Structure?

Is the answer to contribute to the next version of CTypes? Or is this
feature already supported somehow?

Curiously yours, thank in advance,

http://www.google.com/search?q=ctypes+variable+size
http://www.google.com/search?q=ctypes+variable+length
http://www.google.com/search?q=ctypes+variable+offset
http://www.google.com/search?q=ctypes+%22string+of+strings%22
http://www.google.com/search?q=ctypes+%22vary+the+byte+offset%22
http://www.google.com/search?q=ctypes+%22change+the+byte+offset%22

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


Re: FAQ: how to vary the byte offset of a field of a ctypes.Structure

2007-05-31 Thread p . lavarre
ctypes.sizeof(a) is still zero, as if ctypes.Structure.__init__
fetches a.__class__._fields_ rather than a._fields_

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


Re: FAQ: how to vary the byte offset of a field of a ctypes.Structure

2007-05-31 Thread p . lavarre
 Thomas,

Ouch ouch I must have misunderstood what you meant by use the dynamic
nature of Python, and (re-)define the data type after the required
size is already known, on a case by case basis.

Do you have an example of what you meant? I searched but did not find.
Are those your words?

Yes, to declare strings of strings in Python would be to express a
familiar idea that I don't know how to say well in C.

These are standard structs that I exchange with third parties, e.g.,
me editing Class files read later by a Java interpreter, so I can't
avoid having to deal with this complexity designed into them. For
discussion I've simplified the problem: back in real life I have a few
dozen variations of structs like this to deal with.

The following Python mostly works, but only at the cost of rewriting
the small part of CTypes that I need for this app.


import binascii
import struct

class Struct:

def __init__(self, declarations = []):

Add initial values to self and list the names declared.

names = []
for (initial, name) in declarations:
names += [name]
python = ' '.join(['self.' + name, '=',
'initial'])
exec python
self._names_ = names

def _fields_(self):

List the fields.

fields = []
for name in self._names_:
python = 'self.' + name
fields += [eval(python)]
return fields

def _pack_(self):

Pack a copy of the fields.

packs = ''
for field in self._fields_():
packs += field._pack_()
return packs

def _size_(self, bytes = None):

Count the bytes of the fields.

return len(self._pack_())

def _unpack_(self, bytes):

Count the bytes of a copy of the fields.

offset = 0
for field in self._fields_():
size = field._size_(bytes[offset:])
field._unpack_(bytes[offset:][:size])
offset += size
if offset != len(bytes):
why = ('_unpack_ requires a string argument'
'of length %d' % offset)
raise struct.error(why)

class Field(Struct):

Contain one value.

def __init__(self, value = 0):
self._value_ = value

def _pack_(self):
raise AttributeError('abstract')

def _unpack_(self, bytes):
raise AttributeError('abstract')

class Byte(Field):

Contain one byte.

def _pack_(self):
return struct.pack('B', self._value_)

def _unpack_(self, bytes):
self._value_ = struct.unpack('B', bytes)[0]

class ByteArray(Field):

Contain the same nonnegative number of bytes always.

def _pack_(self):
return self._value_

def _unpack_(self, bytes):
if len(bytes) == len(self._value_):
self._value_ = bytes
else:

why = ('_unpack_ requires a string argument'
'of length %d' % len(self._value_))
raise struct.error(why)

class Symbol(Struct):

Contain a count of bytes.

def __init__(self, value = ''):
Struct.__init__(self, [
(Byte(), 'length'),
(ByteArray(value), 'bytes')])
self._pack_()


def _size_(self, bytes = None):
return ord(bytes[0])

def _pack_(self):
self.length = Byte(self.length._size_() +
self.bytes._size_())
return Struct._pack_(self)

class TwoSymbols(Struct):

Contain two Symbols.

def __init__(self, values = ['', '']):
Struct.__init__(self, [
(Symbol(values[0]), 'first'),
(Symbol(values[1]), 'second')])

zz = Symbol()
print binascii.hexlify(zz._pack_()).upper()
# 01

zz = Symbol()
zz.bytes = ByteArray('left')
zz._unpack_(zz._pack_()) ; print repr(zz._pack_())
# '\x05left'

zz = Symbol()
zz.bytes = ByteArray('right')
zz._unpack_(zz._pack_()) ; print repr(zz._pack_())
# '\x06right'

zz = TwoSymbols()
zz.first.bytes = ByteArray('hi')
zz.second.bytes = ByteArray('bye')
zz._unpack_(zz._pack_()) ; print repr(zz._pack_())
# '\x03hi\x04bye'

print zz._size_()
# 7

yy = '''
def yyFunc(self):
return [self.length, self.bytes]
'''
exec yy
Symbol._fields_ = yyFunc
zz = TwoSymbols(['alef', 'bet'])
zz._unpack_(zz._pack_()) ; print repr(zz._pack_())

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


Re: FAQ: how to vary the byte offset of a field of a ctypes.Structure

2007-05-31 Thread p . lavarre
I see that changing self._fields_ doesn't change ctypes.sizeof(self).

I guess ctypes.Structure.__init__(self) fetches
self.__class__._fields_ not self._fields_.

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


Re: FAQ: How do I calculate what quoted strings and numbers mean?

2006-11-15 Thread p . lavarre
 A FAQ that discusses good ways to handle Python-like literals and
 expressions would definitely be a useful addition to the FAQ.  if nobody
 else does anything about it, I'll get there sooner or later.

Thank you.

   eval(source, {'builtins': {}}) works enough like an evaluator of
   literals to ...

 eval(source, {'builtins': {}}) doesn't prevent you from using built-ins,
 though.  it's spelled __builtins__, not builtins:

   eval(len('10'), {builtins: {}})
 2
   eval(len('10'), {__builtins__: {}}
 Traceback (most recent call last):
File stdin, line 1, in module
File string, line 1, in module
 NameError: name 'len' is not defined

Grin.  Indeed, newbie me, I didn't know that either, thank you.

I was happy enough when I saw an improvement like:

 import os
 result = eval(os.system('pwd'))
.../Desktop
 result = eval(os.system('pwd'), {whatever: {}})
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1, in module
NameError: name 'os' is not defined


Now I fear that I must have copied the misspelled builtins from some
page that's still out there somewhere misleading people ...

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


announce: FAQs suggested

2006-11-10 Thread p . lavarre
http://effbot.org/pyfaq/suggest.htm has new FAQ's:

FAQ: How do I ask to exit from a doctest
FAQ: How do I say unsigned char in ctypes?
FAQ: How do I say returns void in ctypes?
FAQ: How do I calculate what quoted strings and numbers mean?

Enjoy, Pat LaVarre

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


FAQ: How do I calculate what quoted strings and numbers mean?

2006-11-10 Thread p . lavarre
 Subject: announce: FAQs suggested ...
 http://effbot.org/pyfaq/suggest.htm has new FAQ's ...
 FAQ: How do I calculate what quoted strings and numbers mean?

 A: eval(source, {'builtins': {}}) works, without also accidentally
 accepting OS commands as input.

 Note: Eval might surprise you if you mistype this idiom as: eval(source, {}).

 Note: This idiom makes sense of ordinary Python literals (such as 010, 0x8,
 8.125e+0, and \x45ight). This idiom also correctly interprets simple
 literal expressions, such as 64**0.5.

That suggested FAQ is misleadingly incorrect as stated - we need help
rewording it.

/F correctly commented:
eval is never a good choice if you cannot trust the source; it's
trivial to do various denial-of-service attacks. See
http://effbot.org/zone/librarybook-core-eval.htm

Correspondingly, newbie me, I actually did copy the eval(source,
{'builtins': {}}) idiom into some code from that page without noticing
the comments re the cost of evaluating literal expressions like 'a' *
(10**9) , abuses of __subclass__ and mro(), etc.

But those objections miss the point.  Having had those troubles
explained to me now, I'm still leaving my code unchanged - it still
does what I mean.  That is,

eval(source, {'builtins': {}}) works enough like an evaluator of
literals to let you duck the work of writing that evaluator until you
need it.  Yagni.

That's useful, and likely an FAQ.  Anybody out there able to say
concisely what we really mean to say here?

Thanks in advance, Pat LaVarre

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


Re: announce: FAQs suggested

2006-11-10 Thread p . lavarre
http://effbot.org/pyfaq/suggest.htm
   FAQ: How do I say returns void in ctypes?
  That's in the ctypes documentation, where it belongs.

 Thank you, before I never had found Use None for void a function not
 returning anything at:
 http://starship.python.net/crew/theller/ctypes/reference.html

 Now I see, that find corresponds to:
 http://docs.python.org/dev/lib/ctypes-foreign-functions.html

 I think this remains an FAQ, because I see void is missing from much
 more prominent places:
 http://docs.python.org/dev/lib/node452.html Fundamental data types
 http://docs.python.org/dev/lib/ctypes-return-types.html

 Finding a way to suggest improving those docs would help more than
 suggesting an FAQ, I agree.

I might have hit this brick wall while working offline, with nothing
but the doc to hand.

http://www.google.com/search?q=site%3Adocs.python.org+ctypes+void
now, if not before, does fetch that key phrase:
Use None for void a function not returning anything

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
 Not as concisely as a one-byte struct code

Help, what do you mean?

 you presumably... read... the manual ...

Did I reread the wrong parts?  I see I could define a ctypes.Structure
since 2.5, but that would be neither concise, nor since 2.3.

 when 24-bit machines become ... popular

Indeed the struct's defined recently, ~1980, were contorted to make
them easy to say in C, which makes them easy to say in Python, e.g.:

X28Read10 = 0x28
cdb = struct.pack('BBIBHB', X28Read10, 0, skip, 0, count, 0)

But when talking the 1960's lingo I find I am actually resorting to
horrors like:

X12Inquiry = 0x12
xxs = [0] * 6
xxs[0] = X12Inquiry
xxs[4] = allocationLength
rq = ''.join([chr(xx) for xx in xxs])

Surely this is wrong?  A failure on my part to think in Python?

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
   cdb0 = '\x08' '\x01\x23\x45' '\x80' '\0'
 
  cdb = ''
  cdb += struct.pack('B', 0x08)
  cdb += struct.pack('I', skip)[-3:]
  cdb += struct.pack('BB', count, 0)

 The change from [-3:] to [1:] is a minor cosmetic improvement,

Ouch, [1:] works while sizeof I is 4, yes, but that's not what I meant,
more generally.

Something else I tried that doesn't work is:

skip = 0x12345 ; count = 0x80
struct.pack('8b3b21b8b8b', 0x08, 0, skip, count, 0)

That doesn't work, because in Python struct b means signed char, not
bit; and a struct repeat count adds fields, rather than making a field
wider.

But do you see what I mean?  The fields of this struct have 8, 3, 21,
8, and 8 bits.  The skip field has 21 bits, the count field has 8
bits, I'd like to vary both of those.

 why do you want to do that to concise working code???

cdb0 = '\x08' '\x01\x23\x45' '\x80' '\0'
works, but it's not parameterised.  Writing out the hex literal always
packs the same x12345 and x80 values into those 21 and 8 bit fields.

I see I can concisely print and eval the big-endian hex:

X08Read6 = 0x08
skip = 0x12345 ; count = 0x80
hex = '%02X' % X08Read6 + ('%06X' % skip) + ('%02X' % count) + '00'
''.join([chr(int(hex[ix:ix+2],0x10)) for ix in range(0,len(hex),2)])

But that's ugly too.  Maybe least ugly so far, if I bury the
join-chr-int-for-range-len-2 in a def.

Is there no less ugly way to say pack bits, rather than pack bytes, in
Python?

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
 Help, what did you mean by the question?

How does Python express the idea:

i) Produce the six bytes '\x08' '\x01\x23\x45' '\x80' '\0' at run-time
when given the tuple (0x08, 0x12345, 0x80, 0).

ii) Produce the six bytes '\x12' '\0\0\0' '\x24' '\0' when given the
tuple (0x12, 0, 0x24, 0).

iii) And so on.

So far, everything I write is ugly.  Help?

 Looks like you ignored ...

I guess you're asking me to leave the mystery of my question alone long
enough to show more plainly that indeed I am trying to make sense of
every word of every answer.

I guess I should do that in separate replies, cc'ed back into this same
thread.  Please stay tuned.

Thanks in advance, Pat LaVarre

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
 struct == Python struct module

 Struct module has (concise) codes B, H, I, Q for unsigned integers of
 lengths 1, 2, 4, 8, but does *not* have a code for 3-byte integers.

I thought that's what the manual meant, but I was unsure, thank you.

   1. Not as concisely as a one-byte struct code

 Looks like you ignored the first word in the sentence (Not).

I agree I have no confident idea of what your English meant.

I guess you're hinting at the solution you think I should find obvious,
without volunteering what that is.

Yes?  If so, then:

I guess for you a one-byte struct code is a 'B' provided as a format
character of the fmt parameter of the struct.pack function.

Yes?  if so, then:

You recommend shattering the three byte int:

skip = 0x012345 ; count = 0x80
struct.pack('6B', 0x08, skip  0x10, skip  8, skip, count, 0)

Except you know that chokes over:

DeprecationWarning: 'B' format requires 0 = number = 255

So actually you recommend:

def lossypack(fmt, *args):
return struct.pack(fmt, *[(arg  0xFF) for arg in args])
skip = 0x012345 ; count = 0x80
lossypack('6B', 0x08, skip  0x10, skip  8, skip, count, 0)

Yes?

  I guess you're asking me ...
  to show more plainly that indeed I am trying
  to make sense of every word of every answer

Am I helping?

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
  when talking the 1960's lingo
  ...
  X12Inquiry = 0x12
  xxs = [0] * 6
  xxs[0] = X12Inquiry
  xxs[4] = allocationLength
  rq = ''.join([chr(xx) for xx in xxs])

 It looks wrong (and a few other adjectives),

Ah, we agree, thank you for saying.

 Looks like little-endian 4-byte integer
 followed by 2-byte integer ... what's wrong with struct.pack(IH,
 X12Inquiry, allocationLength) 

Pack 'IH' doesn't match how the code that I'm refactoring thinks about
these things.

The people who wrote this stuff forty years ago were thinking of bit
fields - here bit lengths of 8 then 3 then 21 then 8 then 8 bits -
cheating only when the bit boundaries happened to hit byte boundaries.

Yes, as you describe in this example, I could cheat when the boundaries
happen to hit H or I boundaries as well, but then I'm still left coping
with the cases where the fields split on byte boundaries that are not H
or I boundaries, such as the example:

  skip = 0x123456; count = 0x80
  hi, lo = divmod(skip, 0x1)

 Does it do what you asked (one pack call instead of three)

One pack call, not three, yes.

Shatters the 3 byte int into 1 and 2 bytes by divmod of (0x + 1),
yes.

  I guess you're asking me ...
  to show more plainly that indeed I am trying
  to make sense of every word of every answer 

Am I helping?

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
Speaking as the OP, perhaps I should mention:

  [-3:] to [1:] is a minor cosmetic improvement

To my eye, that's Not an improvement.

'\x08' '\x01\x23\x45' '\x80' '\0' is the correct pack of (0x08,
0x12345, 0x80, 0) because '\x01\x23\x45' are the significant low three
bytes of a big-endian x12345, thus [-3:].

The [1:] fact that we can keep the 3 significant bytes by tossing
exactly 1 byte away after rounding the bit length of that digital
number up to the nearest power of two which happens to be 4 = 3 + 1 is
merely incidental - not of central significance.

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
Perhaps Python can't concisely say three-byte int ...

But Python can say six-nybble hex:

 import binascii
 cdb = binascii.unhexlify('%02X%06X%02X%02X' % (0x08, 0x12345, 0x80, 0))
 binascii.hexlify(cdb)
'080123458000'


Thanks again for patiently helping me find this.  A shortcut is:

http://docs.python.org/lib/genindex.html
search: hex

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


Re: pack a three byte int

2006-11-09 Thread p . lavarre
  ... Python can say six-nybble hex:
 
   import binascii
   cdb = binascii.unhexlify('%02X%06X%02X%02X' % (0x08, 0x12345, 0x80, 0))
   binascii.hexlify(cdb)
 '080123458000'

 The only problem I can see is that this code is endianness-dependent;
 the suggested versions using pack(...) not. But this may not be of
 concern to you.

Thanks for cautioning us.  I suspect we agree:

i) pack('...') can't say three byte int.
ii) binascii.hexlify evals bytes in the order printed.
iii) %X prints the bytes of an int in big-endian order.
iv) struct.unpack '' of struct.pack '' flips the bytes of an int
v) struct.unpack '' of struct.pack '' flips the bytes of an int
vi) [::-1] flips a string of bytes.

In practice, all my lil-endian structs live by the C/Python-struct-pack
law requiring the byte size of a field to be a power of two, so I can
use Python-struct-pack to express them concisely.  Only my big-endian
structs are old enough to violate that recently (since ~1972)
popularised convention, so only those do I construct with
binascii.unhexlify.

Often I wrap a big-endian struct in a lil-endian struct, but I'm ok
calling hexlify to make the big-endian struct and then catenating it
into the lil-endian struct, e.g., in the following cdb is big-endian
inside cbwBytes:

cbwBytes = struct.pack('IIIBBB',
cbw.dSignature, cbw.dTag, cbw.dDataTransferLength,
cbw.bmFlags, cbw.bLun, cbw.bCbLength,
) + cdb[0:cdbLength] + ('\0' * (0x10 - cdbLength))

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


to Doctest as SystemExit is to Python

2006-11-09 Thread p . lavarre
 From: http://docs.python.org/lib/doctest-soapbox.html ...
 Regression testing is best confined to dedicated objects or files ...

Can I somehow tell doctest that it's time to quit?

I ask because not all doctest examples are created equal.  Some
failures are catastrophic, making all subsequent failures at least
uninteresting, and maybe painfully slow.  Other failures are
negligible, making the print of any subsequent failure valuable.

So sys.exit() doesn't do what I mean: it raises SystemExit, but doctest
redefines the SystemExit exception to mean print a traceback, rather
than meaning to exit quietly after a noisily catastrophic failure,
exiting almost as if the doctest had passed.

And doctest.REPORT_ONLY_FIRST_FAILURE doesn't do what I mean: it prints
only the first failure, always, never the valuable subsequent failures.

Can doctest somehow be persuaded to do the right thing?  That is, to
exit after a catastrophic failure, but not after a negligible failure,
and not after an independent failure?

In the last Python I shipped, to get the effect of exit after
catastrophe, I actually faked a run of doctest:

print 'Expected:'
print '...'
print 'Got:'
print  + repr(result)
print '***Test Failed***'
sys.exit(-1)

Surely that's wrong?  Somehow not idiomatic Python?

Surely I can somehow tell doctest that my code has just realised,
sorry, it is time to quit?

Thanks in advance, Pat LaVarre

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


Re: how is python not the same as java?

2006-11-09 Thread p . lavarre
Jython exists.

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


pack a three byte int

2006-11-08 Thread p . lavarre
Can Python not express the idea of a three-byte int?

For instance, in the working example below, can we somehow collapse the
three calls of struct.pack into one?

 import struct

 skip = 0x123456 ; count = 0x80

 cdb = ''
 cdb += struct.pack('B', 0x08)
 cdb += struct.pack('I', skip)[-3:]
 cdb += struct.pack('BB', count, 0)

 print ' '.join(['%02X' % ord(xx) for xx in cdb])
08 12 34 56 80 00


I ask because I'm trying to refactor working code that is concise:

 cdb0 = '\x08' '\x12\x34\x56' '\x80' '\0'
 print ' '.join(['%02X' % ord(xx) for xx in cdb0])
08 12 34 56 80 00


Thanks in advance, Pat LaVarre

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


Re: call Mac gcc -framework from CTypes how

2006-10-25 Thread p . lavarre
 can I somehow call the IONotificationPortCreate in the
 Framework that Apple built instead,

$ cd /System/Library/Frameworks/
$ cd IOKit.framework/Versions/Current/
$ file IOKit
... Mach-O dynamically linked shared library ...
$ nm -m IOKit | grep IONotificationPortCreate
... (__TEXT,__text) external _IONotificationPortCreate
$

Looks like it will work.  Not named .dylib or .so, but correct `file`
type and relevant `nm -m` symbols.

Thanks all for help offline, especially Nlzero.com,

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


FAQ - How do I declare that a CTypes function returns void?

2006-10-25 Thread p . lavarre
Now at http://pyfaq.infogami.com/suggest we have:

FAQ: How do I declare that CTypes function returns void?

A: c_void = None is not doc'ed, but is suggested by:
 ctypes.POINTER(None)
class 'ctypes.c_void_p'


Remembering c_void = c_int from KR C often works, but if you say a
restype is c_int, then doctest's of that call will print an int, yuck.
If you say the restype is None, then those doctest's work: they print
nothing.

Hope this helps,

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


FAQ - How do I declare that a CTypes function returns unsigned char?

2006-10-25 Thread p . lavarre
Now at http://pyfaq.infogami.com/suggest we have:

FAQ: How do I declare that a CTypes function returns unsigned char?

A: c_uchar = ctypes.c_ubyte

This irregularity actually is doc'ed, it's just pointlessly annoying.

Hope this helps (and of course I trust you'll dispute if I'm nuts),

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


Re: call Mac gcc -framework from CTypes how

2006-10-25 Thread p . lavarre
  can I somehow call the IONotificationPortCreate in the
  Framework that Apple built instead,

 $ cd /System/Library/Frameworks/
 $ cd IOKit.framework/Versions/Current/
 $ file IOKit

Also ctypes.util.find_library('CoreFoundation')

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


Re: doctest quiet again before exit how

2006-10-18 Thread p . lavarre
 ... every run of doctest after the first is verbose ...
 *** DocTestRunner.merge: '__main__' in both testers; summing outcomes.

Another path to the same bug:

import doctest
print doctest.testfile(__file__, verbose=False)
print doctest.testfile(__file__, verbose=False)

Mystifiedly yours, rank Python newbie, Pat LaVarre

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


call Mac gcc -framework from CTypes how

2006-10-18 Thread p . lavarre
gcc -dynamiclib -framework CoreFoundation
builds C code for Mac OS X that I call from Py code.

Can I somehow get rid of the C, such as:

#include CoreFoundation/CoreFoundation.h
void const * kCFTypeDictionaryKeyCallBacks_p(void)
{
return kCFTypeDictionaryKeyCallBacks;
}

?

Thanks in advance, Pat LaVarre

P.S. In Windows, I duck tedium of this kind by finding the Dll that the
C compiler calls under the covers, e.g., the CreateFile of my Win C
code becomes a kernel32.CreateFileW call.

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


doctest quiet again before exit how

2006-10-16 Thread p . lavarre
Looks like every run of doctest after the first is verbose:

$ python2.5 quiet-once.py
(0, 0)
*** DocTestRunner.merge: '__main__' in both testers; summing outcomes.
(0, 0)
*** DocTestRunner.merge: '__main__' in both testers; summing outcomes.
(0, 0)
$
$ cat quiet-once.py
import doctest
print doctest.testmod()
print doctest.testmod()
print doctest.testmod()
$

How do I ask for another quiet run, before exiting the process?

Adding the arg verbose=False to the testmod call doesn't work.

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


ctypes.c_void_p(-1) might not be C return (void *) -1

2006-09-28 Thread p . lavarre
 Subject: Python CTypes translation of (pv != NULL)

And so then the next related Faq is:

Q: How should I test for ((void *) -1)?

A:

(pv == 0x) works often.

(ctypes.cast(pv, ctypes.c_void_p).value == 0x) works better.

((void *) -1) appears often in 32-bit Windows, behind the name
INVALID_HANDLE_VALUE of the type HANDLE that is def'ed as the type
PVOID that is def'ed as (void *).  -1 is x in 32-bit two's
complement.

The more complex comparison works more often because specifying a
restype doesn't decide the __class__ of the result.  For example, the
run below shows a type 'long' result value passed back from a C
routine that has a c_void_p restype:

$ gcc -o passlib.so -dynamiclib -Wall passlib.c
$ python results.py
True False c_void_p(4294967295L) class 'ctypes.c_void_p'
True True 4294967295 type 'long'
$
$ cat passlib.c
void * passback(int ii)
{
return (void *) ii;
}
$
$ cat results.py
from ctypes import *
passlib = cdll.LoadLibrary('./passlib.so')
passback = _fx = passlib.passback
_fx.restype = c_void_p
_fx.argtypes  = [c_int]
def test(pv):
print cast(pv, c_void_p).value == 0x,
print pv == 0x,
print pv, pv.__class__
test(c_void_p(-1))
test(passlib.passback(-1))
$ 

All true?  All bogus?  Partly bogus?  Curiously yours, Pat LaVarre

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


Re: Python CTypes translation of (pv != NULL)

2006-09-28 Thread p . lavarre
 Where did you find that?

Quoted in full from the gift:

Subject: Re: Python CTypes translation of (pv != NULL)
Date: Tue, 26 Sep 2006 11:48:52 +0200
Message-ID: [EMAIL PROTECTED]
http://groups.google.com/group/comp.lang.python/msg/f9f13e731ea3cad7

Cached and pondered just slightly before the gift of a complete
disavowal came after:

Subject: Re: Python CTypes translation of (pv != NULL)
Date: Wed, 27 Sep 2006 20:22:47 +0200
Message-ID: [EMAIL PROTECTED]
http://groups.google.com/group/comp.lang.python/msg/6584d964a70b7a2d

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


eval(source, {'builtins': {}}) archived as Faq

2006-09-28 Thread p . lavarre
Absent from http://www.python.org/doc/current/lib/built-in-funcs.html
but now copied to the Faq list of http://pyfaq.infogami.com/suggest,
from these clp archives:

///

Q: How can I tell Python to calculate what quoted strings and numbers
mean, without also accidentally accepting OS commands as input?

A: eval(source, {'builtins': {}})

Note: What eval may do to you remains as surprising as ever if you
mistype this idiom as: eval(source, {})

Note: This idiom makes sense of ordinary Python literals (such as 010,
0x8, 8.125e+0, and \x45ight).  This idiom also correctly interprets
simple literal expressions, such as 64**0.5.

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


Re: ctypes.c_void_p(-1) might not be C return (void *) -1

2006-09-28 Thread p . lavarre
 I've started a wiki page where I already added an entry about the above 
 question.
 Do you think the entry would have answered your question?
 http://starship.python.net/crew/theller/moin.cgi/CodeSnippets

As concise as I now can imagine, yes thank you.

I see the main point leads: The truth value of any NULL ctypes pointer
instance is False.  That angle neatly ducks my ongoing newbie
confusion over a null constructed in Python via c_void_p(0) being
different from a null constructed in C via return (void *) 0.

 ...
  And so then the next related Faq is:
 
  Q: How should I test for ((void *) -1)?

 For me, on Windows, c_void_p(-1).value is the same
 as c_void_p(0x).value, but it is -1 not 0x.

Different results at my desk.  Specifically, I see:

 from ctypes import * ; c_void_p(-1).value
4294967295L


in Mac OS X 10.4.7 Python 2.5 r25:51918 and Win XpSp2 Python 2.5
r25:51908.

 Worse, on 64-bit systems c_void_p(-1).value is 184467440737009661615, which
 is the same as 0x.
 So, to be portable, INVALID_HANDLE_VALUE should be defined like this:
 INVALID_HANDLE_VALUE = c_void_p(-1).value

Exactly what I should have written, yes, thank you.

And somewhat generalisable: c_void_p(0).value is None.

Maybe this is the thing that's been astonishing me: maybe C often does
return the .value of the pointer, rather than a new instance of the
POINTER class?

 and your test would become
 (ctypes.cast(pv, ctypes.c_void_p).value == INVALID_HANDLE_VALUE

Yes.

Mind you, typing out all that noise inspires me to ask, does (pv ==
INVALID_HANDLE_VALUE) give the wrong answer for any pv other than
c_void_p(-1)?  In other words, if by convention I get all my pointers
from C and never construct a pointer in Python except to take its
value, then can I safely write the more obvious translation of (pv ==
INVALID_HANDLE_VALUE)?

 PS: It is inconsistent that the .value of a c_void_p instance is signed on
 32-bit systems, and unsigned on 64-bit systems, but it seems we have to live
 with that.

I'm interested, if you can make the time to say more ...

 Fortunately, the c_void_p constructor accepts both signed and unsigned
 Python ints and longs, so it should be possible to work around that fact.

Good.

 ...
 might be better to use another wiki for ctypes, maybe the python.org one, for 
 this
 stuff.) ...

Could be.  Offline I heard we might have more pages coming soon.
Checking at random just now, I see http://wiki.python.org/moin/ is
immutable, so I guess I can't add A Wiki page to collect the Faq's
highlit by Clp to the Starting points  Asking for Help 
Wanted...

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


Re: Python CTypes translation of (pv != NULL)

2006-09-28 Thread p . lavarre
Future Googlers might like this thread to end with the Thomas Heller's
brief conclusive review:

/// Copied 2006-09-28 from
/// http://starship.python.net/crew/theller/moin.cgi/CodeSnippets

1.2 Check for NULL ctypes pointers

The truth value of any NULL ctypes pointer instance is False.

So, this C code

if (pv == NULL)
/* handle NULL pointer */
else
/* handle non-NULL pointer */

translates to this Python code

if not pv:
# handle NULL pointer
else:
# handle non-NULL pointer

The above is true for instances of c_void_p, c_char_p, c_wchar_p, and
POINTER(some_ctype).

///

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


Re: Python CTypes translation of (pv != NULL)

2006-09-27 Thread p . lavarre
  http://starship.python.net/crew/theller/ctypes/tutorial.html
 ...
 direct discussion only of how to construct null pointers,
 no discussion of how to test for them ...
 ...
 could be read to mean try ... == ... is ... False ... None ...

CTypes nulls fetched from a struct feel more like None than do CTypes
nulls fetched from elsewhere, astonishing me the Python newbie, e.g.:

$ python nulls.py
True True True None None
True True True None None
True False False None c_char_p(None)
$
$ cat nulls.py
from ctypes import *
class struct_aa(Structure):
_fields_ = [(chars, c_char_p)]
pv = None
print not pv, pv == None, pv is None, cast(pv, c_void_p).value, pv
pv = struct_aa().chars
print not pv, pv == None, pv is None, cast(pv, c_void_p).value, pv
pv = cast(c_void_p(0), c_char_p)
print not pv, pv == None, pv is None, cast(pv, c_void_p).value, pv
$

Possibly relevant, though grabbed at random, is:

/// PEP 8 -- Style Guide for Python Code
/// http://www.python.org/dev/peps/pep-0008/

... beware of writing if x when you really mean if x is not None --
e.g. when testing whether a variable or argument that defaults to None
was set to some other value.  The other value might have a type (such
as a container) that could be false in a boolean context!

///

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


Re: Python CTypes translation of (pv != NULL)

2006-09-27 Thread p . lavarre
 It says:

 NULL pointers have a False boolean value:
   null_ptr = POINTER(c_int)()
   print bool(null_ptr)
 False

Yes.

 That means that NULL pointers are considered False in a boolean
 expression (and you could assume that non-NULL pointers are True, as
 any other object in general),

I see this now that you show the clueless newbie me, yes thank you.
Except now by showing me here we have provoked the authority Thomas
Heller to say:

   Generally pointer instances have a False boolean value, so
   'if pv: '
   should work.  Except for c_void_p, c_char_p and c_wchar_p instances.

That English I do not understand.  Except how?

 so you can test a NULL pointer with a
 simple if ptr: whatever

Apparently, yes, except for the except above.

 --- cut ---
 from ctypes import *
 null_ptr = POINTER(c_int)()
 x=c_int(1234)
 other_ptr = pointer(x)

 if null_ptr: print null_ptr is not NULL
 else: print null_ptr is NULL

 if other_ptr: print other_ptr is not NULL
 else: print other_ptr is NULL
 --- cut ---

Yes.

 It's really the same as bool([])==False, bool(any_non_empty_list)==True:

 L = [1,2,3]
 while L:
print L.pop()

 You don't say:
 while bool(L)==True:

 (do you?)

Oh that's exactly how my newbie innocence led me astray.

Rather than working first to translate the C 'if pv', I worked first to
translate the C '(pv != NULL)',  and then I got lost (and as yet still
am lost) in newbie astonishment over some nulls feeling more like None
than others.

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


Re: Python CTypes translation of (pv != NULL)

2006-09-26 Thread p . lavarre
 Q: The C idea of (pv != NULL) is said most directly in Python ctypes
 how?

 Perhaps reading the ctypes tutorial? (both in the 2.5 docs and in
 http://starship.python.net/crew/theller/ctypes/tutorial.html)

Actually, no.  I see three answers or zero, depending on how you like
to count.

Yes that flat edition helps makes this clear, thank you - there I can
more easily grab an ordered list of all matches of text than in the
more prominent shadow:
http://docs.python.org/dev/lib/module-ctypes.html

I see direct discussion only of how to construct null pointers, no
discussion of how to test for them.  Specifically:

The hint { bool(null_ptr) == False } could be read to mean try ==
False, in the Pointers text.

The hint { (values, POINTER(c_int))] ... bar.values = None } could be
read to say try == None, in the Calling functions text.

The hint { if item.name is None } could be read to say try is None, in
the Accessing values exported from dlls text.

I'm such a Python newbie that I didn't know is None existed alongside
== None.

I guess I'll next dig into that along with the answer below from CTypes
author Thomas Heller.

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


Re: Python CTypes translation of (pv != NULL)

2006-09-26 Thread p . lavarre
Q: The C idea of (pv != NULL) ...
 
  CTypes tutorial ... == False ... == None ... is None ...

 Generally ... 'if pv: '  ... should work.
 Except for c_void_p, c_char_p and c_wchar_p instances.

Please can we give me an example of these exceptions?

Indeed those types are the _p types I use most often. Now here
'bool(pv)' and 'if pv' tell me that null is False and non-null is True,
for every kind of null or non-null that I know how to construct.

Is that mapping somehow not reliable across all instances? Or not
cross-platform?

You did mean to say that the Python fragments 'bool(pv)' and 'if pv'
somehow are not accurate translations of the C fragments 'pv != NULL'
and 'if pv'?  Something other kind of Python is?

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


Re: shlex.split != shlex.shlex get_token til eof

2006-09-26 Thread p . lavarre
Kindly offline the answer is:

(a) Python installation usually includes source, and thus
(b) UTSL:

$ pwd
C:\Python25\Lib\shlex.py
$ ...
$ pwd
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5
$ grep -A 5 def split shlex.py
def split(s, comments=False):
lex = shlex(s, posix=True)
lex.whitespace_split = True
if not comments:
lex.commenters = ''
return list(lex)
$

Voila the THREE undocumented ways that shlex.split has been overriding
the shlex.shlex defaults: nothing in wordchars, yes something in
whitespace_split, but also stuff in commenters and in posix.  (Of
these, the posix override is documented.)

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


Re: shlex.split != shlex.shlex get_token til eof

2006-09-26 Thread p . lavarre
Correspondingly, to the Faq Wiki I added:

/// http://pyfaq.infogami.com/installed-index

Q: Where is Python installed on my machine?

A: Binaries in bin/, source in lib/, doc somewhere else. Read the
module source when you find its doc incomplete.

On Linux, ...

On the Mac, straight from Apple:
/System/Library/Frameworks/Python.framework/Versions/*

On the Mac, straight from Apple:
/System/Library/Frameworks/Python.framework/Versions/*

On the Mac, downloaded yourself:
/Library/Frameworks/Python.framework/Versions/*

On Windows, downloaded yourself:
C:\Python*

///

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


Re: Reverse a String?

2006-09-25 Thread p . lavarre
 http://pyfaq.infogami.com/suggest
 is the right place to submit new entries.

Thanks for sharing the secret.  Now there I have added: Q: How can I
reverse a string, an array, a list, etc.

And to share our secret with future newbies, to
http://pyfaq.infogami.com/ I've added the suggestion:

///

How about here we add a bold:

If you have a suggested FAQ, click thru the Suggest New Articles link
and add a comment there. Don't choose the relevant category and then
discover you lack the privilege to comment there. Don't give up because
you have no ID: just invent one and register your e-mail and proceed.

///

 I would have hoped that the suggestion links on the first page would have 
 sent you

I actually did visit the right place - it appears listed as only the
fourth resource behind the label Suggest New Articles.  But the
only suggestions that were FAQs were from the effbot and submitted with
a font I didn't know how to create.  Also I had no sure idea of what
resource, category, and article meant in this context, so I could
barely decipher that only-apparently-English page.

Instead, because the site looks like a Wiki, I was trying to add my
suggested FAQ in place in the relevant category.  The place I picked
that choked irrecoverably was the Programming FAQ category, just
ahead of the How do I modify a string in place? question, in between
the How do I convert a string to a number? and How do I convert a
number to a string? questions.

Pat LaVarre

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


Python CTypes translation of (pv != NULL)

2006-09-25 Thread p . lavarre
Q: The C idea of (pv != NULL) is said most directly in Python ctypes
how?

A: We are of course supposed to write something like:

def c_not_null(pv):
return (ctypes.cast(pv, ctypes.c_void_p).value != None)

Yes?

Working from the doc, me the clueless newbie, I was slow to guess such
relevant truths as:

ctypes.c_void_p(0).value == None
ctypes.c_void_p(0) != ctypes.c_void_p(0)

Curiously yours, thanks in advance, Pat LaVarre

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


Re: shlex.split != shlex.shlex get_token til eof

2006-09-25 Thread p . lavarre
 I see shlex.split gives me what I want ...
 shlex.shlex surprisingly gives me something else ...
 I can get closer ... by hacking ...
 .wordchars += .+-

Kindly offline I was told,

Try patching .whitespace_split = True instead.  Compare:

shlex.split(//./PhysicalDrive9 //./Cdrom9 //./Tape9 //./A:)

lex = shlex.shlex(//./PhysicalDrive9 //./Cdrom9 //./Tape9 //./A:)
lex.whitespace_split = True
list(lex)

Why and how often this patch makes shlex.shlex and shlex.split agree, I
still don't know - but for these specific examples, it works.

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


Re: Reverse a String?

2006-09-24 Thread p . lavarre
 http://pyfaq.infogami.com/

Tell me more?

Clueless newbie me, thru this door I'm at three deaths and counting.
Does that Py Faq Wiki have a sandbox a la alt.test, and/or a tutorial?

// Death One:

http://pyfaq.infogami.com/_account/in?path=/
requires me to create a persisting ID between 3 and 20 letters and
numbers, i.e., not an e-mail address.  Grumble, ok.

// Death Two:

http://pyfaq.infogami.com/programming-index
kicked back comment How can I reverse a string, an array, a list,
etc.? with Sorry, that looks like spam. I'm not going to post it.

// Death Three:

Search infogami in clp gives me:
http://howto.infogami.com/createnewpages
which suggests:
http://pyfaq.infogami.com/how-do-i-reverse
which dies at Sorry, that page could not be found.

//

Next clue?

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


Re: ruby %w equivalent

2006-09-24 Thread p . lavarre
 is there a python equivalent for the ruby %w operator?
 %w{a b c} creates an array with strings a, b, and c in ruby...

The expression 'a b c'.split() creates the ['a', 'b', 'c'] list of str,
if that helps.

Also dir('a b c') briefly lists much of what
http://docs.python.org/lib/string-methods.html explains.

Also Google was curiously resistant to telling me where Ruby's %w is
documented.

Pat LaVarre

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


Re: help with debugging a ctypes problem

2006-09-23 Thread p . lavarre
 help figuring out how to debug ... ctypes ...
 a commercial dll.  A certain function takes five arguments, foo(a, b, c, d, 
 e).
 Can I view the appropriate stack? ... Any other ideas or advice?  etc?

Did you call the foo of _cdecl ctypes.cdll or the foo of _stdcall =
ctypes.windll?

What is the sizeof each argument type?  Preferably fetched by compiling
some C to printf them?

Would it help to call C in another Dll to return the stack pointer, so
Python could print the stack?

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


Re: Reverse a String?

2006-09-23 Thread p . lavarre
That 'foo'[::-1] is the Python reverse string idiom I'll try here
forward, thanks.

Also '.h.e.l.l.o'[1::2] to pick out every second char, etc., thanks.

Three footnotes:

1) Reverse string isn't yet in http://www.python.org/doc/faq/

2) Google Groups searches here yesterday instead pushed me towards the
less concise:

def reverse(chars):
aa = array.array('c', chars)
aa.reverse()
return aa.tostring()

3) I went looking when first I found time to rethink what I had been
running this past year:

def reverse(chars):
ochars = ''
beyond = len(chars)
for ix in range(beyond):
ochars += chars[beyond - 1 - ix]
return ochars

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


shlex.split != shlex.shlex get_token til eof

2006-09-22 Thread p . lavarre
How can I instantiate shlex.shlex to behave like shlex.split does?

I see shlex.split gives me what I want:

import shlex
print shlex.split(1.2e+3)[0]  # 1.2e+3

But every doc'ed instantiation of shlex.shlex surprisingly gives me
something else:

s1 = shlex.shlex(1.2e+3, None, False)
print s1.get_token()# 1
s2 = shlex.shlex(1.2e+3, None, True)
print s2.get_token()# 1

I can get closer to the shlex.split state by hacking the shlex.shlex
state before the first get_token invocation:

s3 = shlex.shlex(1.2e+3, None, True)
s3.wordchars += .+-
print s3.get_token()# 1.2e+3

But how can I know if I've discovered the last hack that I need?

I ask because I'm patching a cmd.Cmd app to tweak the interpretation of
tokens. It was calling shlex.split. My class instead subclasses
shlex.shlex to catch the context of instream.tell().  That context lets
me see the significant differences between such sources as r'0xAB' and
r'0xAB'.

Can I somehow override just what I mean to change in shlex.split, and
not more?

Curiously yours, thanks in advance, Pat LaVarre
http://docs.python.org/lib/module-shlex.html
2.4.2#67 Python, 2.3.5#1 Python

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


Re: shlex.split != shlex.shlex get_token til eof

2006-09-22 Thread p . lavarre
 shlex.split gives me what I want ...
 every doc'ed instantiation of shlex.shlex ... gives me something else ...

Aye, the discrepancies are gross  legion - presumably astonishing only
newbies like me.

Here's a more dramatic example:

 import shlex
 shlex.split(//./PhysicalDrive9 //./Cdrom9 //./Tape9 //./A:)[0]
'//./PhysicalDrive9'
 shlex.shlex(//./PhysicalDrive9 //./Cdrom9 //./Tape9 //./A:, , 
 True).get_token()
'/'


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