"struct" module problem w/ pyinstaller


,
I am trying to create exectuables on inux using "pyinstaller". I am
using pyinstaller-1.3, RHEL 4.4, Python 2.5.

The executables fail to run. The problem returned is pertaining to
"struct.py" not being able to find the module "_struct".

struct.py is located under /usr/local/lib/python-2.5/, and there is a
_struct.o (no _struct.py anywhere) located under /usr/local/lib/
python-2.5/lib-dynload.

When trying to run the executable, the loader returns:
File "/usr/local/lib/python2.5/struct.py", line 30, in
ImportError: No module named _struct

The line in question is:
from _struct import Struct, error

I am a python neophyte. If someone could give me some information, I
would appreciate it.
Posted On: Monday 5th of November 2012 02:22:21 AM Total Views:  126
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




constructor question

lets supose i have a object >>>class a: >>> __init__(self,b): >>> self.b=b >>>object=a(2) how can I bind the object with "print". I supose that this should be possible with a constructor. but I don't know how. >>>print a 2 >>> Something like this Thnx
VIEWS ON THIS POST

55

Posted on:

Sunday 4th November 2012
View Replies!

Python / C++ embed halfway working - question about constructors

I am running my C++ / Python App on a MacBook Pro with 2.5 installed I have had some success in that I can load a module, get the class, get the reference, but when the python class calls another python class I don't ever seem to get the object back from the constructor. I am doing the following in the C++ file: Py_Initialize() PyObject* module = PyImport_Import(moduleName); PyObject* class = PyObject_GetAttrString(module, className); Py_DECREF(module); Py_DECREF(class); // Create the TSAFE object constructor arguments: // a file, and an int PyObject* tsafeOutputFile = PyFile_FromString("TsafeOutput", "a"); PyObject* resolveValue = PyInt_FromLong(0); PyObject* classArgumentTuple = PyTuple_New(2); PyTuple_SetItem(classArgumentTuple, 0, tsafeOutputFile); PyTuple_SetItem(classArgumentTuple, 1, resolveValue); classReference = PyEval_CallObject(class, classArgumentTuple); Py_MY_INCREF(classReference); Py_MY_DECREF(class); PyObject* pythonMethod = PyObject_GetAttrString(classReference, "registerFlight"); registerReturn = PyEval_CallObject(pythonMethod, argumentTuple); Py_MY_DECREF(pythonMethod); Py_MY_DECREF(argumentTuple); Essentially the code above should: call class constructor call registerFlight() calls registerFlight_() calls _flightPointer() -> where I never get by the section of code where the Flight.py Constructor get called Each flight should be added to my class object to build up a dictionary of flights. The python class methods getting called are detailed below and I never get by the call to _flightPointer(). I have opened a file and write to it at each step of code and I never get all the way through the _flightPointer() method Is there something I am missing here I cannot print the data out of the __init__ method in the Flight.py file I did not include all of the code here because I am hoping the issue is I have got something wrong and it's not the python code but me. Ant help will be greatly appreciated. def registerFlight(self, ID, ACtype="", IFR=1, RVSM=0, ATCcat="", filedAlt=0, filedSpeed=0): "register flight (unitless args for outside client)" filedAlt *= FL # FL = Flight Level = 100 ft filedSpeed *= kn # kn = knots self.registerFlight_(ID, ACtype, IFR, RVSM, ATCcat, filedAlt,filedSpeed) def registerFlight_(self, ID, ACtype="", IFR=1, RVSM=0, ATCcat="", filedAlt=0, filedSpeed=0): "register flight (accepts arguments with units)" flight = self._flightPointer(ID) flight.registerFlight(ACtype, IFR, RVSM, ATCcat, filedAlt, filedSpeed) def _flightPointer(self, ID, track=0, Flight=Flight): "manage tracked and untracked flight lists" fltPointerFile = open('TSAFE_flightPointerOut', 'a') fltPointerFile.write("In the _flightPointer function\n") flights = self.flights unflights = self.untrackedFlights if ID in flights: fltPointerFile.write("in first IF\n") return flights[ID] if track: # new data record is a track update - start tracking if ID in unflights: # move flight to tracked status flights[ID] = unflights[ID] del unflights[ID] else: flights[ID] = Flight(ID) # new Flight object return flights[ID] ## THIS IS THE SECTION OF CODE NOT RETURNING A REFERENCE TO THE Flight object if ID not in unflights: fltPointerFile.write(ID) fltPointerFile.write(" In if ID not in unflights\n\n") unflights[ID] = Flight(ID) fltPointerFile.write("BACK FROM CALLING Flight(ID)\n") unflightsValue = ("unflights[ID]", unflights[ID]) unflightsString = str(unflightsValue) fltPointerFile.write("Return value is ") fltPointerFile.write(unflightsString) fltPointerFile.write('\n') return unflights[ID]
VIEWS ON THIS POST

