Re: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 140)
Lord... forgive the Holy Roller, spammers for they know not what they do -- http://mail.python.org/mailman/listinfo/python-list
Re: inheriting a large python code base
Look at the algorithms and see if there are faster ways. Great advice with the comments of writing test cases, getting into version control, taking passes through the code with tools, understanding what is slow and why it is considered slow. Then you should invest the time to understand the internal logic and the algorithms. Understand the performance O(N log N), O(N^2), O(2^N). See if there are better algorithms that should be used - is there an O(N). Implement that algorithm, test, then compare performance. Finally optimize the coding constructs. Depending on how long your program takes (a few milli-secs, a few secs, a few hours, a few days), optimized coding constructs may make no measurable difference. Finding better algorithms will. But a better algorithm changing code from 2 milli-secs to 1 milli-sec is only useful in specific environments - so it may not be worth your effort. Understand the performance of the code and the environment it is executed in. That is how I have gone about it type of work. -- https://mail.python.org/mailman/listinfo/python-list
Generating header information using ElementTree
Hi there, I'm only new to Python so please bear with me. I using ElementTree to generate an XML file that will reference a DTD and an XSL file. The header information I want at the start of the file is as follows: How do you add this header information to the tree as I can't find any documentation or examples on how you can do this. Any help would be appreciated. Thank you and good luck. Craig Williamson -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating header information using ElementTree
Fredrik Lundh wrote: > Craig wrote: > > > I'm only new to Python so please bear with me. I using ElementTree to > > generate an XML file that will reference a DTD and an XSL file. The > > header information I want at the start of the file is as follows: > > > > > > > > > > > > How do you add this header information to the tree > > to the file, you mean? use print. > > Thanks for the quick response. Here is the code I am using to manually write to the file is: outFile = open("record.xml", 'w') outFile.write = ("\n") outFile.write = ("\n") outFile.write = ("\n") outFile.close() When I run the code I get the following error message: Traceback (most recent call last): File "bob-xml.py", line 189, in main() File "bob-xml.py", line 173, in main outFile.write = ("\n") AttributeError: 'file' object attribute 'write' is read-only What am I doing wrong here? If anyone could help that would be appreciated. Thanks again. Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating header information using ElementTree
Diez B. Roggisch wrote: > Craig schrieb: > > Fredrik Lundh wrote: > > > >> Craig wrote: > >> > >>> I'm only new to Python so please bear with me. I using ElementTree to > >>> generate an XML file that will reference a DTD and an XSL file. The > >>> header information I want at the start of the file is as follows: > >>> > >>> > >>> > >>> > >>> > >>> How do you add this header information to the tree > >> to the file, you mean? use print. > >> > >> > > > > Thanks for the quick response. Here is the code I am using to manually > > write to the file is: > > > > outFile = open("record.xml", 'w') > > outFile.write = ("\n") > > outFile.write = (" > href=\"test.xsl\"?>\n") > > outFile.write = ("\n") > > outFile.close() > > > > When I run the code I get the following error message: > > > > Traceback (most recent call last): > > File "bob-xml.py", line 189, in > > main() > > File "bob-xml.py", line 173, in main > > outFile.write = ("\n") > > AttributeError: 'file' object attribute 'write' is read-only > > > > What am I doing wrong here? If anyone could help that would be > > appreciated. Thanks again. > > write is a method, not a property. > > outFile.write("whatever") > > is the way to go... > > Diez Great. Got that sorted. The problem I have now is that some of the XML data is not copied across to the file when I have the text information included. The number of characters that is lost is equal to the number of characters that is in the block of text I entered before. The code I am using is: def WriteXMLRecord ( record, XMLFileBaseName, root): RecordName = SubElement(root, "Log") #iterate through all the fields in the record for key in record: # write the key and its data test = SubElement(RecordName, key) test.text = str(record[key]) tree = ElementTree(root) tree.write(XMLFileBaseName) def main(): outFile = open("record.xml", 'w') outFile.write(""" \n\n""") root = Element("Log") WriteXMLRecord(data1, "record.xml", root) WriteXMLRecord(data2, "record.xml", root) WriteXMLRecord(data3, "record.xml", root) outFile.close() Any help would be appreciated. Thanks and good luck. Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating header information using ElementTree
John Machin wrote: > Craig wrote: > > > Great. Got that sorted. The problem I have now is that some of the > > XML data is not copied across to the file when I have the text > > information included. The number of characters that is lost is equal > > to the number of characters that is in the block of text I entered > > before. The code I am using is: > > > > def WriteXMLRecord ( record, XMLFileBaseName, root): > > RecordName = SubElement(root, "Log") > > #iterate through all the fields in the record > > for key in record: > > # write the key and its data > > test = SubElement(RecordName, key) > > test.text = str(record[key]) > > tree = ElementTree(root) > > tree.write(XMLFileBaseName) > > I'm guessing, based on reading the docs for the write method, that you > should be using the file handle, rather than the file name, if the file > is already opened. So (1) change the name of the 2nd arg to > XMLFileHandle or somesuch, and in the caller, use outFile (the handle) > instead of "record.xml". > > > > > def main(): > > outFile = open("record.xml", 'w') > > outFile.write(""" > > > > \n\n""") > > > > root = Element("Log") > > WriteXMLRecord(data1, "record.xml", root) > > WriteXMLRecord(data2, "record.xml", root) > > WriteXMLRecord(data3, "record.xml", root) > > outFile.close() > > > HTH, > John Great. Got it. Thanks so much for all your help. Craig -- http://mail.python.org/mailman/listinfo/python-list
ElementTree xmlns:xsi question
Hi there, I'm generating an XML script using ElementTree which has the following attributes in the root element: http://www.w3.org/2001/XMLSchema-instance"; xsi:noNamespaceSchemaLocation="code/can.xsd"> My python script I have written is: root = Element("CANmessages", xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";, xsi:noNamespaceSchemaLocation="code/can.xsd") Obviously there is a syntax error inregard to the colons in the attribute names. I have to have the xsi attributes in there otherwise the XML won't work correctly. What can I do to make the code correct and the output being 100% correct as well. Any help would be greatly appreciated. Craig -- http://mail.python.org/mailman/listinfo/python-list
Open 16-bit/24-bit windows bitmap using PIL
Hi there, I'm trying to open a 256-colour windows BMP and a 24-bit windows BMP with PIL usiing the following command: Image.open("image.bmp") When I try and open the 24-bit BMP the error I get is: Traceback (most recent call last): File "", line 1, in im = Image.open("lightbulb.bmp") File "C:\Python25\lib\site-packages\PIL\Image.py", line 1730, in open return factory(fp, filename) File "C:\Python25\lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 96, in _bitmap raise IOError("Unsupported BMP header type (%d)" % len(s)) IOError: Unsupported BMP header type (108) When I try and open the 256-colour BMP the error I get is: Traceback (most recent call last): File "", line 1, in im = Image.open("lightbulb2.bmp") File "C:\Python25\lib\site-packages\PIL\Image.py", line 1730, in open return factory(fp, filename) File "C:\Python25\lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 120, in _bitmap raise IOError("Unsupported BMP compression (%d)" % compression) IOError: Unsupported BMP compression (1) I can open a windows monochrome bitmap fine using PIL but the colour options are more desirable. I am using Windows 2000 if that is any help and I am saving the different BMP's using Microsoft Paint. If you could help that would be great. Craig -- http://mail.python.org/mailman/listinfo/python-list
Convert PNG files to BMP files using PIL
Hi there, I'm trying to convert some PNG files to bitmap files which can then be converted to X11 bitmaps using the im.tobitmap() function. But the error I get when using the im.tobitmap() function on the PNG files I get the following error: >>> im.tobitmap() Traceback (most recent call last): File "", line 1, in im.tobitmap() File "C:\Python25\Lib\site-packages\PIL\Image.py", line 545, in tobitmap raise ValueError("not a bitmap") ValueError: not a bitmap >>> Can this be done using PIL or is there another library that can be used to fulfil the task. If you could let me know that would be great. Thanks and good luck. Craig -- http://mail.python.org/mailman/listinfo/python-list
Opening colour BMPs with PIL
Hi there, I'm trying to open colour BMPs using PIL and I'm getting the following errors. Opening a 16 colour BMP I get: >>> im = Image.open("image.bmp") Traceback (most recent call last): File "", line 1, in im = Image.open("lightbulb2.bmp") File "C:\Python25\Lib\site-packages\PIL\Image.py", line 1901, in open return factory(fp, filename) File "C:\Python25\Lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\python25\lib\site-packages\PIL\BmpImagePlugin.py", line 120, in _bitmap raise IOError("Unsupported BMP compression (%d)" % compression) IOError: Unsupported BMP compression (2) >>> Opening a 256 colour BMP I get: >>> im = Image.open("image.bmp") Traceback (most recent call last): File "", line 1, in im = Image.open("image.bmp") File "C:\Python25\Lib\site-packages\PIL\Image.py", line 1901, in open return factory(fp, filename) File "C:\Python25\Lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\python25\lib\site-packages\PIL\BmpImagePlugin.py", line 120, in _bitmap raise IOError("Unsupported BMP compression (%d)" % compression) IOError: Unsupported BMP compression (1) >>> Opening a 24 bit colour BMP I get: >>> im = Image.open("image.bmp") Traceback (most recent call last): File "", line 1, in im = Image.open("image.bmp") File "C:\Python25\Lib\site-packages\PIL\Image.py", line 1901, in open return factory(fp, filename) File "C:\Python25\Lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\python25\lib\site-packages\PIL\BmpImagePlugin.py", line 96, in _bitmap raise IOError("Unsupported BMP header type (%d)" % len(s)) IOError: Unsupported BMP header type (108) >>> I am using Windows XP with Python 2.5. I can open monochrome BMPs fine but I don't want that. If you could help that would be greatly appreciated. Thanks and good luck. Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: Opening colour BMPs with PIL
Fredrik Lundh wrote: > Craig wrote: > > > I'm trying to open colour BMPs using PIL and I'm getting the following > > errors. > > what program did you use to produce those BMP files? can you prepare > reasonably small samples using the same program and post them somewhere? > > Thanks for the reply. I'm using Microsoft Paint to create the files so that's most likely the problem (surprise, surprise). I found that by using GIMP to create them has no problems with opening BMP images. I'll just keep using GIMP instead. -- http://mail.python.org/mailman/listinfo/python-list
X11 bitmap image conversion problem
Hi there, This could be a curly question. When I created the x11 bitmap image using the im.tobitmap() function I found out later that the display information in the array is big endian (I think) but I want little endian. Basically if an image byte in the X11 format is 0001 (0x3D), I want 1000(0xBC). Is there an easy way to flip the bits after the im.tobitmap() conversion has been done or do I have to find another way? If you could help that would be greatly appreciated. Thanks and good luck. Craig -- http://mail.python.org/mailman/listinfo/python-list
Mirror imaging binary numbers
Hi there, I'm trying to switch binary numbers around so that the MSB becomes the LSB etc. Is there an easy way of doing this as I can't seem to find anything. If you could help that would be great. Thanks and good luck. Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: Mirror imaging binary numbers
Matimus wrote: > Craig wrote: > > I'm trying to switch binary numbers around so that the MSB becomes the > > LSB etc. > > What do you mean 'binary numbers'? They are all binary. If you mean the > int type, they are 32 bits long and there are 16 bits between the MSB > and LSB (Most/Least Significant _Byte_). Do you want to swap the most > significant word with the least significant word? Swap the most > significant nibble with the least significant nibble in a Byte? Or do > you want to completely reverse the bit order? > > To swap nibbles in a byte: > > reverseVal = (val & 0xf) << 4 | (val & 0xf0) >> 4 > > Basicly you are going to need to use the bit operators (|,&, << and >>) > to get what you need. If you could be more specific perhaps I could be > of more help. Thanks so much for the response. I have an array of individual bytes which will eventually make up a binary bitmap image that is loaded onto an LCD screen (1 = black dot, 0 = white dot). At the moment each byte is reversed to what it should be (completely reverse the bit order): e.g 0001 should be 1000, 11001100 should be 00110011, etc. It is not an int problem as such, it is more a bit level swap if you get what I mean. If you could help that would be great. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mirror imaging binary numbers
Terry Reedy wrote: > "Craig" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > Thanks so much for the response. I have an array of individual bytes > > which will eventually make up a binary bitmap image that is loaded onto > > an LCD screen (1 = black dot, 0 = white dot). At the moment each byte > > is reversed to what it should be (completely reverse the bit order): > > e.g 0001 should be 1000, 11001100 should be 00110011, etc. It > > is not an int problem as such, it is more a bit level swap if you get > > what I mean. If you could help that would be great. > > Using any of the solutions posted by others, I would first make a 256 byte > string in which each byte was the bit reversed version of its index. > > IE, bitrev = "\x00\x80\x40\xC0.\xFF" > > Then your actual image processing is a simple, quick lookup for each byte. > > Terry Jan Reedy Thanks for all your great help guys. They work great. -- http://mail.python.org/mailman/listinfo/python-list
Adding extra modules to a Pyinstaller build
Hello all: I need to add several Python standard modules to a Pyinstaller project. The modules are not (and cannot be) explicitly imported in my project script, so is there a way to add them to my .spec file in order to allow Pyinstaller to search for them in PYTHONPATH and add them to the project? Regards, Craig -- http://mail.python.org/mailman/listinfo/python-list
Need help calling a proprietary C DLL from Python
I use a proprietary dll from Software Source (vbis5032.dll). I have successfully used it from Visual Basic 6, Fujitsu Cobol and from Perl. I would now like to use it from Python. The following is the C++ prototype for one of the functions: short FAR PASCAL VmxOpen(BSTR*Filespec, LPSHORT lpLocatorSize, LPSHORT lpOmode, LPHANDLE lphwmcb, BSTR*Password); The following is some Python code I put together: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf sprintf = libc.sprintf print "\nVB/ISAM testing:" fName = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) printf ("fName = \x22%slx22\n", fName) pw = windll.oleaut32.SysAllocStringByteLen("XYZ\x00", 4) printf ("pw = \x22%slx22\n", pw) CacheSize = c_long(0) OpenMode = c_long(3) vHandle = c_long(0) p_vHandle = pointer(vHandle) X = c_long(0) printf ("Before - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." X = windll.vbis5032.VmxOpen(byref(fName), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(pw)) printf ("After - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) exit(0) The following is the output from the Python code: VB/ISAM testing: fName = "s:\msdb\dcodlx22 pw = "XYZlx22 Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\test3.py", line 19, in X = windll.vbis5032.VmxOpen(byref(fName), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(pw)) TypeError: byref() argument must be a ctypes instance, not 'int' I am neither a C++ nor a Python expert, but having already used this dll from other languages, I know this should be possible. I am sure it is just my lack of knowledge of Python. Can anyone assist with this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 20, 2:29 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > On 20 Mar, 19:09, Craig <[EMAIL PROTECTED]> wrote: > > The culprit i here: > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > This binds these names to Python ints, but byref expects C types. > > Also observe that CacheSize and OpenMode should be c_short. I changed CacheSize and OpenMode to c_short, and commented out that line producing the "Before" message, and the output is the same. Further "tinkering" revealed that it is the byref on the fName and pw that are causing the error. The entire problem appears to be around the production of a BSTR and the passing of pointers (byref) to the BSTR. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 20, 2:38 pm, Craig <[EMAIL PROTECTED]> wrote: > On Mar 20, 2:29 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > > > On 20 Mar, 19:09, Craig <[EMAIL PROTECTED]> wrote: > > > The culprit i here: > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > This binds these names to Python ints, but byref expects C types. > > > Also observe that CacheSize and OpenMode should be c_short. > > I changed CacheSize and OpenMode to c_short, and commented out that > line producing the "Before" message, and the output is the same. > > Further "tinkering" revealed that it is the byref on the fName and pw > that are causing the error. > > The entire problem appears to be around the production of a BSTR and > the passing of pointers (byref) to the BSTR. Can anyone shed some light on how to work with BSTR's? -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 20, 4:55 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote: > On Thu, Mar 20, 2008 at 3:42 PM, Craig <[EMAIL PROTECTED]> wrote: > > > On Mar 20, 2:38 pm, Craig <[EMAIL PROTECTED]> wrote: > > > On Mar 20, 2:29 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > > > > > On 20 Mar, 19:09, Craig <[EMAIL PROTECTED]> wrote: > > > > > The culprit i here: > > > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > > > This binds these names to Python ints, but byref expects C types. > > > > > Also observe that CacheSize and OpenMode should be c_short. > > > > I changed CacheSize and OpenMode to c_short, and commented out that > > > line producing the "Before" message, and the output is the same. > > > > Further "tinkering" revealed that it is the byref on the fName and pw > > > that are causing the error. > > > > The entire problem appears to be around the production of a BSTR and > > > the passing of pointers (byref) to the BSTR. > > > Can anyone shed some light on how to work with BSTR's? > > Since you didn't tell ctypes about the function signature, it assumes > it returns int and gives you a python int. Provide a function > signature (c_void_p should work for BSTR) for both functions and you > should have an easier time of it. > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list Thanks Chris. I changed X to a c_short also, and modified the example as suggested: X = c_short(0) X = windll.vbis5032.VmxOpen(byref(c_void_p(fName)), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(c_void_p(pw))) printf ("After - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) And, this is what printed: After - X = 4325376, CacheSize = 0, OpenMode = 3, vHandle = 17586736 The printf shows that the values of X and vHandle have changed, but I am not sure it is working properly as X should be a MUCH smaller number (< 256). I would have expected a 0 (VIS_OK), 13 (VIS_DOS_ERROR) or 14(VIS_DISK_ERROR) if it had worked. Next, I changed: fName = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", 13) so that I knew it would not find the file, and got: After - X = 2555917, CacheSize = 0, OpenMode = 3, vHandle = 0 The vHandle staying 0 tells me that it did not find the file, but the value of X seems random. Based on the original C prototype, what am I doing wrong so that the return from the call to vbis5032 is not "usable"? -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 20, 6:26 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > On 20 Mar, 19:09, Craig <[EMAIL PROTECTED]> wrote: > > > The following is the C++ prototype for one of the functions: > > short FAR PASCAL VmxOpen(BSTR*Filespec, > > LPSHORT lpLocatorSize, > > LPSHORT lpOmode, > > LPHANDLE lphwmcb, > > BSTR*Password); > > import ctypes > import comtypes > > LPBSTR = ctypes.POINTER(comtypes.BSTR) > HANDLE = ctypes.POINTER(ctypes.POINTER(ctypes.c_long)) > LPHANDLE = ctypes.POINTER(HANDLE) > LPSHORT = ctypes.POINTER(ctypes.c_short) > > VmxOpen = ctypes.windll.vbis5032.VmxOpen > VmxOpen.restype = c_short > VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] > > Filespec = comtypes.BSTR('blahblahblah') > LocatorSize = ctypes.c_short(256) > Omode = ctypes.c_short(1) > hwmcb = HANDLE() > Password = comtypes.BSTR('blahblahblah') > > res = WmxOpen( byref(Filespec), byref(LocatorSize), >byref(Omode), byref(hwmcb), byref(Password) ) > > or if that fails: > > pFilespec = ctypes.pointer(Filespec) > pLocatorSize = ctypes.pointer(LocatorSize) > pOmode = ctypes.pointer(Omode) > phwmcb = ctypes.pointer(hwmcb) > pPassword = ctypes.pointer(Password) > > res = WmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) sturlamolden, thanks for the input. I had to change your example to the following to get it to run: from ctypes import * import comtypes LPBSTR = POINTER(comtypes.BSTR) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) VmxOpen = windll.vbis5032.VmxOpen VmxOpen.restype = c_short VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] Filespec = comtypes.BSTR('s:\\msdb\\dcod') LocatorSize = c_short(0) Omode = c_short(3) hwmcb = HANDLE() Password = comtypes.BSTR('GU32ASBURYPARK60A42A20') res = VmxOpen( byref(Filespec), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(Password) ) print "res = " + str(res) pFilespec = pointer(Filespec) pLocatorSize = pointer(LocatorSize) pOmode = pointer(Omode) phwmcb = pointer(hwmcb) pPassword = pointer(Password) res = VmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) print "res = " + str(res) After changing the assignment for Password to the correct value, both calls to VmxOpen returned a status of 20, which indicates an invalid password. I received a direct email from someone, and I came up with the following after implementing his advice: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf FileSpec = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) printf ("FileSpec = \x22%s\x22\n", FileSpec) Password = windll.oleaut32.SysAllocStringByteLen("XYZ\x00", 4) printf ("Password = \x22%s\x22\n", Password) LocatorSize = c_short(0) Omode = c_short(3) hwmcb = c_long(0) X = c_short(0) printf ("Before - X = %#x (%d), LocatorSize = %d, Omode = %d, hwmcb = %d\n", X, X, LocatorSize, Omode, hwmcb) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." X.value = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) printf ("After - X = %#x (%d), LocatorSize = %d, Omode = %d, hwmcb = %d \n", X, X, LocatorSize, Omode, hwmcb) windll.oleaut32.SysFreeString(FileSpec) windll.oleaut32.SysFreeString(Password) This returned a correct value in X of 0 (VIS_OK). When I changed: FileSpec = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) to: FileSpec = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", 13) I got the expected X value of 13 (VIS_DOS_ERROR). As was pointed out to me, and not really to my surprise as I am still very "green" at Python, the correct call was: X.value = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) instead of: X = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) Thank you to everyone for their help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 21, 4:04 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Thu, 20 Mar 2008 16:50:18 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > > > I received a direct email from someone, and I came up with the > > following after implementing his advice: > > Just for completeness... I'm the "someone"... And this is a copy of > the message in question: > > > > > > > Please forgive my going direct -- I do not have Usenet posting > > privileges from work. > > > From your message: > > > -=-=-=-=-=-=- > > And, this is what printed: > > After - X = 4325376, CacheSize = 0, OpenMode = 3, vHandle = 17586736 > > > The printf shows that the values of X and vHandle have changed, but I > > am not sure it is working properly as X should be a MUCH smaller > > number (< 256). I would have expected a 0 (VIS_OK), 13 (VIS_DOS_ERROR) > > or 14(VIS_DISK_ERROR) if it had worked. > > > Next, I changed: > > fName = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", > > 13) > > so that I knew it would not find the file, and got: > > After - X = 2555917, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > The vHandle staying 0 tells me that it did not find the file, but the > > value of X seems random. > > -=-=-=-=-=-=-=- > > > X does NOT seem random to me -- but I took the effort to render it > > in hexadecimal. X seems to be coming back as a 32-bit integer. Your <256 > > code appears to be in the second half of that integer -- observe: > > > >>> "%8.8X" % 4325376 > > '0042' > > >>> "%8.8X" % 2555917 > > '0027000D' > > > Also observe that x0D => 13 decimal... your stated "VIS_DOS_ERROR" > > code. > > > >>> 0x0042 > > 66 > > >>> 0x0027 > > 39 > > >>> 0x000d > > 13 > > > I have no explanation for the leading 16-bits... But under the > > rules of Python, "X = ..." is commonly a rebinding operation, so presetting > > X as a ctypes short integer may not be having any effect (I suspect those > > are more important for calls where the input parameters need to be mutable > > and of a known C format). > > > >>> import ctypes > > >>> x = ctypes.c_short(123) > > >>> dir(x) > > ['__class__', '__ctype_be__', '__ctype_le__', '__ctypes_from_outparam__', > > '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', > > '__init__', '__module__', '__new__', '__nonzero__', '__reduce__', > > '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', > > '_as_parameter_', '_b_base_', '_b_needsfree_', '_objects', '_type_', > > 'value'] > > > >>> x > > c_short(123) > > >>> x.value > > 123 > > > >>> x.value = 13 > > >>> x > > c_short(13) > > > Note that in this I have assigned to the "value" component of a > > c_short object. Plugging in your results values: > > > >>> x.value = 4325376 > > >>> x > > c_short(0) > > >>> x.value = 2555917 > > >>> x > > c_short(13) > > > Gives... ta da... 0 and 13 respectively. Perhaps you should, after creating > > X as a c short object, be assigning to the value, not to the object... > > > X.value = windll. ... > > > {Replies are being directed to my home email} > > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ Sorry, I wasn't trying to exclude any credit from Dennis, I just wasn't sure if he wanted to be listed. As it turns out, I am running into more of these BSTR and pointer problems. I have moved on to the next function to convert: short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS lpvstats); which uses a structure: typedef struct tagVSTATS { LONG nrecords; WORD gps_used; WORD gps_unused; WORD max_key_len; LONG grp_size; WORD init_alloc; WORD cr_opts; WORD
Re: Need help calling a proprietary C DLL from Python
On Mar 22, 3:13 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Fri, 21 Mar 2008 23:21:48 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > Sorry, I wasn't trying to exclude any credit from Dennis, I just > > wasn't sure if he wanted to be listed. > > As responded to elsewhere -- it was more a case of minimizing the > "non-work" traffic on my work email address... > > > > > This is what I have tried: > > > > > LPBSTR = POINTER(c_void_p) > > > > > And, on the last variation of this, this function needs to receive > > BSTR values passed back from the dll: > > short FAR PASCAL VmxGet(LPHANDLE lpDatasetNumber, LPSHORT lpSecIndex, > > LPSHORT lpOption, BSTR *SrchKey, > > BSTR *SecKey, BSTR *PriKey, LPSTR > > lpTypeDef); > > SrchKey is provided by me, SecKey and PriKey are returned by the dll, > > and TypeDef is defined by me and filled by the dll. > > > For this, I have added: > > VmxGet = windll.vbis5032.VmxGet > > VmxGet.restype = c_short > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, > > LPBSTR] > > Remember that Python strings are immutable... Also note that the > signature you give above seems to differentiate between passing a > pointer variable LPSTR (ie; lpTypeDef is just 4-bytes which will/should > contain the address pointing to the real string) and passing the address > of the first byte of a string buffer BSTR (*PriKey is the same as > &PriKey[0] -- but PriKey itself has to be a sequence of characters or an > empty buffer allocated to hold them). > > From the ctypes documentation: >http://docs.python.org/lib/node453.html > > """ > Assigning a new value to instances of the pointer types c_char_p, > c_wchar_p, and c_void_p changes the memory location they point to, not > the contents of the memory block (of course not, because Python strings > are immutable): > > >>> s = "Hello, World" > >>> c_s = c_char_p(s) > >>> print c_s > > c_char_p('Hello, World')>>> c_s.value = "Hi, there" > >>> print c_s > > c_char_p('Hi, there') > > >>> print s # first string is unchanged > Hello, World > > You should be careful, however, not to pass them to functions expecting > pointers to mutable memory. If you need mutable memory blocks, ctypes > has a create_string_buffer function which creates these in various ways. > The current memory block contents can be accessed (or changed) with the > raw property; if you want to access it as NUL terminated string, use the > value property: > > >>> from ctypes import * > >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to > >>> NUL bytes > >>> print sizeof(p), repr(p.raw) > 3 '\x00\x00\x00' > >>> p = create_string_buffer("Hello") # create a buffer containing a NUL > >>> terminated string > >>> print sizeof(p), repr(p.raw) > 6 'Hello\x00' > >>> print repr(p.value) > 'Hello' > >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer > >>> print sizeof(p), repr(p.raw) > > 10 'Hello\x00\x00\x00\x00\x00'>>> p.value = "Hi" > >>> print sizeof(p), repr(p.raw) > > 10 'Hi\x00lo\x00\x00\x00\x00\x00' > > """ > > Drawback -- it looks like you may have to preset the size of the > buffer... > > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ That is not really a drawback. Pretty much everything is fixed-length anyway. I guess I am having trouble with the whole immutable thing. And, the pointers too. Anyway, I have the following for "types": LPBSTR = POINTER(c_void_p) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) LPVSTATS = POINTER(c_void_p) c_string = c_char_p LPSTR = c_string I guess passing a structure is out of the question. So, I tried a string (something - just to get the data back): #short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS lpvstats); VmxInfo = windll.vbis5032.VmxInfo VmxInfo.restype = c_short VmxInfo.argtypes = [LPHANDLE, LPSTR] VsamInfo = cre
Re: Need help calling a proprietary C DLL from Python
On Mar 22, 9:40 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Sat, 22 Mar 2008 15:12:47 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > > > > > Anyway, I have the following for "types": > > LPBSTR = POINTER(c_void_p) > > HANDLE = POINTER(POINTER(c_long)) > > LPHANDLE = POINTER(HANDLE) > > LPSHORT = POINTER(c_short) > > LPVSTATS = POINTER(c_void_p) > > c_string = c_char_p > > LPSTR = c_string > > > I guess passing a structure is out of the question. So, I tried a > > string (something - just to get the data back): > > #short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS > > lpvstats); > > VmxInfo = windll.vbis5032.VmxInfo > > VmxInfo.restype = c_short > > VmxInfo.argtypes = [LPHANDLE, LPSTR] > > VsamInfo = create_string_buffer("12345678901234567890123456789012") > > printf ("VsamInfo = \x22%s\x22\n", VsamInfo.raw) > > print "Ready to call (Library = " + find_library("vbis5032") + ") ..." > > res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) > > And I get: > > Ready to call (Library = C:\Windows\vbis5032.dll) ... > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 101, in > > res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) > > ctypes.ArgumentError: argument 2: : wrong > > type > > Did you try just passing the buffer, rather than nesting a "byref" > > http://docs.python.org/lib/ctypes-passing-pointers.html > > Note how the string buffer parameter has NO odd games on it. This > especially applies to the other call below, for PriKey and the other > BSTR *... term > > As for passing a structure... Well, I'd suggest using struct.pack to > push arguments into such a structure (though it it is using pointers to > other items it may get tricky), using create_string_buffer to make the > Python string "structure" a C-memory block, passing that, and if needed, > struct.unpack the item after the call. > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ Based on your input, I changed: LPSTR = c_char_p VmxGet = windll.vbis5032.VmxGet VmxGet.restype = c_short VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), TypeDef ) printf ("After - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d \n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef.raw) I got back exactly what I expected for TypeDef, but SecKey and PriKey were what I initialized them to , not what should have been returned. Do you mean that I should change any string that is expected to be changed by the dll to a create_string_buffer type (LPSTR) instead of a windll.oleaut32.SysAllocStringByteLen type (LPBSTR) and then simply list it in the call instead of byref, as I did with TypeDef? Can it really be that simple? As for the structure: class VSTATS(Structure): _fields_ = [ ("nrecords", c_long), ("gps_used", c_short), ("gps_unused", c_short), ("max_key_len", c_short), ("grp_size", c_long), ("init_alloc", c_short), ("cr_opts", c_short), ("free_prop_area", c_short), ("format", c_void_p), ("reserved", c_void_p) ] vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) can I just use a create_string_buffer (LPSTR) and parse things up via substrings after the call returns? -- http://mail.python.org/mailman/listinfo/python-list
Re: Anomaly in time.clock()
On Mar 22, 10:03 pm, Tim Roberts <[EMAIL PROTECTED]> wrote: > Godzilla <[EMAIL PROTECTED]> wrote: > > >Just found out that win32api.GetTickCount() returns a tick count in > >milli-second since XP started. Not sure whether that is reliable. > >Anyone uses that for calculating elapsed time? > > What do you mean by "reliable"? The tick count is updated as part of > scheduling during timer interrupts. As long as no one disables interrupts > for more than about 15ms, it is reliable. > > However, it's only a 32-bit value, so the number rolls over every 49 days. > -- > Tim Roberts, [EMAIL PROTECTED] > Providenza & Boekelheide, Inc. Try getting XP or Vista to stay up for 49 days. I have had Vista stay up for a little over 11 days. If it doesn't crash, it will have to be rebooted for some update or other. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 23, 4:48 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Sat, 22 Mar 2008 19:05:31 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > I got back exactly what I expected for TypeDef, but SecKey and PriKey > > were what I initialized them to , not what should have been returned. > > > Do you mean that I should change any string that is expected to be > > changed by the dll to a create_string_buffer type (LPSTR) instead of a > > windll.oleaut32.SysAllocStringByteLen type (LPBSTR) and then simply > > list it in the call instead of byref, as I did with TypeDef? > > Based upon my interpretation of the C prototype and the ctypes > documentation (sample code), that IS what I expect... (I didn't expect > it to work with the TypeDef field though...) > > There are two ways in which a C language function call can handle > returning string data. (Let's see if I remember how to code C; been 6 > years) > > char pre_alloc_buffer[] = "This is a fixed nul-terminated buffer space"; > char *dynamic_buffer; /* this is an uninitialized pointer to char */ > char *dynamic_too; > > The function can either modify a buffer passed in: > > int func1(char *bfr); > > or it can allocate a buffer internally and return that either as a > function result, or via a reference to a pointer variable > > char *func2(char *bfr[]); /* ugh, my memory is fading*/ > /* If I did this right, it is a pointer to array of character */ > > res = func1(pre_alloc_buffer); > or > res = func1(&pre_alloc_buffer[0]); /* long/explicit form */ > > The address of the start of the buffer space is passed, and func1 > performs its magic in the pre-allocated buffer. > > dynamic_too = func2(&dynamic_buffer); > > Here, we pass the address of just a pointer variable (which > currently points to garbage). func2 is expected to perform something > wherein IT allocates memory and that memory address is what is put into > the argument/return > > ... > *bfr = malloc(...); > return (bfr); > > Based on my interpretation of the prototypes, I'd have expected the > two BSTR to be the func1 style passing of a buffer, but the last > argument /might/ have been the second func2 style. > > I really can't be more definitive; I've not used ctypes -- only read > the documentation; the only DLLs I've had to use were covered by the > win32 extension library which comes as part of the ActiveState Python > installation. > > > > > Can it really be that simple? > > > As for the structure: > > class VSTATS(Structure): > > _fields_ = [ > >("nrecords", c_long), > >("gps_used", c_short), > >("gps_unused", c_short), > >("max_key_len", c_short), > >("grp_size", c_long), > >("init_alloc", c_short), > >("cr_opts", c_short), > >("free_prop_area", c_short), > >("format", c_void_p), > >("reserved", c_void_p) > > ] > > vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) > > can I just use a create_string_buffer (LPSTR) and parse things up via > > substrings after the call returns? > > It may be possible, though the library seems to have gone out of its > way to mask such efforts from the user. > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ This dll was designed to be used from either C or Visual Basic 6. I have the declare statements for VB6, if that helps. Based on the results I have so far (and I have tried MANY permutations like trying to use the LPSTR for SecKey and PriKey which are returned as is TypeDef), it looks like SecKey and PriKey are being used as data instead of pointers. For this, I try: LPSTR = c_char_p VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = create_string_buffer(41) SecKey.raw = "1234567890123456789012345678901234567890" PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef =
Re: Need help calling a proprietary C DLL from Python
On Mar 23, 7:59 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > > > This dll was designed to be used from either C or Visual Basic 6. > > > I have the declare statements for VB6, if that helps. > > Probably not that much -- I'd bet it's full of variant records > > > > > Based on the results I have so far (and I have tried MANY permutations > > like trying to use the LPSTR for SecKey and PriKey which are returned > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > instead of pointers. > > > For this, I try: > > LPSTR = c_char_p > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > LPSTR] > > SrchKey = > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > \x00", 41) > > SecKey = create_string_buffer(41) > > SecKey.raw = "1234567890123456789012345678901234567890" > > PriKey = > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > 41) > > TypeDef = create_string_buffer(128) > > TypeDef.raw = "X".center(128, "X") > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > and I get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 158, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > WindowsError: exception: access violation reading 0x3433322D > > > I notice that SecKey.raw starts with "1234" and the exception address > > is 0x3433322D, which is "432-". > > 0x2D is 4 less than the expected 0x31... > > > > > And, changing to: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > LPSTR] > > PriKey = create_string_buffer(41) > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > I then get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 159, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > WindowsError: exception: access violation reading 0x4443423D > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > is 0x4443423D, which is "DBC=". > > ... and 0x3D is 4 less than the expected 0x41 > > Which leads me to suspect that BSTR are a structure, not a plain > string, in which the address given is supposed to be prefaced with a > length value. IOWs, something like: > > ||--| > ^^ C-string data > ||Address to be passed > |(address - 4) to get to a length count field > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > (the URL is from HTTP through to the end, including .aspx) > > Creating such may not be difficult -- but passing it to the DLL > could be. I don't know if ctypes allows pointer arithmetic. > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > length prefix. > > The only mention of BSTR in the win32 extensions is in text that > implies that the win32 extension library takes care of converting > from/to BSTR and Python strings transparently -- but that won't work for > your third-party library I suspect. > > Might have to beg the author(s) of ctypes to add a BSTR type to the > list of those supported... as I can find no means of tweaking the > address computed by byref() to point somewhere into a structure rather > than the beginning of the structure. > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > >>> pk > 1373844 > >>> id(pk) > 18941724 > >>> ctypes.string_at(pk) > '1234567890' > >>> ctypes.string_at(pk-4, 20) > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > > Okay, the return value from SysAlloc... IS the integer representing > the address of a BSTR structure (IE, the address four bytes in from the > real memory start)... Note how backi
Re: Need help calling a proprietary C DLL from Python
On Mar 24, 12:27 pm, Craig <[EMAIL PROTECTED]> wrote: > On Mar 23, 7:59 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > > > > > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig <[EMAIL PROTECTED]> > > declaimed the following in comp.lang.python: > > > > This dll was designed to be used from either C or Visual Basic 6. > > > > I have the declare statements for VB6, if that helps. > > > Probably not that much -- I'd bet it's full of variant records > > > > Based on the results I have so far (and I have tried MANY permutations > > > like trying to use the LPSTR for SecKey and PriKey which are returned > > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > > instead of pointers. > > > > For this, I try: > > > LPSTR = c_char_p > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > > LPSTR] > > > SrchKey = > > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > > \x00", 41) > > > SecKey = create_string_buffer(41) > > > SecKey.raw = "1234567890123456789012345678901234567890" > > > PriKey = > > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > > 41) > > > TypeDef = create_string_buffer(128) > > > TypeDef.raw = "X".center(128, "X") > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > and I get: > > > Traceback (most recent call last): > > > File "C:\temp\vbisam_test_2.py", line 158, in > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(S > > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > WindowsError: exception: access violation reading 0x3433322D > > > > I notice that SecKey.raw starts with "1234" and the exception address > > > is 0x3433322D, which is "432-". > > > 0x2D is 4 less than the expected 0x31... > > > > And, changing to: > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > > LPSTR] > > > PriKey = create_string_buffer(41) > > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > I then get: > > > Traceback (most recent call last): > > > File "C:\temp\vbisam_test_2.py", line 159, in > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(S > > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > WindowsError: exception: access violation reading 0x4443423D > > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > > is 0x4443423D, which is "DBC=". > > > ... and 0x3D is 4 less than the expected 0x41 > > > Which leads me to suspect that BSTR are a structure, not a plain > > string, in which the address given is supposed to be prefaced with a > > length value. IOWs, something like: > > > ||--| > > ^^ C-string data > > ||Address to be passed > > |(address - 4) to get to a length count field > > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > > (the URL is from HTTP through to the end, including .aspx) > > > Creating such may not be difficult -- but passing it to the DLL > > could be. I don't know if ctypes allows pointer arithmetic. > > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > > length prefix. > > > The only mention of BSTR in the win32 extensions is in text that > > implies that the win32 extension library takes care of converting > > from/to BSTR and Python strings transparently -- but that won't work for > > your third-party library I suspect. > > > Might have to beg the author(s) of ctypes to add a BSTR type to the > > list of those supported... as I can find no means of tweaking the > > address computed by byref() to point somewhere into a structure rather > > than the beginning of the structure. > > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > > >>> pk > > 1373844 > > >&
Re: Need help calling a proprietary C DLL from Python
On Mar 24, 3:45 pm, Craig <[EMAIL PROTECTED]> wrote: > On Mar 24, 12:27 pm, Craig <[EMAIL PROTECTED]> wrote: > > > > > On Mar 23, 7:59 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > > > > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig <[EMAIL PROTECTED]> > > > declaimed the following in comp.lang.python: > > > > > This dll was designed to be used from either C or Visual Basic 6. > > > > > I have the declare statements for VB6, if that helps. > > > > Probably not that much -- I'd bet it's full of variant records > > > > > Based on the results I have so far (and I have tried MANY permutations > > > > like trying to use the LPSTR for SecKey and PriKey which are returned > > > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > > > instead of pointers. > > > > > For this, I try: > > > > LPSTR = c_char_p > > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > > > LPSTR] > > > > SrchKey = > > > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > > > \x00", 41) > > > > SecKey = create_string_buffer(41) > > > > SecKey.raw = "1234567890123456789012345678901234567890" > > > > PriKey = > > > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > > > 41) > > > > TypeDef = create_string_buffer(128) > > > > TypeDef.raw = "X".center(128, "X") > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > > and I get: > > > > Traceback (most recent call last): > > > > File "C:\temp\vbisam_test_2.py", line 158, in > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(S > > > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > > WindowsError: exception: access violation reading 0x3433322D > > > > > I notice that SecKey.raw starts with "1234" and the exception address > > > > is 0x3433322D, which is "432-". > > > > 0x2D is 4 less than the expected 0x31... > > > > > And, changing to: > > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > > > LPSTR] > > > > PriKey = create_string_buffer(41) > > > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > > I then get: > > > > Traceback (most recent call last): > > > > File "C:\temp\vbisam_test_2.py", line 159, in > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(S > > > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > > WindowsError: exception: access violation reading 0x4443423D > > > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > > > is 0x4443423D, which is "DBC=". > > > > ... and 0x3D is 4 less than the expected 0x41 > > > > Which leads me to suspect that BSTR are a structure, not a plain > > > string, in which the address given is supposed to be prefaced with a > > > length value. IOWs, something like: > > > > ||--| > > > ^^ C-string data > > > ||Address to be passed > > > |(address - 4) to get to a length count field > > > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > > > (the URL is from HTTP through to the end, including .aspx) > > > > Creating such may not be difficult -- but passing it to the DLL > > > could be. I don't know if ctypes allows pointer arithmetic. > > > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > > > length prefix. > > > > The only mention of BSTR in the win32 extensions is in text that > > > implies that the win32 extension library takes care of converting > > > from/to BSTR and Python strings transparently -- but that won't work for > > > your third-party library I suspect. > > > > Might
Re: Need help calling a proprietary C DLL from Python
On Mar 25, 2:02 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Mon, 24 Mar 2008 15:21:11 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > And this is what I got: > > VmxGet test - looking for valid record... > > Before -PriKey = 0x0044F56C,SecKey = 0x0044F534 > > ci_PriKey = 0x0044F56C, ci_SecKey = 0x0044F534 > > After -PriKey = 0x0044F56C,SecKey = 0x0044F534 > > ci_PriKey = 0x0043D49C, ci_SecKey = 0x0043D484 > > So VmxGet() DID allocate new BSTR structures. > > It might be interesting to extract the length data that is part of > the BSTR and compare. > > ctypes.string_at(PriKey - 4, 4) #if I recall the arguments > vs > ctypes.string_at(ci_PriKey - 4, 4) > > If the second (after conversion to integer) is larger than the > former, it could mean that the routine checks what is passed in to > ensure enough storage space, and if it won't fit, does the allocation. > > If it were always going to do an allocation, there would have been > no excuse for /reading/ the passed in structure length. > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ I changed to the following to followup on the length data: printf ("Before -PriKey = 0x%8.8X,SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(ci_SecKey), byref(ci_PriKey), TypeDef ) printf ("After -PriKey = 0x%8.8X,SecKey = 0x%8.8X\n", PriKey, SecKey) printf ("ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) print ord(string_at(PriKey - 4, 1)), ord(string_at(PriKey - 3, 1)), ord(string_at(PriKey - 2, 1)), ord(string_at(PriKey - 1, 1)) print ord(string_at(ci_PriKey.value - 4, 1)), ord(string_at(ci_PriKey.value - 3, 1)), ord(string_at(ci_PriKey.value - 2, 1)), ord(string_at(ci_PriKey.value - 1, 1)) And, got: Before -PriKey = 0x0028B6FC,SecKey = 0x0028B6C4 ci_PriKey = 0x0028B6FC, ci_SecKey = 0x0028B6C4 After -PriKey = 0x0028B6FC,SecKey = 0x0028B6C4 ci_PriKey = 0x0027D284, ci_SecKey = 0x0027D26C 41 0 0 0 7 0 0 0 Which makes sense for two reasons: 1. It would only return the non-space-filled part of the returned key. 2. At least from VB6, the variable does not even have to be used before the call. I have gone on to design a function for printing the contents as fields in a Structure. def DCOD_Print(): temp = unpack(DecoderRecordFormat, TypeDef.raw) DCOD = DecoderRecord(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5]) print " DistID = \x22%s\x22" % DCOD.DistID print " YearCode = \x22%s\x22" % DCOD.YearCode print " AccountType = \x22%s\x22" % DCOD.AccountType print "AccountNumber = \x22%s\x22" % DCOD.AccountNumber print " Description = \x22%s\x22" % DCOD.Description print " Unused = \x22%s\x22" % DCOD.Unused return class DecoderRecord(Structure): _fields_ = [ ("DistID", c_char_p), ("YearCode", c_char_p), ("AccountType", c_char), ("AccountNumber", c_char_p), ("Description", c_char_p), ("Unused", c_char_p) ] DecoderRecordFormat = "3s4ss32s32s56s" Then, a simple: print DCOD_Print() parses the record into its fields, and displays those fields. In other files, some of those fields are VB6 currency types, which have been described as 8-byte integers with an implied 4 decimal places (which I guess would be __int64 or c_longlong and then divide by 10,000, or simply put a decimal point 4 away from the end). Any ideas on how best to process this type of data in Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help calling a proprietary C DLL from Python
On Mar 26, 12:24 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Tue, 25 Mar 2008 08:24:13 -0700 (PDT), Craig <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > 41 0 0 0 > > 7 0 0 0 > > Which makes sense for two reasons: > > 1. It would only return the non-space-filled part of the returned key. > > 2. At least from VB6, the variable does not even have to be used > > before the call. > > Hmmm... I wonder what the library would have done if you just passed > a 0 to it... Rather than even doing that SysAlloc...() mess... > > PriKey = ctypes.int32(0)#or whatever the syntax was > > ... byref(PriKey) > > May with an effective null pointer the library would just allocate > directly rather than trying to determine the length field of the one > passed in. > > Something for the future, maybe... > > > print " DistID = \x22%s\x22" % DCOD.DistID > > You realize you can avoid those \x22 literals by changing the outer > quotes? > > print ' DistID = "%s" ' % > > or using triples > > print """DistID = "%s" """ % ... > > > > > In other files, some of those fields are VB6 currency types, which > > have been described as 8-byte integers with an implied 4 decimal > > places (which I guess would be __int64 or c_longlong and then divide > > by 10,000, or simply put a decimal point 4 away from the end). > > Don't divide directly; you might lose significance as the result is > converted to double-precision float. > > You could possibly convert to string, splice in that . and then pass > the result to the Decimal module/type... > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ I made these changes: # SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) SecKey = c_int32(0) ci_SecKey = c_int32(SecKey) # PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) PriKey = c_int32(0) ci_PriKey = c_int32(PriKey) And got: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 123, in ci_SecKey = c_int32(SecKey) TypeError: an integer is required Creating 2 "dummy" BSTR's isn't too bad of an option anyway. No, being somewhat new I didn't realize I could use (') in place if (") if I wanted to use a (") as a literal, but it seems to make a lot of sense now. I don't understand why I never tried it. As for the division vs. string manipulation, I agree - the string seems to be the simplest way to insure no loss of data. Thanks for all the input. -- http://mail.python.org/mailman/listinfo/python-list
Re: what IDE is the best to write python?
eclipse --- On Sun, 2/1/09, Dennis Lee Bieber wrote: From: Dennis Lee Bieber Subject: Re: what IDE is the best to write python? To: python-list@python.org Date: Sunday, February 1, 2009, 3:31 AM On Sat, 31 Jan 2009 23:42:42 -0800 (PST), "mcheun...@hotmail.com" declaimed the following in comp.lang.python: > Hi all >  what IDE is the best to write python?    The one in which YOU are most comfortable. --    Wulfraed   Dennis Lee Bieber      KD6MOG    wlfr...@ix.netcom.com      wulfr...@bestiaria.com       HTTP://wlfraed.home.netcom.com/    (Bestiaria Support Staff:      web-a...@bestiaria.com)       HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: python in emacs
I would go to ubuntu linux if you can. --- On Sun, 2/15/09, Diez B. Roggisch wrote: From: Diez B. Roggisch Subject: Re: python in emacs To: python-list@python.org Date: Sunday, February 15, 2009, 9:23 AM kentand...@sbcglobal.net schrieb: > When I visit a file with extension .py, emacs says "loading > python...done", and gives me a "python" menu with options like "start > interpreter" and "eval buffer". When I try to use one of these options > emacs says "loading compile...done", then hangs and has to be shut down > from the task manager. The Python folder is in my PATH variable and > works fine from the command line (or with IDLE). I'm using emacs-22.3 on > windows xp, and have the same problem with both python-2.2 and > python-3.0. Anybody got any tips, or should I just give up and use some > other editor? Did you try setting the python interpreter with the full path? Diez -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending SMS using python script
There's a Python wrapper to the Skype API here: http://sourceforge.net/projects/skype4py/ On Linux I've used the PyGTK GUI that uses this. It's called SkySentials here: http://www.kolmann.at/philipp/linux/skysentials/ Craig On Apr 3, 6:50 am, "ISF (Computer Scientists without Frontiers, Italy)" wrote: > On 2 Apr, 06:41, guptha wrote: > > > > > hi group, > > my application needs to sendSMSoccasionally to all the clients  .Is > > there any library in python that supports in sendingSMS. > > I like to conform few information i gathered in this regard. > > > I can sendSMSby two ways > > > 1. SendingSMSusing Email clients > > 2. Usingsmsgateway to send message(we can implementSMSGateway API > > 's ,provided by vendor and ,sendSMS-- we will be charged > > accordingly ) > > > In case of First approach > > 1. We can make use of libgamil library to sendSMSusing gmail ( I > > ref :http://blog.datasingularity.com/?p=63) > > i suppose sendingsmsthrough gmail is not supported in India > >  2. Can we use Skype4py library, > > > In case of second approach > > 1. Is there any way to sendSMSfor free inside India ,or ,Any freeSMSgateway > > providers in India > > Any information regarding this is appreciable > >  Thanks > > A friend from India sent me this hint: > > the following link can be explored further for sending SMS on pyS60 > (python for symbian OS)http://mobilenin.com/pys60/menu.htm > > wkr, > Aldo -- http://mail.python.org/mailman/listinfo/python-list
Re: What IDE support python 3.0.1 ?
Well i use netbean is alot better i think and it work with 2.6 and 3.0 --- On Thu, 4/16/09, mousemeat wrote: From: mousemeat Subject: Re: What IDE support python 3.0.1 ? To: python-list@python.org Date: Thursday, April 16, 2009, 4:41 AM Use eclipse with the pydev module. I use python(x,y) which is a big bundle of most of the python stuff you could possibly want (including scientific stuff, but its not mandatory to use it) configured to work together. It uses python 2.5. You can have the best of both worlds. Search for 'from __future__ import' to see how to get 3.0 features into 2.x, minimizing the eventual upgrade hassles. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
python question
How do i install this.i never seen a python write in c before. -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
http://downloads.emperorlinux.com/contrib/pyiw http://downloads.emperorlinux.com/contrib/pywpa Sorry fro the 2 post.How do i install a python moudles write en in C? -- http://mail.python.org/mailman/listinfo/python-list
Re: python question
I use python 2.6.2 and i useing ubuntu 9.04 not windows. --- On Thu, 5/21/09, Dave Angel wrote: > From: Dave Angel > Subject: Re: python question > To: "Craig" > Cc: python-list@python.org > Date: Thursday, May 21, 2009, 2:22 PM > Craig wrote: > > How do i install this.i never seen a python write in c > before. > > > > > >   > Well, I've never seen a snake program in any language, > python or otherwise. And I believe python was named > after Monty Python, not the snake. But once it got its > name, snake puns abound. > > Anyway, why not tell you what you want to install, and on > what platform? If it's Python 2.6.2 on MS Windows XP, > just download and run the msi file. >    On web page:   http://www.python.org/download/, you'd choose Python > 2.6.2 Windows installer > <http://www.python.org/ftp/python/2.6.2/python-2.6.2.msi> > and it'd give you file python-2.6.2.msi > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: www.python.org website is down?
Yes the same prob. --- On Sat, 8/8/09, Mark Lawrence wrote: > From: Mark Lawrence > Subject: Re: www.python.org website is down? > To: python-list@python.org > Date: Saturday, August 8, 2009, 8:41 AM > Caezar wrote: > > I cannot connect to the official Python website. I get > the following > > error message: > > > > "Connection Interrupted > > The connection to the server was reset while the page > was loading. > > The network link was interrupted while negotiating a > connection. > > Please try again." > > > > Are you experiencing the same problem? > Yes, it's been down for several hours. > > -- Kindest regards. > > Mark Lawrence. > > -- http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Crays
Who the one from wisconsin and did you try the python group in madison maybe they can help. Well i from madison are and i just a newbie with python.What OS you useing? --- On Thu, 8/27/09, Mark Dickinson wrote: > From: Mark Dickinson > Subject: Re: Python on Crays > To: python-list@python.org > Date: Thursday, August 27, 2009, 1:48 PM > On Aug 25, 11:34 pm, Carrie Farberow > > wrote: > > Ok, here are links to word documents outlining the > commands I executed as well as the make.log file and the > make_install.log file > > [links snipped] > > So from the output of make, it looks as though none of the > modules specified in the Modules/Setup file is being built > at all on your system. So not just unicodedata, but > the > math, cmath, array, itertools modules and more are > missing from your build. > > You can check this by running Python: after the make > step > finishes, you should have a working Python executable > called > 'python' in the current directory; if you start it up > and > then type 'import math' at the '>>>' prompt, I'm > guessing > you'll get an error message that looks something like: > > ImportError: No module named math > > I don't have much idea why those modules aren't being > built; > I tried imitating the relevant parts of your instructions > (to the degree that they make sense on my non-Cray system) > without any problems. > > Anyway, I agree that issue1594809 doesn't look so > relevant; > the only common factor is that in both cases Python is > failing to find the unicodedata module; but in that > issue > the unicodedata module is present but doesn't get found > because the paths are messed up, while in your case the > unicodedata module isn't being built at all. > > Suggestions: > > (1) double check that you've uncommented the appropriate > lines > in the Modules/Setup file. E.g., after the configure > step, there's > a line in Modules/Setup that looks like: > > #unicodedata unicodedata.c  # static Unicode > character database > > that leading '#' should be removed so that it looks like: > > unicodedata unicodedata.c  # static Unicode > character database > > and similarly for the other modules in that section. > Make sure that you're editing the Modules/Setup file > *after* the configure step and *before* the make step. > > (2) Find a local Unix/Python guru and ask him/her to > help out. These sorts of problems are generally much > easier to figure out when you've got direct access to > the machine. > > Sorry I can't be more help than this. > > -- > Mark > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: IDE for python similar to visual basic
Try wingware i have it and i like it. --- On Fri, 8/28/09, qwe rty wrote: > From: qwe rty > Subject: IDE for python similar to visual basic > To: python-list@python.org > Date: Friday, August 28, 2009, 5:19 PM > i have been searching for am IDE for > python that is similar to Visual > Basic but had no luck.shall you help me please? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: RIse and fall of languages in 2012
At one point or another I'm pretty sure I've googled "_ sucks" for every language I've ever used- even the ones I like. ie: Python easily more than once. Craig reporting from the road 10550 N Torrey Pines Rd La Jolla CA 92037 work: 858 784 9208 cell: 619 623 2233 On Jan 10, 2013, at 3:32 PM, Steven D'Aprano wrote: > On Thu, 10 Jan 2013 12:42:49 -0700, Michael Torrie wrote: > >>> And from the TIOBE Index, Python is steady at number 8: >>> >>> http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html >> >> The TIOBE index is meaningless. Since it's based on google searches, >> one could probably guess that any language that is awkward and difficult >> will require more searches to figure out how to use the thing. Thus of >> course C is top! Especially if ranked by sarcastic queries like, "C >> sucks," and "why does C suck so much." > > If you have a problem with TIOBE's methodology, feel free to come up with > your own. Or take it up with them. > > I dispute that TIOBE measures difficulty of language. If it did, Malbolge > would likely be at the top of the list. Yes, there are sarcastic queries > asking "C sucks", but that's just measurement error: 21,200 hits for "C > sucks" versus 9,900,000 for "C programming". It's not as if there is any > language, not even Python, that is so easy to use that nobody needs to > write about it. > > >> Javascript is doing much more than just "treading water." > > How do you know? What's *your* methodology for determining the popularity > of a language? > > * "But everybody knows that Javascript is super popular!!!" > > * "All my friends are using Javascript." > > * "I'm a web developer, and I use Javascript for my day job." > > * "I counted 14 job adverts on Monster.com for Javascript devs last week, > what more evidence does anyone need?" > > * "I googled for `What's the most popular language?` and found a blog > that says it's Javascript, that's good enough for me." > > * "I have a gut feeling." > > If you are going to criticise TIOBE's methodology, and then make your own > claims for language popularity, you really need to demonstrate that your > methodology is better. > > >> Javascript >> may not be glamorous but it is *the* glue that makes the web run. > > And web development is a tiny fraction of all software development. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Beowulf clusters
When you write HPC code the GIL isn't an issue, but you'll have plenty of others. Craig reporting from the road 10550 N Torrey Pines Rd La Jolla CA 92037 work: 858 784 9208 cell: 619 623 2233 On Jan 13, 2013, at 6:22 PM, Mark Janssen wrote: > On Sun, Jan 13, 2013 at 8:19 PM, Oscar Benjamin > wrote: >> On 14 January 2013 02:10, Mark Janssen wrote: >>> Has anyone used python for high-performance computing on Beowulf clusters? >> >> Yes. > > How did they deal with the Global interpreter lock across many machines? > > Cheers, > > Mark > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
alternative to with statement?
I see that there was previously a PEP to allow the with statement to skip the enclosing block... this was shot down, and I'm trying to think of the most elegant alternative. The best I've found is to abuse the for notation: for _ in cachingcontext(x): # create cached resources here # return cached resources I would have really liked: with cachingcontext(x): # create cached resources here # return cached resources I'd also like to avoid the following because it is unnecessary boilerplate: with cachingcontext(x) as skip: if not skip: # create cached resources here # return cached resources -- http://mail.python.org/mailman/listinfo/python-list
Re: alternative to with statement?
It is a bit non-normal. but I think this is a good use case as I want to create a very simple-to-use system for non-python experts to safely wrap their CLI programs in a caching architecture... that's why I lament the inability to not use the more streamlined 'with' syntax– abusing the for loop might just be confusing. The with statement is also a good fit because the caching strategy does have to atomically acquire, create and release the appropriate locks. With this statement the cached CLI wrappers can be called from simultaneously from different scripts and still coordinate their activity, by waiting for each other to finish, and reusing the cached results, etc. On Feb 28, 2012, at 1:04 PM, Craig Yoshioka wrote: > I see that there was previously a PEP to allow the with statement to skip the > enclosing block... this was shot down, and I'm trying to think of the most > elegant alternative. > The best I've found is to abuse the for notation: > > for _ in cachingcontext(x): ># create cached resources here > # return cached resources > > I would have really liked: > > with cachingcontext(x): ># create cached resources here > # return cached resources > > I'd also like to avoid the following because it is unnecessary boilerplate: > > with cachingcontext(x) as skip: >if not skip: > # create cached resources here > # return cached resources > > > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
AUTO: Craig Churchill is out of the office (returning 27/07/2011)
I am out of the office until 27/07/2011. I will respond to your message when I return. If you require assitance in relation to the SPEAR Integration project please contact Terry Mandalios. Note: This is an automated response to your message "Re: Tabs -vs- Spaces: Tabs should have won." sent on 19/7/2011 2:59:19. This is the only notification you will receive while this person is away. Notice: This email and any attachments may contain information that is personal, confidential, legally privileged and/or copyright.No part of it should be reproduced, adapted or communicated without the prior written consent of the copyright owner. It is the responsibility of the recipient to check for and remove viruses. If you have received this email in error, please notify the sender by return email, delete it from your system and destroy any copies. You are not authorised to use, communicate or rely on the information contained in this email. Please consider the environment before printing this email. -- http://mail.python.org/mailman/listinfo/python-list
This is a test
I have added you to the EMAIL list, so when I have questions. Just learn for fun. Craig Hatch -- https://mail.python.org/mailman/listinfo/python-list
Re: more newbie help needed
> Note, however, that there are more pythonic ways to perform this task. > You might try: > > for index in range(len(fruit)): >letter = fruit[-index-1] >print letter Or, if you're *really* just trying to reverse the string, then the following might read more easily (although it's probably longer): fruit="banana" fruit = list(fruit) fruit.reverse() fruit = ''.join(fruit) print fruit It turns the string into a list, reverses it, joins it back together (back into a string), then prints it. Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: Parse file into array
> I was wondering how i could parse the contents of a file into an array. > the file would look something like this: > > gif:image/gif > html:text/html > jpg:image/jpeg Try something like this: d = {} for line in open("input.txt").readlines(): ext, mime = line.strip().split(":") d[ext] = mime print d Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: exposing C array to python namespace: NumPy and array module.
not Py_DECREF Py_XDECREF(result); -- Ugh - I'd forgotten how ugly C code limited to 80 cols and without syntax highlighting really was. Especially when the reformatting is done as badly as I've done it. I hope you can make some sense out of that, anyway. Note that once the setup is done you can run as many python code snippets as you want, for declaring variables, functions, classes, etc. In my case, its easier to execute snippets as shown above than it is to worry about the module search path and wrapping things using a Python module. If you're doing substantial amounts of Python coding for your module, you'll almost certainly be better off writing a Python module that uses your C module internally (see PIL for a good example of this). -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: exposing C array to python namespace: NumPy and array module.
On Sat, 2005-01-01 at 10:27 -0600, Bo Peng wrote: > Sorry if I was not clear enough. I was talking about the differece > between python array module > (http://docs.python.org/lib/module-array.html, Modules/arraymodule.c in > the source tree) and NumPy array. They both use C-style memory block > arrangement for efficient memory access. While NumPy has both, the array > module is designed to be used purely in Python so there is no header > file and no function to build an array from a pointer. Thanks for clarifying that - I had misunderstood your reference to arraymodule.c . I guess the core language doesn't have an array type, but as there's a standard lib module that does (I'd forgotten it was there), it hardly matters. It would seem sensible to extend that module with a C API for mapping an existing array. That would be a rather handy thing to have in the standard library. > One of the methods you suggested (creating a new type) already > implemented in arraymodule.c. I am not sure if it is appropriate to add > the file into my project and add a 'CreateFromLenAndBuf' function. That sounds like a reasonable approach to me, but I'm hardly an expert. The code's license permits you to do so, and it's hardly worth repeating the work if you don't have to. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: screen clear question
On Sun, 2005-01-02 at 11:31, jcollins wrote: > Is there a command in Python to clear the screen? That is without writing > multiple blank lines. Without knowing what 'screen' you're talking about, it's hard to say. If you mean clearing a terminal, you can call 'tput clear' or '/usr/bin/clear' on many UNIX systems; no idea about Windows. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: emulating an and operator in regular expressions
On Mon, 2005-01-03 at 08:52, Ross La Haye wrote: > How can an and operator be emulated in regular expressions in Python? > Specifically, I want to return a match on a string if and only if 2 or more > substrings all appear in the string. For example, for a string s = 'Jones > John' and substrings sg0 = 'Jones' and sg1 = 'John', I want to return a > match, but for substrings sg0 = 'Jones' and sg2 = 'Frank' I do not want to > return a match. Because the expression 'A and B' is logically equivalent to > 'not (not A or not B)' I thought I could try something along those lines, > but can't crack it. My first thought would be to express your 'A and B' regex as: (A.*B)|(B.*A) with whatever padding, etc, is necessary. You can even substitute in the sub-regex for A and B to avoid writing them out twice. -- Craig Ringer -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Developing Commercial Applications in Python
On Mon, 2005-01-03 at 19:00, [EMAIL PROTECTED] wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? My understanding is that you're dead safe with Python its self, as AFAIK you can even bundle (possibly modified) the Python sourcecode into your application. You'd simply need to keep an eye on the licenses of any extensions you used, like ReportLab, PIL, mx, database interfaces, twisted, etc. Many are licensed under the same license as Python or an MIT-like license, but of course some Python extensions are not and you would need to consider that. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
RE: removing comments form a file
On Mon, 2005-01-03 at 11:46 -0300, Batista, Facundo wrote: > - Used file instead of open, to don't read the whole file in memory. [EMAIL PROTECTED] ~]$ python Python 2.3.4 (#1, Oct 26 2004, 16:42:40) .>>> file is open True .>>> print repr(file), repr(open) I'd be interested if you could clarify what you mean there. As far as I know, the whole file will only be read into memory if you use file.read () or file.readlines(). If you use an iterator it does internal readahead, but won't read the lot at once. If you use read() it reads only what you say. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Bad Interpreter
On Mon, 2005-01-03 at 12:24 -0800, [EMAIL PROTECTED] wrote: > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? You probably have Windows-style line endings in the file. The kernel sees the ^M at the end of the line and gets all confused. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding a restricted python interpreter
On Wed, 2005-01-05 at 13:43, Maurice LING wrote: > Rolf Magnus wrote: > > Hi, > > > > I would like to embed a python interpreter within a program, but since that > > program would be able to automatically download scripts from the internet, > > I'd like to run those in a restricted environment, which basically means > > that I want to allow only a specific set of modules to be used by the > > scripts, so that it wouldn't be possible for them to remove files from the > > hard drive, kill processes or do other nasty stuff. > > Is there any way to do that with the standard python interpreter? > > > > I won't really count on that. In my opinions, which may be wrong, Python > is not constructed to work in a sandbox like Java. That is my understanding. In fact, I'd say with Python it's nearly impossible given how dynamic everything is and the number of tricks that can be used to obfuscate what you're doing. Think of the fun that can be had with str.encode / str.decode and getattr/hasattr . I looked into this, and my conclusion ended up being "Well, I'm using Python because I want it's power and flexibilty. If I want a secure scripting environment, I should use something like Lua or Qt Script for Applications instead." AFAIK that's why the rexec() builtin is disabled - it's just not practical to make a restricted Python execution environment. > You can try to use 'exec' to run your scripts in a constructed > environment. For example, > > global = {} > local = {} > > ... your stuffs > > statement = [] # to hold the script to run > > for line in statement: > exec statement in global, local > > global and local are the global and local namespaces respectively. > Although it had been explained to me before but I can't recall the > details of how it works. In gist, you may be able to craft a global and > local environment for your script to run in. > I do not know if it is possible to disable or override 'import'.. You can do a fair bit to it by wrapping/replacing __builtin__.__import__ . Preventing people from getting around what you've done, though... not sure. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding a restricted python interpreter
On Thu, 2005-01-06 at 23:05, Peter Maas wrote: > Craig Ringer schrieb: > It would certainly be difficult to track all harmful code constructs. > But AFAIK the idea of a sandbox is not to look at the offending code > but to protect the offended objects: files, databases, URLs, sockets > etc. and to raise a security exception when some code tries to offend > them. That's a good point. I'm not sure it's really all that different in the end though, because in order to control access to those resources you have to restrict what the program can do. It'd probably be valid to implement a restricted mode at CPython level (in my still-quite-new-to-the-Python/C-API view) by checking at the "exit points" for important resources such as files, etc. I guess that's getting into talk of something like the Java sandbox, though - something Java proved is far from trivial to implement. Of course, CPython is just a /tad/ smaller than Java ;-) . Personally, I'd be worried about the amount of time it'd take and the difficulty of getting it right. One wouldn't want to impart a false sense of security. My original point, though, was that I don't think you can use the standard interpreter to create a restricted environment that will be both useful and even vaguely secure. I'd be absolutely delighted if someone could prove me wrong. > Python is a very well designed language but progress is made by > criticism not by satisfaction ;) Heh, I'm hardly complacent... I run into quite enough problems, especially with embedding and with the C API. Maybe one day I'll have the knowledge - and the time - to have a chance at tackling them. I'd love a restricted mode - it'd be great. I'm just not very optimistic about its practicality. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C Object Comparison
On Thu, 2005-01-06 at 18:34, Anand K Rayudu wrote: > Here is my python code > > import myModule > > a=myModule.myAPI1("1") > b=myModule.myAPI2("name") > > # basically both above functions return same C pointer. > # so i want to compare > if(a==b): print "They are same" > else : print "They are different" > > python always prints they are different, > I guess this is because in python layer we create PythonCObject for > every C pointer, and that is how it is exposed to python. Though both > the APIs are returning the same C pointer, they are different instances > of PythonCObject. That sounds likely to me. > So i guess that is the reason comparison is failing. > How ever is it possible to make python to compare actual C pointer, > rather than the PythonCObject Pointer. You might be able to subclass PyCObject and work with your subclassed version (that adds a __eq__ method). In the end, though, I don't think that's the right path to proceed down. My understanding is that CObjects are for passing pointers through Python code in a safe way. I don't think they're really intended for uses where the Python code is actually working with the objects, only pass them around as opaque objects. If you want to actually work with the objects you're passing around, I'd think about implementing my own type that better fits the API my extension module wants to present to Python code. I'm using PyCObjects as a temporary ugly hack in an embedded app I'm working on... but it's seriously ugly. What I should do, and will soon do now that I've tested the concept of what I'm doing and it works, is move all my functions into a class and make the class own and manage the C++ object (and pointer to it) that it owns. Perhaps that's a better solution for you too? If you want any opinions from folks here about the best way to solve your problem, you'll probably need to explain a bit more of your problem - like what your extension module is doing that makes it have to pass PyCObjects around and get Python code to work with them. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: File Handling Problems Python I/O
On Fri, 2005-01-07 at 02:06, Josh wrote: > Peter, > > Thank you for the rookie correction. That was my exact problem. I > changed the address to use forward slashes and it works perfect. I did > not know that a backslash had special meaning within a string, but now > I do! Thanks again There's another common mistake you might want to head off now, too. Consider the following program: directory = r"c:\mydata" datafilename = "something.txt" datafile = open(directory + datafilename,"r") - It's very common for this to happen, usually when the paths are originally written with trailing slashes then changed to not have them later. Rather than saying "all paths must have trailing slashes", manually formatting in slashes, or other platform-specific uglyness, consider using the os.path module to take care of it: import os directory = r"c:\mydata" datafilename = "something.txt" datafile = open(os.path.join(directory,datafilename),"r") This will work on any platform (so long as the literal paths are correct) and will work no matter whether or not there are trailing path separators on the input strings. os.path.join can take more than two arguments, too. os.path has lots of other handy tools, so I strongly recommend checking it out. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding a restricted python interpreter
On Thu, 2005-01-06 at 23:40, Steve Holden wrote: > Jp Calderone wrote: > > [...] > > > > > > A Python sandbox would be useful, but the hosting provider's excuse > > for not allowing you to use mod_python is completely bogus. All the > > necessary security tools for that situation are provided by the > > platform in the form of process and user separation. > > Not sure this is strictly true: mod_python gets loaded into the server's > address space and gives the ability to add any type of handler. While > Apache might well be able to respawn failed subprocesses, it's not > something that most hosting providers would like to have to do all the > time for many hosted sites. I wonder if SCGI or a similar "persistent CGI" solution might be more practical for running CGI scripts under specific user accounts. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: curses is not imported under Linux (and Python 2.4)
On Fri, 2005-01-07 at 00:38, Konrad Koller wrote: > import curses > produces the ImportError: No module named _curses > ("from _curses import *" in line 15 in __init__.py) > Of course imp.find_module ("_curses") reports the same error. > How can I make use of the curses package for writing a Python script > with curses? What Linux distro? Is the Python version you're running one you compiled, one that shipped with the distro, or a 3rd party RPM? At a guess, I'd say you compiled it yourself and you don't have the ncurses development packages (providing the ncurses header files and static libs) installed. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: missing sys.setappdefaultencoding
On Fri, 2005-01-07 at 19:06, Alex Martelli wrote: > Uwe Mayer <[EMAIL PROTECTED]> wrote: > > well, I wrote a nice python program which won't work if the default encoding > > has not been set from ascii to latin-1 or latin-15. > > Then your program is not very nice...;-) Agreed. I prefer to use explicit str.encode(), str.decode() and unicode() calls where appropriate. On a side note, PEP 263 handles the text encoding interpretation of Python program source, and is well worth reading and following. http://python.org/peps/pep-0263.html -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting on keys in a list of dicts
On Sat, 2005-01-08 at 00:26, It's me wrote: > What does it mean by "stability in sorting"? If I understand correctly, it means that when two sorts are performed in sequence, the keys that are equal to the second sort end up ordered the way they were left by the first sort. I'm far from certain of this, but at least I'm presenting an opportunity for someone to yell "no, you're wrong!" and in the process definitively answer the question. For example, given the list: .>>> l = [(1,2), (8,2), (2,2), (3,2), (4,3), (5,3), (8,9)] if we sort by the first element of each tuple then the second (the default), we get: .>>> l.sort() .>>> l [(1, 2), (2, 2), (3, 2), (4, 3), (5, 3), (8, 2), (8, 9)] Now, if we sort based on the second element we get: .>>> def seconditem(x): return x[1] .>>> l.sort(key=seconditem) .>>> l [(1, 2), (2, 2), (3, 2), (8, 2), (4, 3), (5, 3), (8, 9)] You'll note that there are several correct answers to the request "sort the list 'l' by the second element of each item", including: [(1, 2), (2, 2), (3, 2), (8, 2), (4, 3), (5, 3), (8, 9)] [(2, 2), (1, 2), (8, 2), (3, 2), (4, 3), (5, 3), (8, 9)] [(1, 2), (2, 2), (3, 2), (8, 2), (5, 3), (4, 3), (8, 9)] and many others. Because we didn't specify that the first item in the value tuples should be used in the sort key, so long as the second key is equal for a group of items it doesn't matter what order items in that group appear in. Python (at least 2.4), however, returns those groups where the order isn't defined in the same order they were before the sort. Look at this, for example: .>>> l.sort() .>>> l.reverse() .>>> l [(8, 9), (8, 2), (5, 3), (4, 3), (3, 2), (2, 2), (1, 2)] .>>> l.sort(key=seconditem) .>>> l [(8, 2), (3, 2), (2, 2), (1, 2), (5, 3), (4, 3), (8, 9)] See how the exact same sort command was used this time around, but because the list was reverse-sorted first, the elements are in reverse order by first item when the second item is equal? In the first case we used the same result as the stable sort could be obtained with: .>>> def revitem(x): return (x[1], x[0]) >>> l.sort(key=revitem) >>> l [(1, 2), (2, 2), (3, 2), (8, 2), (4, 3), (5, 3), (8, 9)] (in other words, saying "use the value tuple as the sort key, but sort by the second element before the first") That doesn't extend to more complex cases very well though. Imagine you had 3-tuples not 2-tuples, and wanted to maintain the previous sort order of equal groupings when re-sorting by a different key... but you didn't know what key was last used for sorting. A stable sort algorithm means you don't need to care, because the order will be maintained for you not randomized. Well, that's several hundred more words than were probably required, but I hope I made sense. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: how to extract columns like awk $1 $5
On Sat, 2005-01-08 at 01:15, Anand S Bisen wrote: > Hi > > Is there a simple way to extract words speerated by a space in python > the way i do it in awk '{print $4 $5}' . I am sure there should be some > but i dont know it. The 'str.split' method is probably what you want: .>>> x = "The confused frog mumbled something about foxes" .>>> x.split() ['The', 'confused', 'frog', 'mumbled', 'something', 'about', 'foxes'] .>>> x.split(" ")[4:6] ['something', 'about'] so if 'x' is your string, the rough equivalent of that awk statement is: .>>> x_words = x.split() .>>> print x_words[4], x_words[5] or perhaps .>>> print "%s %s" % tuple(x.split()[4:6]) -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Help uninstalling/installing Python 2.4
On Sat, 2005-01-08 at 08:08, Baggs wrote: > Tk calls did not work, the output from Python when running a program > stated that I probably did not have TK installed. I got and installed > TK 8.4 and the problem persisted (I know I should have written down the > exact error, but I didn't... but the story gets worse!) You probably didn't have the -devel packages for Tcl and Tk installed, so Python would've decided you didn't have Tk and not built tkinter support. Chances are if you install the devel packages and recompile Python, it'll work fine. > when I re-installed I still have > problems.. everything installs ok, but now I get the following errors > with Python... > > bash: /usr/bin/python: No such file or directory Is that when you run a script, or when you type 'python' in your shell? If the former, make sure you write your scripts with a #! like this: #!/usr/bin/env python not #!/usr/bin/python That way, the right python will get run so long as it's on your path - it doesn't have to be in /usr/bin. If the error is when typing 'python' on the command line, ensure you have no aliases for the name 'python' hanging around ('alias python' to find out). Also check what is actually being run with 'which python' and see if it's a wrapper script that calls /usr/bin/python. > when I go to /usr/local/bin and type ./python I get > > Python 2.4 (#6, Jan 7 2005, 18:44:57) > [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > Traceback (most recent call last): >File "/etc/pythonrc.py", line 2, in ? > import readline > ImportError: No module named readline > > I think some paths are screwed up.. can someone take pity on me and give > me a hand. I'd say that'll be the same as with Tkinter - you probably didn't have the GNU readline development headers installed, so Python disabled readline support when it was compiled. That's just a guess, but seems pretty likely. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: _tkinter problem
On Sat, 2005-01-08 at 14:30, Jatinder Singh wrote: > Hi > I am running a script which is importing tkinter from > "/usr/local/lib/python2.3/lib-tk/Tkinter.py" and generating an error > " import _tkinter > ImportError: No module named _tkinter " > > can anybody tell me what is it? and how to get away with it? I think your question is the same problem as another recent poster - that is, you didn't have the Tcl and Tk headers installed when you installed Python. Please see my answer to "Help uninstalling/installing Python 2.4" (Yes, I know yours isn't Python 2.4 - it doesn't matter). -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: C structure in the Python extension
Dave win wrote: >Howdy: > When I was writting interface functions of the extending python, I >meet a question. As I using the "PyArg_ParseTuple(args,arg_type,...)" >function call, if I wanna use the personal defined argument, such as the >C structure which I made. How to make it? > >static PyObject* Call_V_ABSUB(PyObject *self, PyObject* args){ > myStruct FU; > myStruct result; > if(!PyArg_ParseTuple(args,"O&",&FU)) return NULL; >^^^ >How to modify here??? > V_ABSUB(FU); > > return Py_BuildValue("i",result); >} > > You can't, really. Python code can't work with C structs directly, so it can't pass you one. I have used one utterly hideous hack to do this when prototyping code in the past, but that was before I knew about PyCObject. PyCObject is also pretty evil if abused, but nowhere NEAR on the scale of what I was doing. Can you say passing pointers around as Python longs? Can't bring yourself to say it? Don't blame you. My only defense was that it was quick hack prototype code, and that the Python/C API for making classes is too painful to use when quickly prototyping things. To do what you want, you could encapsulate a pointer to the struct in a PyCObject, then pass that around. Your Python code will just see a PyCObject with no attributes or methods; it can't do anything to it except pass it to other Python code (and delete it, but that'll result in a memory leak if the PyCObject holds the only pointer to the struct). Your C code can extract the pointer to the struct and work with that. DO NOT do this if the Python code just deleting the PyCObject could ever discard the last pointer to the struct, as you'll leak the struct. A much BETTER option is probably to rewrite myStruct to be a Python type ("class") implemented in C, and provide it with both a C and Python API. This isn't too hard, though the Python/C API does make creating types a bit cumbersome. (Most of this seems to be because you're playing pretend-we-have-objects in C, rather than issues specific to the Python/C API). -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: here document
On Tue, 2005-01-11 at 18:46, harold fellermann wrote: > On 11.01.2005, at 11:34, Nader Emami wrote: > > Would somebody help me how i can write the 'here document' in > > Python script please? I have a csh script in which a program > > is invoked with some argument in the form of here document: > > > > /bin/exe.x << End_Here > > CategorY = GRIB > > etc. > > End_Here > > > > I translate this script to Python and i don't know how can I > > do this! > > f = open("/bin/exe.x","w") > print >>f , """CategoryY = GRIB > etc. > """ You mean "os.popen" not "open" I assume? The former opens a pipe to a command, the latter overwrites the file. I'd use: os.popen("/bin/exe.x", "w").write("""\ CategorY = GRIB etc. """) myself, but that's just taste (well, and performance I suspect). -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Python.org, Website of Satan
On Wed, 2005-01-12 at 16:58 +0100, Gerhard Haering wrote: > On Wed, Jan 12, 2005 at 10:15:34AM -0500, Jane wrote: > > [...] Some people have too much time on their hands... > > OMG, PyPy is full of evil, too!!!1 > > print sum([ord(x) for x in "PyPy"]) > > or, if you haven't upgraded to 2.4, yet: That'll work fine in Python 2.3. I think you meant: print sum(ord(x) for x in "PyPy") which is a different matter entirely (well, regarding compatibility anyway). -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: python and macros (again) [Was: python3: 'where' keyword]
On Thu, 2005-01-13 at 08:39 +, Antoon Pardon wrote: > > At best it would offer new paradigms for existing constructs (violating > > the "there should be one obvious way to do it" zen); at worst it would > > obfuscate the whole language. > > That zen is already broken. Look at the number of answers one gets > if a newbee askes for a ternary operator. I think that a simple > ternary operator or macro's with an official supported macro that > implemented the ternary operator would have been far closer to > the spirit of only having one obvious way than what we have now. And then we have iteration (generator expressions, list comprehensions, for loops, ...?) over (sequences, iterators, generators) I happen to be extremely fond of the flexibility this provides, but one obvious way to do it there is not. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: counting items
On Wed, 2005-01-12 at 20:10 +0100, Bernhard Herzog wrote: > "It's me" <[EMAIL PROTECTED]> writes: > > > May be flatten should be build into the language somehow > > That shouldn't be necessary as it can easily be written in a single list > comprehension: > > a = [[1,2,4],4,5,[2,3]] > flat_a = [x for cur, rest in [[a[:1], a[1:]]] for x in cur > if (not isinstance(x, (list, tuple)) > and (not rest or not cur.append(rest.pop(0))) > or (x and (cur.append(x[0]) or rest.__setslice__(0, 0, > x[1:]))) > or (not x and rest and cur.append(rest.pop(0] > > ;-) If it means I _never_ have to see that list comprehension again, then seeing 'flatten' go into itertools would make me very, very happy :-P -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Free python server.
On Thu, 2005-01-13 at 19:07 +0100, [EMAIL PROTECTED] wrote: > Thank you very much. > Arbornet.org seems to be ok > Unforutnately I was convinced that I only have to only copy my *.py file to > /public_hml directory and everything will be all right. Your file probably need to (a) be in the cgi-bin, not public_html, (b) be flagged executable ("chmod a+x file.py"), and (c) begin with the line: '#!/usr/bin/env python' If the server doesn't provide you with CGI (or, strongly preferable, SCGI or mod_python), you're probably out of luck. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: [Fwd: Re: Embedding Multiplr Python interpreter in C++]
On Fri, 2005-01-14 at 22:42, Steve Holden wrote: > Take a look at mod_python's code: that allows several independent > interpreters in the same Apache process using Py_NewInterpreter() I've never been entirely clear on whether mod_python does its magic by relying on having one thread per sub-interpreter, or if it can support multiple sub interpreters in a single thread. Any ideas? I'm pretty sure it's the former, but it'd be nice to be sure. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Executing a script created by the end user
I am working on a python project where an object will have a script that can be edited by the end user: object.script If the script is a simple one with no functions, I can easily execute it using: exec object.script But if the object script is a bit more complicated, such as the example below, my approach does not work: def main(): hello1() hello2() def hello1(): print 'hello1' def hello2(): print 'hello2' -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
On Mon, 2005-01-17 at 12:15 -0300, John Lenton wrote: > knowledgeable and experienced users know when to ignore the rules. +1 QOTW One of the nice things is that Python permits you to do exactly that where appropriate while avoiding forcing you to do gruesome things to get a job done. I think the classic example of your statement is the use of 'goto' in C and C++ code. Don't use goto - except when there's no other sensible way to make your code clear. For example, goto and Py_XECREF seem to be very handy for cleanup after detecting an exception when working with the Python/C API. That said, I do think "the rules" deserve consideration and respect - they're usually there because of many others' experience over time. It's interesting to learn those lessons first hand, but it's nice to be able to avoid repeating every single one of them. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
On Wed, 2005-01-19 at 09:04 -0800, [EMAIL PROTECTED] wrote: > Rick Muller wrote: > >I was wondering whether anyone could recommend a good C++ book, with > >"good" being defined from the perspective of a Python programmer. > > The STL and the template feature of C++ gives the programmer some of > the functionality of Python (using templates instead of duck typing, > vectors instead of lists etc.), I'm particularly fond of internally refcounted objects (as used extensively in Qt) and of guarded pointers, myself. The use of these two things means one can avoid the "sometimes works, sometimes doesn't" fun of referencing deleted memory by accident. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on generator...
On Fri, 2005-01-21 at 17:14 +0300, Denis S. Otkidach wrote: > On 21 Jan 2005 05:58:03 -0800 > [EMAIL PROTECTED] (Joh) wrote: > > > i'm trying to understand how i could build following consecutive sets > > from a root one using generator : > > > > l = [1,2,3,4] > > > > would like to produce : > > > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > >>> def consecutive_sets(l): > ... for i in xrange(2, len(l)): > ... for j in xrange(0, len(l)-i+1): > ... yield l[j:j+i] Since you have a much faster brain than I (though I ended up with exactly the same thing barring variable names) and beat me to posting the answer, I'll post the inevitable awful generator expression version instead: consecutive_sets = ( x[offset:offset+subset_size] for subset_size in xrange(2, len(x)) for offset in xrange(0, len(x) + 1 - subset_size) ) -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on generator...
On Fri, 2005-01-21 at 22:38 +0800, Craig Ringer wrote: > consecutive_sets = ( x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size) ) Where 'x' is list to operate on, as I should've initially noted. Sorry for the reply-to-self. I did say "awful" for a reason ;-) -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic properties
On Fri, 2005-01-21 at 06:43 -0800, michael wrote: > setattr (self, key, property (fget, fset, fdel)) > it gives me > > > > What am I doing wrong here Properties must be defined in the class, not the instance, to work as expected. (Edit: Nick Coghlan explained this more accurately). You can dynamically generate properties in a metaclass or class factory, and you can add them to a class after the class is created (even from an instance of that class). If you add properties to an instance of a class rather than the class its self, though, you won't get the expected results. .class Fred(object): .def __init__(self): .self._name = 'fred' .def getname(self): .return self._name .def setname(self, newname): .self._name = newname .name = property(getname, setname) . .f = Fred() .print f.name . .# Works: .class Fred2(object): .def __init__(self): .self._name = 'fred2' .def getname(self): .return self._name .def setname(self, newname): .self._name = newname . .Fred2.name = property(Fred2.getname, Fred2.setname) .f2 = Fred2() .print f2.name . .# Won't work: .class Fred3(object): .def __init__(self): .self._name = 'fred3' .def getname(self): .return self._name .def setname(self, newname): .self._name = newname . .f3 = Fred3() .f3.name = property(f3.getname, f3.setname) .print f3.name . .# Also won't work .f3 = Fred3() .f3.name = property(Fred3.getname, Fred3.setname) .print f3.name . .# This will work, though, because while it adds the property .# after the instance is created, it adds it to the class not .# the instance. .f3 = Fred3() .Fred3.name = property(Fred3.getname, Fred3.setname) .print f3.name The chances are that whatever you want to do with dynamically created properties is better done with __getattr__ and __setattr__ instead. If they don't fit the bill, you can add properties to the class from its instances. I intensely dislike this though, personally. I'd want to look into using a class factory or metaclass to do the job if __getattr__ and __setattr__ are insufficient or unacceptable. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on need help on generator...
On Fri, 2005-01-21 at 16:05 +0100, Francis Girard wrote: > I recently read David Mertz (IBM DeveloperWorks) about generators and > got excited about using lazy constructs in my Python programming. Speaking of totally great articles, and indirectly to lazyness (though not lazyily evaluated constructs), I was really impressed by this fantastic article on metaclasses: http://gnosis.cx/publish/programming/metaclass_1.html http://gnosis.cx/publish/programming/metaclass_2.html which shows that they're really just not that hard. That saved me an IMMENSE amount of utterly tedious coding just recently. > But besides the fact that generators are either produced with the new > "yield" reserved word or by defining the __new__ method in a class > definition, I don't know much about them. They can also be created with a generator expression under Python 2.4. A generator expression works much like a list comprehension, but returns a generator instead of a list, and is evaluated lazily. (It also doesn't pollute the outside namespace with its working variables). >>> print [ x for x in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print ( x for x in xrange(1,10) ) >>> print list(( x for x in xrange(1,10) )) [1, 2, 3, 4, 5, 6, 7, 8, 9] Not the use of xrange above for efficiency in the generator expressions. These examples are trivial and pointless, but hopefully get the point across. > In particular, I don't know what Python constructs does generate a > generator. As far as I know, functions that use yield, and generator expressions. I was unaware of the ability to create them using a class with a __new__ method, and need to check that out - I can imagine situations in which it might be rather handy. I'm not sure how many Python built-in functions and library modules return generators for things. > I know this is now the case for reading lines in a file or with the > new "iterator" package. But what else ? Does Craig Ringer answer mean > that list comprehensions are lazy ? Nope, but generator expressions are, and they're pretty similar. > Where can I find a comprehensive list of all the lazy constructions > built in Python ? (I think that to easily distinguish lazy from strict > constructs is an absolute programmer need -- otherwise you always end > up wondering when is it that code is actually executed like in > Haskell). I'm afraid I can't help you with that. I tend to take the view that side effects in lazily executed code are a bad plan, and use lazy execution for things where there is no reason to care when the code is executed. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on generator...
On Fri, 2005-01-21 at 16:54 +0100, Francis Girard wrote: > First, I think that you mean : > > consecutive_sets = [ x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size)] > > (with square brackets). > I'm just trying to understand and obviously I'm missing the point. Yep. This: ( x for x in xrange(10) ) will return a generator that calculates things as it goes, while this: [ x for x in xrange(10) ] will return a list. Check out: http://www.python.org/peps/pep-0289.html http://docs.python.org/whatsnew/node4.html http://www.python.org/dev/doc/newstyle/ref/genexpr.html for details. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Configuring Python for Tk on Mac
On Fri, 2005-01-21 at 07:39 -0800, Martyn Quick wrote: > On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. > > When I go into a terminal and type "python" up comes a nice python > interface and all seems great. However when I type "import Tkinter" > I'm greeted by the following error. > > >>> import Tkinter > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter > > So I guess something about this implementation is not appropriately > configured. In general, that error means that Python can't find the C extension module used to provide the low-level interface for Tkinter. It's not installed, can't be found (library path or python path issues), can't be opened (permissions), etc. Note the comment in the error message to that effect. I've just checked the OSX 10.3 machine here, and it fails to import tkinter there too. I'd say Apple just don't build Python with Tk support. > What do I do to set it up so I can use Tkinter? Try Google - this seems to be a moderately FAQ for MacOS/X. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple size and memory allocation for embedded Python
On Fri, 2005-01-21 at 16:03 -0600, Jinming Xu wrote: > Hi Folks, > > Python seems unstable, when allocating big memory. For example, the > following C++ code creates a tuple of tuples: > > PyObject* arCoord = PyTuple_New(n); > double d = 1.5; > for(int i=0; i { > PyObject* coord = PyTuple_New(2); > PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > PyTuple_SetItem(arCoord,i, coord); > } > > When the n is small, say 100, the code works fine. when n is big, say > 10,000, Python has trouble allocating memory, saying: > > "Exception exceptions.IndexError: 'tuple index out of range' in 'garbage > collection' ignored > Fatal Python error: unexpected exception during garbage collection > Aborted" You're not checking for errors from PyTuple_SetItem. You need to do so, otherwise exceptions will go uncaught and may pop up at weird points later in your software's execution, or crash things. int PyTuple_SetItem( PyObject *p, int pos, PyObject *o) Inserts a reference to object o at position pos of the tuple pointed to by p. It returns 0 on success. Note: This function ``steals'' a reference to o. It returns an int result code, so you should probably be checking it. You CERTAINLY should be ensuring that PyTuple_New() doesn't return NULL (meaning a failure, probably of memory allocation). I also don't see anything in there to resize the tuple. http://docs.python.org/api/tupleObjects.html -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple size and memory allocation for embedded Python
On Fri, 2005-01-21 at 17:20 -0500, Steve Holden wrote: > Jinming Xu wrote: > > > Hi Folks, > > > > Python seems unstable, when allocating big memory. For example, the > > following C++ code creates a tuple of tuples: > > > > PyObject* arCoord = PyTuple_New(n); > > double d = 1.5; > > for(int i=0; i >{ > > PyObject* coord = PyTuple_New(2); > > PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > > PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > > PyTuple_SetItem(arCoord,i, coord); > >} > > > > When the n is small, say 100, the code works fine. when n is big, say > > 10,000, Python has trouble allocating memory, saying: > > > > "Exception exceptions.IndexError: 'tuple index out of range' in 'garbage > > collection' ignored > > Fatal Python error: unexpected exception during garbage collection > > Aborted" > > > > Could anyone please give me some insight or a fix for this? > > > > Thanks in advance for your answer. > > > I'm going to guess that the problem is related to incorrect reference > counts. It's usually a safe bet, after all. Another biggie is unchecked return codes leaving the exception state set, though... that can cause _really_ _weird_ problems. ALWAYS check return values. > I don't see any IncRefs in there. In this case it looks OK. PyFloat_FromDouble() reuturns a new reference, as does PyTuple_New(), and PyTuple_SetItem() steals a reference to its PyObject* argument. Of course, there could be refcount errors outside the shown code segment, but in this case I'd say the immediate error will be because of an unhandled exception. As to why that exception is being thrown Also, forget my comment in my last post about not resizing - I'd failed to notice the initial creation size of the tuple (the creation of which isn't checked, but would segfault the app on failure). > Python is pretty stable, so it's usually best to suspect our own code > unless you're heavily into using the C API (which I'm not, so feel free > to ignore me). That's been my experience - stability issues in my Python/C code have almost always come down to refcounting bugs and/or failing to detect and handle or propagate an exception. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: finding name of instances created
On Fri, 2005-01-21 at 16:13 -0800, Andrà wrote: > Short version of what I am looking for: > > Given a class "public_class" which is instantiated a few times e.g. > > a = public_class() > b = public_class() > c = public_class() > > I would like to find out the name of the instances so that I could > create a list of them e.g. > ['a', 'b', 'c'] > > I've read the Python Cookbook, Python in a Nutshell, Programming > Python, Learning Python, ... googled (probably missed something > obvious), all to no avail. Yep. The short answer is that the instances don't have names - they're just bound to names in a particular scope. They can be bound to different names in the same scope or in other scopes. You can get a dictionary for a particular scope using locals() then search it to find the key for a given value. That key will be the name the object is bound to in that scope. In general, you won't want to do that - the need to do so probably suggests a design issue in what you're trying to do. > If I can do the above, I believe I could do the following thing which > is what I am really after eventually. > > Given the statement > > >> a = public_class() > > I would like to generate > > >> my_dict['a'] = private_class() > > so that one could write > > >> a.apparently_simple_method() > > and that, behind the scene, I could translate that as > > >> my_dict['a'].not_so_simple_method() I'm not clear as to why you can't do this as part of the class of which 'a' is an instance. > as well as do things like > > >> for name in my_dict: > >> do_stuff(name) > > Any help, pointers, sketches or outline of solution would be greatly > appreciated. I'm not really able to grasp what you're trying to do (but others might). It wouldn't hurt if you could post a description of what you're actually trying to achieve - /why/ you want this - as that can often be very helpful both in understanding what you're thinking and in suggesting a suitable approach or alternative. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on need help on generator...
On Sat, 2005-01-22 at 10:10 +0100, Alex Martelli wrote: > The answer for the current implementation, BTW, is "in between" -- some > buffering, but bounded consumption of memory -- but whether that tidbit > of pragmatics is part of the file specs, heh, that's anything but clear > (just as for other important tidbits of Python pragmatics, such as the > facts that list.sort is wickedly fast, 'x in alist' isn't, 'x in adict' > IS...). A particularly great example when it comes to unexpected buffering effects is the file iterator. Take code that reads a header from a file using an (implicit) iterator, then tries to read() the rest of the file. Taking the example of reading an RFC822-like message into a list of headers and a body blob: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> for line in infile: if not line.strip(): break headers.append(tuple(line.split(':',1))) .>>> body = infile.read() (By the way, if you ever implement this yourself for real, you should probably be hurt - use the 'email' or 'rfc822' modules instead. For one thing, reinventing the wheel is rarely a good idea. For another, the above code is horrid - in particular it doesn't handle malformed headers at all, isn't big on readability/comments, etc.) If you run the above code on a saved email message, you'd expect 'body' to contain the body of the message, right? Nope. The iterator created from the file when you use it in that for loop does internal read-ahead for efficiency, and has already read in the entire file or at least a chunk more of it than you've read out of the iterator. It doesn't attempt to hide this from the programmer, so the file position marker is further into the file (possibly at the end on a smaller file) than you'd expect given the data you've actually read in your program. I'd be interested to know if there's a better solution to this than: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> initer = iter(infile) .>>> headers = [] .>>> for line in initer: if not line.strip(): break headers.append(tuple(line.split(':',1))) .>>> data = ''.join(x for x in initer) because that seems like a pretty ugly hack (and please ignore the variable names). Perhaps a way to get the file to seek back to the point last read from the iterator when the iterator is destroyed? -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on need help on generator...
On Sat, 2005-01-22 at 17:46 +0800, I wrote: > I'd be interested to know if there's a better solution to this than: > > .>>> inpath = '/tmp/msg.eml' > .>>> infile = open(inpath) > .>>> initer = iter(infile) > .>>> headers = [] > .>>> for line in initer: > if not line.strip(): > break > headers.append(tuple(line.split(':',1))) > .>>> data = ''.join(x for x in initer) > > because that seems like a pretty ugly hack (and please ignore the > variable names). Perhaps a way to get the file to seek back to the point > last read from the iterator when the iterator is destroyed? And now, answering my own question (sorry): Answer: http://tinyurl.com/6avdt so we can slightly simplify the above to: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> headers = [] .>>> for line in infile: if not line.strip(): break headers.append(tuple(line.split(':',1))) .>>> data = ''.join(x for x in infile) at the cost of making it less clear what's going on and having someone later go "duh, why isn't he using read() here instead" but can't seem to do much more than that. Might it be worth providing a way to have file objects seek back to the current position of the iterator when read() etc are called? If not, I favour the suggestion in the referenced post - file should probably fail noisily, or at least emit a warning. What are others thoughts on this? -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on need help on generator...
On Sat, 2005-01-22 at 12:20 +0100, Alex Martelli wrote: > Craig Ringer <[EMAIL PROTECTED]> wrote: > > > .>>> data = ''.join(x for x in infile) > > Maybe ''.join(infile) is a better way to express this functionality? > Avoids 2.4 dependency and should be faster as well as more concise. Thanks - for some reason I hadn't clicked to that. Obvious in hindsight, but I just completely missed it. > > Might it be worth providing a way to have file objects seek back to the > > current position of the iterator when read() etc are called? If not, I > > It's certainly worth doing a patch and see what the python-dev crowd > thinks of it, I think; it might make it into 2.5. I'll certainly look into doing so. I'm not dumb enough to say "Sure, I'll do that" before looking into the code involved and thinking more about what issues could pop up. Still, it's been added to my increasingly frightening TODO list. > > favour the suggestion in the referenced post - file should probably fail > > noisily, or at least emit a warning. > > Under what conditions, exactly, would you want such an exception? When read() or other methods suffering from the same issue are called after next() without an intervening seek(). It'd mean another state flag for the file to keep track of - but I doubt it'd make any detectable difference in performance given that there's disk I/O involved. I'd be happier to change the behaviour so that a warning isn't necessary, though, and I suspect it can be done without introducing backward compatibility issues. Well, so long as nobody is relying on the undefined file position after using an iterator - and I'm not dumb enough to say nobody would ever do that. I've really got myself into hot water now though - I'm going to have to read over the `file' source code before impulsively saying anything REALLY stupid. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a tutorial
On Wed, 2005-01-26 at 09:35 +, Keith Thompson wrote: > "Xah Lee" <[EMAIL PROTECTED]> writes: > [snip] > > Following is a tutorial on Python's classes. > [snip] > > Please stop posting this to comp.lang.c. I'm sure the folks in most > of the other newsgroup aren't interested either -- or if they are, > they can find it in comp.lang.python. Going by the general reaction on c.l.py, I think it'd be more accurate if you left that at "Please stop posting". Sorry for the cross-post, and for this "perl-python" moron who appears to have nothing to do with either, or any knowledge of them. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
On Wed, 2005-01-26 at 22:28 -0500, Davor wrote: > I browsed docs a bit today, and they also confirm what I have believed - > that OO is totally secondary in Python. In fact, > object/classes/metaclasses are nothing but *dictionaries with identity* > in python. Love this approach. I was really impressed with the design of the language, especially this bit. I first "got" it when reading Learning Python 2nd Ed (well *after* I'd been using Python for a while, but it's always good to read even intro books to fill out "obvious" things you might've missed). I love the way the same "It's just a dictionary search" principle applies to inheritance, scoped variable lookups, etc. In Python, even metaclasses just operate on the class dictionary. How pleasantly simple :-) - especially how the step from class factory to metaclass is so small and approachable. I also love the way I can chuck a bunch of objects into a functionally styled processing pipeline, say a series of functions that each just return the result of a listcomp/genexp. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
On Wed, 2005-01-26 at 17:32 -0500, rbt wrote: > Grant Edwards wrote: > > On 2005-01-26, rbt <[EMAIL PROTECTED]> wrote: > > > > > >>Is there an easy way to exclude binary files (I'm working on > >>Windows XP) from the file list returned by os.walk()? > > > > > > Sure, assuming you can provide a rigorous definition of 'binary > > files'. :) > > non-ascii That's not really safe when dealing with utf-8 files though, and IIRC with UCS2 or UCS4 as well. The Unicode BOM its self might (I'm not sure) qualify as ASCII. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Hello
On Thu, 2005-01-27 at 19:39 -0500, g_xo wrote: > Hello everyone, > > I am a python beginner and look forward to learning the language and > working on some interesting projects using it. > > I was wondering if anybody may help me get access to the news group > comp.lang.python I am trying to access it using KNode but I get an > "unable to resolve host name" error. comp.lang.python is gatewayed to this mailing list, and vice versa. You just posted on c.l.p . If you want to access it over NNTP as a newsgroup, rather than receiving it as a mailing list, you just need to ensure you provide your newsreader with a news server that you have access to. Most ISPs provide news servers, often at 'news.ispname.net' if the ISP is 'ispname.net'. You need to get the correct details of which news server to use from your ISP and configure your newsreader to use that. Once your newsread is talking correctly to your ISP's news server, *then* you can subscribe to comp.lang.python. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: example needed: sip + Qt
On Fri, 2005-01-28 at 13:30 +0100, Uwe Mayer wrote: > Hi, > > can someone provide me with a running example for subclassing QWidget (or > something similarly simple) in C++ and then creating SIP (4.x+) bindings > for in for Python (2.3+)? Out of curiosity, would this be for an extension module used in an embedded Python interpreter, or for plain extension module for use with a standalone interpreter? I'm afraid I can't help you with your specific problem, though I'll be interested to hear if anybody here does know. If you don't have any luck here, try the PyQt/PyKDE list (and search its archives first). -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic class methods misunderstanding
On Fri, 2005-01-28 at 11:17 -0500, Bill Mill wrote: > Beautiful! thank you very much. Looking into the "new" module in > python 2.4, that's equivalent to: > > self.m = type(self.__init__)(method, self, Test) > > I didn't know that you could call types to create another type. Well, a type is essentially a class (in the OOP sense, not the python- specific classobj sense). You can call a type or class to create an instance of that class or type. Here, you call the 'instancemethod' type to create an instance of type 'instancemethod'. Makes sense ... in hindsight. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Dr. Dobb's Python-URL! - weekly Python news and links (Feb 9)
QOTW: "Such infrastructure building is in fact fun and instructive -- as long as you don't fall into the trap of *using* such complications in production code, where Python's simplicity rules;-)." -- Alex Martelli http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/41a6c0e1e260cd72/ "C++ to Python is a steep 'unlearning' curve..." -- Philip Smith "URK -- _my_ feeling is that we have entirely *too many* options for stuff like web application frameworks, GUI toolkits, XML processing, ..." -- Alex Martelli http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9bdc98acb5acae4/ "We should concentrate on *real* problems, ones that exist in real code, not ones that mostly exist in wild-eyed prose that consists of predictions of pain and death that conspicuously fail to occur, no matter how many times they are repeated or we are exhorted to heed them or face our doom." -- Jeremy Bowers http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/ Special thanks this week to Dean Goodmanson for his help identifying several items. The Online Computer Library Center contest is open. It closes May 15. Among the usual C++ and Java languages, Python also is available for selection: http://www.oclc.org/research/researchworks/contest/default.htm#guidelines Baoqui Chi runs into a documented, but easily overlooked, trap in the handling of __del__ methods and receives good advice on better fixes: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/13ec343eb0a37247/ Steve Holden explains how to think about bytecode management: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/59c0466111b075b8/ in a conversation aimed at Pyro improvement. Michael Tobis sparks off a discussion on the underlying nature of generators and offers a caution on jumping to conclusions about the writings of non-native English speakers: http://mail.python.org/pipermail/python-list/2005-January/263448.html Derek finds out that the Python interpereter is smarter about finding resources than it lets on: http://mail.python.org/pipermail/python-list/2005-January/263473.html irc.freenode.net #python is overcrowded: the entrance now routes to #python-cleese or #python-gilliam: http://divmod.org/users/washort/python-split.htmlmklm Steve Holden provides an evocative illustration that the rules are there for a reason, even if breaking them doesn't hit you (*ahem*) immediately: http://mail.python.org/pipermail/python-list/2005-February/263851.html In response to a question about rewriting exceptions to include more information, Stefan Behnel gets a couple of rather useful answers: http://mail.python.org/pipermail/python-list/2005-February/263843.html Netcraft Reports 33K Zope servers in January, 55K in February! http://mail.zope.org/pipermail/zope-announce/2005-February/001651.html Joakim Stork discovers that thanks to classes being first class objects in Python, sometimes the best solution is so simple it's often possible to miss it entirely: http://mail.python.org/pipermail/python-list/2005-February/263891.html Someone posts an interesting attempt at a cross-platform way to discover the user's home directory: http://mail.python.org/pipermail/python-list/2005-February/263921.html Metaclasses are handy things. Steven Bethard demonstrates a nice simple use case: http://mail.python.org/pipermail/python-list/2005-February/264037.html As John Machin demonstrates, generating SQL in Python doesn't have to be ugly: http://mail.python.org/pipermail/python-list/2005-February/264248.html Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently su
Dr. Dobb's Python-URL! - weekly Python news and links (Feb 9)
QOTW: "Such infrastructure building is in fact fun and instructive -- as long as you don't fall into the trap of *using* such complications in production code, where Python's simplicity rules;-)." -- Alex Martelli http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/41a6c0e1e260cd72/ "C++ to Python is a steep 'unlearning' curve..." -- Philip Smith "URK -- _my_ feeling is that we have entirely *too many* options for stuff like web application frameworks, GUI toolkits, XML processing, ..." -- Alex Martelli http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9bdc98acb5acae4/ "We should concentrate on *real* problems, ones that exist in real code, not ones that mostly exist in wild-eyed prose that consists of predictions of pain and death that conspicuously fail to occur, no matter how many times they are repeated or we are exhorted to heed them or face our doom." -- Jeremy Bowers http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/ Special thanks this week to Dean Goodmanson for his help identifying several items. The Online Computer Library Center contest is open. It closes May 15. Among the usual C++ and Java languages, Python also is available for selection: http://www.oclc.org/research/researchworks/contest/default.htm#guidelines Baoqui Chi runs into a documented, but easily overlooked, trap in the handling of __del__ methods and receives good advice on better fixes: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/13ec343eb0a37247/ Steve Holden explains how to think about bytecode management: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/59c0466111b075b8/ in a conversation aimed at Pyro improvement. Michael Tobis sparks off a discussion on the underlying nature of generators and offers a caution on jumping to conclusions about the writings of non-native English speakers: http://mail.python.org/pipermail/python-list/2005-January/263448.html Derek finds out that the Python interpereter is smarter about finding resources than it lets on: http://mail.python.org/pipermail/python-list/2005-January/263473.html irc.freenode.net #python is overcrowded: the entrance now routes to #python-cleese or #python-gilliam: http://divmod.org/users/washort/python-split.htmlmklm Steve Holden provides an evocative illustration that the rules are there for a reason, even if breaking them doesn't hit you (*ahem*) immediately: http://mail.python.org/pipermail/python-list/2005-February/263851.html In response to a question about rewriting exceptions to include more information, Stefan Behnel gets a couple of rather useful answers: http://mail.python.org/pipermail/python-list/2005-February/263843.html Netcraft Reports 33K Zope servers in January, 55K in February! http://mail.zope.org/pipermail/zope-announce/2005-February/001651.html Joakim Stork discovers that thanks to classes being first class objects in Python, sometimes the best solution is so simple it's often possible to miss it entirely: http://mail.python.org/pipermail/python-list/2005-February/263891.html Someone posts an interesting attempt at a cross-platform way to discover the user's home directory: http://mail.python.org/pipermail/python-list/2005-February/263921.html Metaclasses are handy things. Steven Bethard demonstrates a nice simple use case: http://mail.python.org/pipermail/python-list/2005-February/264037.html As John Machin demonstrates, generating SQL in Python doesn't have to be ugly: http://mail.python.org/pipermail/python-list/2005-February/264248.html Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently su
Re: Protecting Python source
On Mon, 2004-11-29 at 18:04, Peter Maas wrote: > I can think of 3 reasons to prevent tampering: > > - You need money and want to sell your software on a "per seat" basis. If you mean that you therefore must add built-in copy-protection, then sure. Users will always get around it if they really want to, so tamper-resistance is probably closer to the truth, but it'll slow them down. On the other hand, one can license software per-seat quite effectively without software enforcement, or with only informative software enforcement ("By the way, you appear to be over your seat count."). In many cases this is good enough - the user can always crack / steal your software, tamper resistant or not (witness: the games industry), and code without copy protection is a LOT friendly. For example, my employer currently relies on software that has a dongle. The software manufacturer has gone out of business, so if that dongle dies we're in trouble, as development of a replacement is moving slowly. In future, if we're given the choice between a product that's superior in price or functionality but has opressive copy protection and one that's more limited or more expensive, but has no software enforcement of copy protection, we'll buy the inferior or overpriced one. We're quite capable of monitoring our own license compliance. Those who aren't are also generally quite capable of 'fixing' the software, tamper resistant or not, so I really don't see the point. > - You don't want customers to fiddle with your code and then innocently >call for support and demand "bug fixes" for free. There, what you really want is tamper-evident code not tamper-proof code. That's quite a bit more practical IMO, and may be a good place to look at digital signing. > - Your customer demands closed source because the code contains trade >secrets. My understanding is that that's never guaranteed safe, no? Or are restrictions against reverse engineering now commonly enforcable? -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Class methods in Python/C?
Hi folks I've been doing some looking around, but have been unable to find out how to implement class methods on Python objects written in C. "Why are you using C?" you ask? Yeah, so do I. However, I need to provide bindings for an application that Python is embedded into, and thanks to Qt the bindings are going to be both simple and quite powerful. However, I need a way to do class methods... If anybody has any tips on this, It'd be much appreciated. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list
Re: Class methods in Python/C? [ANSWER]
On Tue, 2004-11-30 at 20:39, Nick Coghlan wrote: > You probably want to look at staticmethod(). (classmethod() is slightly > different, and probably not what you want. In fact, classmethod() is > practically > *never* what you want. Guido wrote it himself, and even he ended up not using > it) Hmm, I've always rather favoured class methods myself. However, that's not the point - the same question can apply just as well to static methods. I know how to construct both in Python, though I rarely use static methods, only class methods. What I was after is a way to define a static method in a C extension module. I just found it - in the library reference, of course. I'd simply missed it before. For anybody else looking through the archives to answer this question later: http://docs.python.org/api/common-structs.html It turns out there are calling convention flags to specify class methods and static methods. From the docs: METH_CLASS The method will be passed the type object as the first parameter rather than an instance of the type. This is used to create class methods, similar to what is created when using the classmethod() built-in function. New in version 2.3. METH_STATIC The method will be passed NULL as the first parameter rather than an instance of the type. This is used to create static methods, similar to what is created when using the staticmethod() built-in function. New in version 2.3. Sorry for the noise everybody, I could've sworn I looked over that already. -- Craig Ringer -- http://mail.python.org/mailman/listinfo/python-list