143

Posted on:

Sunday 4th November 2012
View Replies!

Constructor re-initialization issue

all, I have come across this issue in Python and I cannot quite understand what is going on. class Param(): def __init__(self, data={}, condition=False): if condition: data['class']="Advanced" print data In the previous example, I expect the variable data to be re- initialized every time I construct an object type Param. However, when I do the following: Param(condition=True) Param(condition=False) The second call still prints {'class': 'Advanced'} Shouldn't data be initialized to {} since it is the default in __init__ Why would the state of data be preserved between two independent instantiations
VIEWS ON THIS POST

264

Posted on:

Sunday 4th November 2012
View Replies!

Suggestions for structure of HTML-generating app

This isn't a strictly Python question but I wonder if someone could give me some clues here. I've been writing a number of stand-alone apps that use CherryPy as an embedded web server for displaying processed data and interacting with the application. To go along with this I've also been using CherryTemplate as a handy HTML template generator. My question is this - what's the best way to separate the application code from the UI generation code from the "raw" HTML To give you an idea what I mean, the core application code is fairly straightforward and writes to SQLite databases and/or dictionaries. That's the easy bit. The data then often needs a fair amount of massaging to make it suitable for display. For example, one app I've got monitors network utilisation so writes bits-per-second values to SQLite. The UI then takes those values and generates bar charts (done by cropping an image to size before putting it into a table cell), changes text colour if utilisation is >90% and so on etc. I've done this with lots of Python code embedded in the CherryTemplate pages but that becomes a real maintenance headache as the templates become huge and the code and HTML is scattered around with no clear distinction between the two. I've also tried using pure-Python HTML generation functions that output, say, entire tables made up from the source data that are then called by the template, but then you end up with Python functions with lots of HTML embedded in them which, again, ends up being difficult to keep track of. Are there any good approaches of doing this kind of thing that I've missed, or am I resigned to having HTML and Python code mixed and so will just have to keep all that nastiness to as few modules as possible
VIEWS ON THIS POST

102

Posted on:

Sunday 4th November 2012
View Replies!

Boa constructor debugging - exec some code at breakpoint?

there.. I'm using boa constructor to debug a python application. For my application, I need to insert break points and execute some piece of code interactively through shell or someother window when the breakpoint has been reached. Unfortunately the shell I think is a seperate process so whatever variables are set while executing in debugger dont appear in the shell when I try to print using print statement. Can anyone tell me how can I do this Really appreciate any support,
VIEWS ON THIS POST

87

Posted on:

Sunday 4th November 2012
View Replies!

ctypes: return a pointer to a struct

I'm not able to build IP2Location's Python interface so I'm trying to use ctypes to call its C interface. The functions return a pointer to the struct below. I haven't been able to figure out how I should declare the return type of the functions and read the fields. Any hint is appreciated. typedef struct { char *country_short; char *country_long; char *region; char *city; char *isp; float latitude; float longitude; char *domain; char *zipcode; char *timezone; char *netspeed; } IP2LocationRecord;
VIEWS ON THIS POST

157

Posted on:

Sunday 4th November 2012
View Replies!

Re: Data structure recommendation?

* Steven Clark: > Hi all- > > I'm looking for a data structure that is a bit like a dictionary or a > hash map. In particular, I want a mapping of floats to objects. > However, I want to map a RANGE of floats to an object. This solution may be more than you actually need, but I implemented two metric space indexes which would do what you want (and I wanted to plug it anyway ): http://well-adjusted.de/mspace.py/ You can do arbitrary range searches and nearest-neighbour search in these indexes provided you have a metric distance function for the objects you want to index. The distance function in your case would simply be the absolute difference between your floats. If every log message was contained in objects of this type: class LogMessage(object) def __init__(self, timestamp, object): self.timestamp = timestamp self.message = message you could write a distance function for these objects like this: def log_distance(log1, log2): return abs(log1.timestamp - log2.timestamp) and then you would create and search an index like this: from mspace import VPTree index = VPTree(all_log_messages, log_distance) index.search(single_msg, 10) The last line would yield all log messages within ten seconds (or whatever the unit of your timestamps is) of the given LogMessage single_msg. You could also use index.nn_search(single_msg, 3) To find the three messages closest to the given single_msg. Searching should be quite fast (O(log(n)), but indexing might take some time (O(n*log(n))). The problem is that VPTrees have to be constructed from the complete data set initially. They cannot grow. The alternative from mspace.py, BKTrees, may grow over time but they don't work with non-discrete distances. If you want to use them, you'd have to convert your timestamps to int/long first. J. -- In the west we kill people like chickens. [Agree] [Disagree]
VIEWS ON THIS POST

173

Posted on:

Monday 5th November 2012
View Replies!

Convert PyIDispatch object to struct IDispatch*

I am trying to use ctypes to call dll functions. One of the functions requires argument "struct IDispatch* ". I do have a PyIDispatch object in python. How can I convert this "PyIDispatch object" to "struct IDispatch* "
VIEWS ON THIS POST

59

Posted on:

Monday 5th November 2012
View Replies!

Calling CVF-Fortran-dll with ctypes and simple structure

Hi all, I deal with the old problem passing characters from python to a fortran dll build with CFV6.6c. I reduced our complex structure to a simple one. Here is the Fortran code: SUBROUTINE DEMO2L(s) C sample for calling CVF6.6c-DLLs from C vb/vba/python with simple structure !DEC$ ATTRIBUTES DLLEXPORT:EMO2L TYPE rcDEMO INTEGER a REAL b CHARACTER c*9 END TYPE TYPE(rcDEMO) :: s C WRITE(*,*) s.a, s.b, s.c C sample calculation: s.a = s.a*10 s.b = s.b**2.3 s.c = 'Sample' RETURN END From VB the calling is very simple: Declare Sub DEMO2L Lib "release\demo1l.dll" (ByRef k As rcDEMO) Type rcDEMO a As Long b As Single c As String * 9 End Type Dim k As rcDEMO Sub run() k.a = 2 k.b = 3# k.c = "Test" Call DEMO2L(k) Debug.Print k.a, k.b, k.c End Sub and result to: " 20 12,5135 Sample" When I try this from python: from ctypes import * class rcDemo(Structure): _fields_ = [ ('a', c_int), ('b', c_float), ('c', c_char_p), ] mydll = windll.LoadLibrary("release\DEMO1L.DLL") rc = rcDemo() rc.a = 2 rc.b = 3. rc.c = "Test56789" mydll.DEMO2L(byref(rc)) print rc.a print rc.b print ">" + rc.c + "" + rc.c + "
VIEWS ON THIS POST

143

Posted on:

Monday 5th November 2012
View Replies!

struct unpack

If I run: testValue = '\x02\x00' junk = struct.unpack('h', testValue) Everything works but If I run testValue = raw_input("Enter Binary Code..:") inputting at the console '\x02\x00' junk = struct.unpack('h', testValue) It errors out with Traceback (most recent call last): File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in junk = struct.unpack('h', testValue) File "struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 2 any ideas
VIEWS ON THIS POST

65

Posted on:

Monday 5th November 2012
View Replies!

Boa Constructor Mac crash when adding menubar

hi. Every time I go through the Boa Constructor tutorial and I get to the "Add a Menu Bar" section, Boa Constructor crashes after I select a wx.menubar and then left click either in the Data or design frames. I saw a post on the internet from the usenet about this very question, but was from 2005, and there was a reply that there would be a fix, but I can't figure out if this issue was supposed to be resolved.
VIEWS ON THIS POST

91

Posted on:

Monday 5th November 2012
View Replies!

For discussion, semantic construct

Here is a construction for passing parameters. I include the Python idea, a C/C++ equivalent, and write a little about it. (Blech.) It is a little obscure, and my use cases are not as good as yours. So say yours. The presentation is structured: problem, solution. Problem: Sometimes you need to signal a particular meaning of a parameter. These examples are from my library. uniform( node.toprettyxml, indent, newl, encoding ) It is in a proxy class for the xmlnode class; outer modules call node.dump(), and can specify these parameters. @guibind( listbox, "" ) def onenter( event ): It is a time-saving function to keep my train of thought up to speed when I'm writing, one of the reasons Python suits me. @execute_func( start_new_thread ) def anonproc(): It makes more sense (*subjective) to me to write "and execute the 'next thing' in a new thread", than to write the thing, and then go back and say execute. A lot more, in fact. (*If it doesn't to you, then ignore the application, and just consider the construct independently.) Like the prior, it maintains the speed and level of the time that I'm spending on code. Last but not least, class Workbook( EasyXML ): descripts= Descp( "bold", req= "1" ), Descp( "text" ) It keeps a list of constructor descriptions, which the base class constructor uses, roughly stated, as domain knowledge, that is further information, in parsing constructor parameters. In 'guibind', sometimes it makes sense to include the control that is being bound in a parameter, and sometimes it distinctly doesn't. In 'uniform', the next layer may or may not specify a particular argument, but to the end of abstraction/encapsulation, middle layers do not specify default values for parameters. In 'execute_func', the specified function may occur in varying places in the argument list, including as a keyword-only argument. In 'Descp', one descriptor is allowed to I am suggesting that these examples have a common thread, and there is an elegant resolution. It may not even be 'recipie' material, let alone 'std. lib.' material, but it is interesting, and I want to know what others think about the merits and demerits of it. Where is it strong and weak The thread they share is the meaning of flags. In 'uniform', the outer user can call a target function in a uniform way; regardless of what decisions the calling code makes, the actual call can still only occur once in it. If outer code decides to specify one parameter in one branch, and another in another, it can merely initialize both to a special flag, and non-defaults will only be specified if that flag is replaced. The flag is a value that is guarateed to be unique, regardless of what semantic meaning the parameter has, though pretty only applicable in cases where the default is not None, as well as somewhat trivialized if the default is the flag too. It is most useful where default arguments are complicated, or their use is contrary to abstraction. In 'guibind', the flag value allows the user to specify his or her own calling signature, and placement of the variable of the control. Is it the first parameter The last Always a specific name These questions are left for the outer user to answer, varying on a case by case basis. In execute_func, the function is the same. The meaning that the function has in the call to the tertiary function is open to the outer user to decide. And in 'Descp', the argument that sets the content of the XML node, as opposed to child nodes of it, as well as whether it's required or not, is open to the outer user's discretion. The idiom looks a little funny (*subjective). Who knows why, but here it is, in an abstracted case from the above. for ar in ars: if ar is SpecialFlag: replace it with meaning for kwar, kwarval in kwars.items(): if kwarval is SpecialFlag: replace it with meaning SpecialFlag itself has a pretty simple definition. SpecialFlag= object() It is never an int, so never confused with an int, nor ever a special case of int, such as MAX_INT or -1. It is never a string either, so the user can pass any value -or- -this- to outside functions as a parameter. It is a signal that always stays out of the way. Here are the same examples with SpecialFlag present. As the names have meaning too, and I haven't (as yet!) completed the abstraction abstraction, the flag is a different object with a different name in these cases. uniform( node.toprettyxml, DefaultA, '\n', DefaultA ) uniform( node.toprettyxml, '\t', '', DefaultA ) uniform( node.toprettyxml, ' ', DefaultA, 'UTF-8' ) The signatures are identical: three parameters, no keywords. Prior to this invocation, set indent, newl, encoding= DefaultA, DefaultA, DefaultA, and then only call node.toprettyxml once. uniform( node.toprettyxml, indent, newl, encoding ) And the parameters have the right meaning, whether you specify them or not. @guibind( listbox, "", EventN, ControlN ) @guibind( listbox, "", ControlN ) @guibind( listbox, "", EventN, cont= ControlN ) Then the function specified has the right parameters, although at the extra cost of rearranging argument and keyword argument lists, once at each call. @execute_func( start_new_thread, func= FuncA ) @execute_func( Thread, target= FuncA ) @execute_func( urlretrieve, 'what.com', reporthook= FuncA ) In the two cases of the wrappers, they offer the interesting property that the function name after execution contains the return value from the calls. The function can be accessed in a different way, and that's somewhat open. class Workbook( EasyXML ): descripts= Descp( "bold", req= "1" ), Descp( "text", DataN ) So instantiating a workbook is a snap. book= Workbook( bold= False, text= "Bus hours and server hours per day per week" ) And the constructor of Workbook, which simply defaults to that of EasyXML, checks the class definition of 'self' for the descriptor list, and reads that 'text' now refers to a string that will merely be the content of a node, and bold refers to a node attribute. I'm sure there are other ways to do this. This is one of them; how does it measure up
VIEWS ON THIS POST

52

Posted on:

Monday 5th November 2012
View Replies!

RE: Populating huge data structures from disk

> Note that you're not doing the same thing at all. You're > pre-allocating the array in the C code, but not in Python (and I don't > think you can). Is there some reason you're growing a 8 gig array 8 > bytes at a time > > They spend about the same amount of time in system, but Python spends 4.7x > as much > CPU in userland as C does. > > Python has to grow the array. It's possible that this is tripping a > degenerate case in the gc behavior also (I don't know if array uses > PyObjects for its internal buffer), and if it is you'll see an > improvement by disabling GC. That does explain why it's consuming 4.7x as much CPU. > > x = lengthy_number_crunching() > > magic.save_mmap("/important-data") > > > > and in the application do... > > > > x = magic.mmap("/important-data") > > magic.mlock("/important-data") > > > > and once the mlock finishes bringing important-data into RAM, at > > the speed of your disk I/O subsystem, all accesses to x will be > > hits against RAM. > > You've basically described what mmap does, as far as I can tell. Have > you tried just mmapping the file Yes, that would be why my fantasy functions have 'mmap' in their names. However, in C you can mmap arbitrarily complex data structures whereas in Python all you can mmap without transformations is an array or a string. I didn't say this earlier, but I do need to pull more than arrays and strings into RAM. Not being able to pre-allocate storage is a big loser for this approach.
VIEWS ON THIS POST

144

Posted on:

Monday 5th November 2012
View Replies!

Re: Populating huge data structures from disk

On Nov 6, 2007 2:40 PM, Michael Bacarella wrote: > > > > For various reasons I need to cache about 8GB of data from disk into > core on > > > application startup. > > > > Are you sure On PC hardware, at least, doing this doesn't make any > > guarantee that accessing it actually going to be any faster. Is just > > mmap()ing the file a problem for some reason > > > > I assume you're on a 64 bit machine. > > Very sure. If we hit the disk at all performance drops unacceptably. The > application > has low locality of reference so on-demand caching isn't an option. We get > the behavior > we want when we pre-cache; the issue is simply that it takes so long to > build this cache. > You're not going to avoid hitting disk just by reading into your memory space. If your performance needs are really so tight that you can't rely on the VM system to keep pages you're using in memory, you're going to need to do this at a much lower (and system specific) level. mmap() with a reasonable VM system shouldn't be any slower than reading it all into memory. > > > Building this cache takes nearly 2 hours on modern hardware. I am > surprised > > > to discover that the bottleneck here is CPU. > > > > > > The reason this is surprising is because I expect something like this to > be > > > very fast: > > > > > > #!python > > > import array > > > > > > a = array.array('L') > > > > > > f = open('/dev/zero','r') > > > > > > while True: > > > > > > a.fromstring(f.read(8)) > > > > This just creates the same array over and over, forever. Is this > > really the code you meant to write I don't know why you'd expect an > > infinite loop to be "fast"... > > Not exactly. fromstring() appends to the array. It's growing the array > towards You're correct, I misread the results of my testing. > infinity. Since infinity never finishes it's hard to get an idea of how > slow > this looks. Let's do 800MB instead. > That makes this a useless benchmark, though... > Here's an example of loading 800MB in C: > > $ time ./eat800 > > real 0m44.939s > user 0m10.620s > sys 0m34.303s > > $ cat eat800.c > #include > #include > #include > > int main(void) > { > int f = open("/dev/zero",O_RDONLY); > int vlen = 8; > long *v = malloc((sizeof (long)) * vlen); > int i; > > for (i = 0; i < 100000000; i++) { > if (i >= vlen) { > vlen *= 2; > v = (long *)realloc(v,(sizeof (long)) * vlen); > } > read(f,v+i,sizeof (long)); > } > return 0; > } > > Here's the similar operation in Python: > $ time python eat800.py > > real 3m8.407s > user 2m40.189s > sys 0m27.934s > > $ cat eat800.py > #!/usr/bin/python > > import array > a = array.array('L') > > f = open('/dev/zero') > for i in xrange(100000000): > a.fromstring(f.read(8)) > > Note that you're not doing the same thing at all. You're pre-allocating the array in the C code, but not in Python (and I don't think you can). Is there some reason you're growing a 8 gig array 8 bytes at a time > They spend about the same amount of time in system, but Python spends 4.7x > as much > CPU in userland as C does. > Python has to grow the array. It's possible that this is tripping a degenerate case in the gc behavior also (I don't know if array uses PyObjects for its internal buffer), and if it is you'll see an improvement by disabling GC. > And there's no solace in lists either: > > $ time python eat800.py > > real 4m2.796s > user 3m57.865s > sys 0m3.638s > > $ cat eat800.py > #!/usr/bin/python > > import struct > > d = [] > f = open('/dev/zero') > for i in xrange(100000000): > d.append(struct.unpack('L',f.read(8))[0]) > > > cPickle with protocol 2 has some promise but is more complicated because > arrays can't be pickled. In a perfect world I could do something like this > somewhere in the backroom: > > x = lengthy_number_crunching() > magic.save_mmap("/important-data") > > and in the application do... > > x = magic.mmap("/important-data") > magic.mlock("/important-data") > > and once the mlock finishes bringing important-data into RAM, at > the speed of your disk I/O subsystem, all accesses to x will be > hits against RAM. > You've basically described what mmap does, as far as I can tell. Have you tried just mmapping the file > > Any thoughts > > Did you try array.fromfile like I suggested > -- > http://mail.python.org/mailman/listinfo/python-list >
VIEWS ON THIS POST

102

Posted on:

Monday 5th November 2012
View Replies!

Re: Populating huge data structures from disk

On Nov 6, 2007 3:42 PM, Michael Bacarella wrote: > > > Note that you're not doing the same thing at all. You're > > pre-allocating the array in the C code, but not in Python (and I don't > > think you can). Is there some reason you're growing a 8 gig array 8 > > bytes at a time > > > > They spend about the same amount of time in system, but Python spends 4.7x > > as much > > CPU in userland as C does. > > > > Python has to grow the array. It's possible that this is tripping a > > degenerate case in the gc behavior also (I don't know if array uses > > PyObjects for its internal buffer), and if it is you'll see an > > improvement by disabling GC. > > That does explain why it's consuming 4.7x as much CPU. > > > > x = lengthy_number_crunching() > > > magic.save_mmap("/important-data") > > > > > > and in the application do... > > > > > > x = magic.mmap("/important-data") > > > magic.mlock("/important-data") > > > > > > and once the mlock finishes bringing important-data into RAM, at > > > the speed of your disk I/O subsystem, all accesses to x will be > > > hits against RAM. > > > > You've basically described what mmap does, as far as I can tell. Have > > you tried just mmapping the file > > Yes, that would be why my fantasy functions have 'mmap' in their names. > > However, in C you can mmap arbitrarily complex data structures Well, for certain limited values of "arbitrary", but okay. It's true that you can cast pointers into the mmapped region into, say, pointers to a struct of structs. The Python equivalent would be to have your Python classes be wrappers around access to this memory buffer, calculating the offset needed to get any particular field. ctypes.Structure is probably a good starting point if you want to implement this. Sadly, it looks like mmap.mmap() doesn't expose the address of its buffer so you'll either need to use the C mmap (via ctypes, probably) or use array.array to load the bytes and use it's bufferinfo() to get the address to load your structs from. >whereas > in Python all you can mmap without transformations is an array or a string. Read "array or string" as "stream of bytes" in this context. > I didn't say this earlier, but I do need to pull more than arrays > and strings into RAM. Not being able to pre-allocate storage is a big > loser for this approach. > It is a little annoying that there's no way to pre-allocate an array. It doesn't over-allocate, either, so building on a few bytes at a time is pretty much worst case behavior.
VIEWS ON THIS POST

110

Posted on:

Monday 5th November 2012
View Replies!

Re: ctypes - pointer to array of structs?

skip@pobox.com schrieb: > (Is this the right place to ask ctypes questions There's a mailing list > but the last post to it seems to have been in November 2006.) You could use the ctypes-users mailing list: https://lists.sourceforge.net/lists/...o/ctypes-users It is also available via gmane. > Using ctypes I reference a structure which contains a pointer to an array of > another structure: > > class SYMBOL(Structure): > _fields_ = [("symbol", c_char_p), > ("num", c_int), > ("units", c_int), > ("baseprice", c_int), > ("active", c_int)] > SYMBOL_PTR = POINTER(SYMBOL) > > class TABLE(Structure): > _fields_ = [("map", SYMBOL_PTR), > ("nsymbols", c_uint), > ...] > > Effectively, TABLE.map is an array of TABLE.nsymbols SYMBOLS. How to I > reference elements in that array In C I would just treat TABLE.map like an > array and index into it (for i=0; i< TABLE.nsymbols; i++) ...). This is > data returned from a C library, not something I'm building in Python to pass > into C. Assuming you got a pointer to TABLE from a function call like this: somefunction.restype = POINTER(TABLE) ptab = somefunction(...) then you should be able to use this code (C has the '*' operator to derefence pointers, Python does not so you have to use p[0] instead of *p): table = ptab[0] symp = table.map for i in range(table.nsymbols): sym = symp[0] print sym.symbol, sym.num, sym.units, sym.baseprice Thomas
VIEWS ON THIS POST

149

Posted on:

Monday 5th November 2012
View Replies!

struct.unpack less than 1 byte

hello all, i need to read from a file a struct like this [1byte, 12bits, 12bits] reading 1 byte or more is not a problem ... but the 12 bits values are ...
VIEWS ON THIS POST

59

Posted on:

Monday 5th November 2012
View Replies!

Re: Problems with struct.pack()

On Wed, 2007-10-10 at 19:00 -0500, Robert Dailey wrote: > > > I have opened a unicode file for writing: > > import codecs > file = codecs.open( "somefile.dat", "wb", "utf-16" ) > > and I attempt to do this: > > file.write( struct.pack ( "I", 5000 ) ) > > However, this won't work because the encoding of the string returned > by "pack" isn't unicode. I'm a bit confused right now as to how I can > get this to work. I can't allow the unicode-ness of the file interfere > with the actual order of the bytes that pack() is returning (In other > words, don't pack NULL characters in there) Please start at the beginning. What are you actually trying to accomplish and why do you think you need to write arbitrary binary data into a file that is supposed to be a UTF-16 encoded Unicode text file -- Carsten Haese http://informixdb.sourceforge.net
VIEWS ON THIS POST

76

Posted on:

Monday 5th November 2012
View Replies!

Confusion regarding constructor as default value

Why are the following different def AddRow(self, rowName, tableRow=TableRow(ReleaseDate(""), ExpiryDate(""))): # check to see if the row already exists, if not add it to the container if not self.dict.has_key(rowName): self.dict[rowName] = tableRow def AddRow(self, rowName, tableRow): # check to see if the row already exists, if not add it to the container if not self.dict.has_key(rowName): self.dict[rowName] = TableRow(ReleaseDate(""), ExpiryDate("")) It seems that when I use the first function that I'm getting duplicate objects in self.dict
VIEWS ON THIS POST

95

Posted on:

Monday 5th November 2012
View Replies!

Noob: Loops and the 'else' construct

I have just come across a site that discusses Python's 'for' and 'while' loops as having an (optional) 'else' structure. At first glance I interpreted it as being a bit like the 'default' structure in PHP's switch block... But the switch block isn't a loop, so, I am now confused as to the reason for using 'else' with the for and while loops... A few quick tests basically show that statements in the else structure are executed at the fulfillment of the loop's expression (ie, no break). Example: for i in range(10): print i else: print 'the end!' 0 1 2 3 4 5 6 7 8 9 10 the end!
VIEWS ON THIS POST

85

Posted on:

Monday 5th November 2012
View Replies!