How to use multiple instances of the same COM object at the same time
Dear Usenet readers,
Our company wants to implement about 40 biometric access control devices
which have a proprietary DLL with a COM object in it.
I've done some research about COM objects and how to use them.
Now, I need to connect to every device separately and register for real
time events. So, I need about 40 instances of the COM object
simultaneously connected and registered to catch all events of all devices.
I assumed I needed threading for this, and I have done a simple
implementation.
All I want to ask is: Does anybody see something that I could have done
in a better way? I'm new to COM objects in Python!
The program runs fine, it is very basic and I tested it with 3 devices
connected at the same time. In production this will be 40!
Thanks in advance
Jan
Source code:
# Based on eventappartmentthreading from the win32com demo
import sys, os, time
import win32com.client
import win32api
import win32event
# sys.coinit_flags not set, so pythoncom initializes apartment-threaded.
import pythoncom
from threading import Thread
threadlist = dict() # this stores the device ids
# using the threadid as the key field
class ZkEvents:
def __init__(self):
self.event = win32event.CreateEvent(None, 0, 0, None)
thread = win32api.GetCurrentThreadId()
print "thread %s " % thread
self.dev_id = threadlist[thread]
print "Thread Connected For ID %s " % self.dev_id
def OnFinger(self):
print self.dev_id,
print "OnFinger"
def OnVerify(self, iUserID=pythoncom.Empty):
print self.dev_id,
print "OnVerify: %s" % iUserID
def OnKeyPress(self, iKey=pythoncom.Empty):
print self.dev_id,
print "KeyPress: %s" % iKey
def WaitWhileProcessingMessages(event, timeout = 60):
start = time.clock()
while True:
# Wake 4 times a second - we can't just specify the
# full timeout here, as then it would reset for every
# message we process.
rc = win32event.MsgWaitForMultipleObjects( (event,), 0,
250,
win32event.QS_ALLEVENTS)
if rc == win32event.WAIT_OBJECT_0:
# event signalled - stop now!
return True
if (time.clock() - start) > timeout:
# Timeout expired.
return False
# must be a message.
pythoncom.PumpWaitingMessages()
def TestZkEvents(ip, dev_id):
thread = win32api.GetCurrentThreadId()
print 'TestZkEvents created ZK object on thread %d'%thread
threadlist[thread] = dev_id
pythoncom.CoInitialize()
zk = win32com.client.DispatchWithEvents("zkemkeeper.ZKEM", ZkEvents)
if zk.Connect_Net(ip, 4370):
print "Connect %s OK" % ip
else:
print "Connect %s Failed" % ip
try:
if zk.RegEvent(1, 65535): # 65535 = register for all events
print "RegEvent %s, %s OK" % (ip, dev_id)
else:
print "RegEvent %s, %s Failed" % (ip, dev_id)
except pythoncom.com_error, details:
print "Warning - could not open the test HTML file", details
# Wait for the event to be signaled while pumping messages.
while True:
if not WaitWhileProcessingMessages(zk.event):
print "No Events From %s During Last Minute" % dev_id
zk = None
if __name__=='__main__':
# this should be a for loop with database fields...
t1 = Thread(target=TestZkEvents, args=('192.168.1.211',40))
t1.start()
t2 = Thread(target=TestZkEvents, args=('192.168.1.212',45))
t2.start()
t3 = Thread(target=TestZkEvents, args=('192.168.1.213',49))
t3.start()
--
http://mail.python.org/mailman/listinfo/python-list
reseting an iterator
Wouldn't it be easy for Python to implement generating functions so that the iterators they return are equipped with a __reset__() method? Here is the context of this question. Python documentation defines a "iterator" as an object ITERATOR having methods __next__() and __iter__() such that the call ITERATOR.__iter__() returns the object itself, and once a call ITERATOR. __next__() raises StopIteration every such subsequent call does the same. Python iterators model "generating Turing machines", i.e. deterministic Turing machines which take no input, which have a separation symbol # in the output alphabet; have an one-way-infinite output tape on which the output head prints and moves only to the right; The machine may have a halting state; a word is said to be "generated by M" if it appears on the output tape delimited by separation symbols # (independently of whether M halts or computes infinitely). Generating Turing machines provide a characterization of recursively enumerable languages: a language is generated by a generating Turing machine iff it is accepted by a Turing machine. Turing machines can take as input and run other Turing Machines -- similarly Python functions can take other functions (including iterators) as parameters and call them. HOWEVER, this symmetry breaks down: a Turing machine which takes a generating Turing machine M as input can run M for a number of steps and then RESET M and run it again, while iterators as currently defined in Python do not have a reset method. (I realize that instead of reseting an old iterator, one can make a new iterator but it is not as elegant.) (Contrary to Python's philosophy that there should be one-- and preferably only one --obvious way to do it) there are several ways to define iterators: -- http://mail.python.org/mailman/listinfo/python-list
Re: reseting an iterator
On May 20, 2:35 pm, Jan wrote: OOPS, I have pressed some keys and the message went out before It was finished. Here is the last fragment: So, one can define iterators by defining a class whose objects have methods __iter__ and __next__ -- with this approach it is easy to add some __reset__ method. But the easiest way to define iterators is by constructing a generating function (with yield expressions); this function returns iterators, although without __reset__. Another way to define an iterator is to define callable and using iter(CALLABLE, SENTINEL) -- the resulting iterator will not have __reset__. I do not know how Python is implemented but I believe that in the last two cases, Python could produce improved iterators with __reset__ at almost no additional cost. Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: reseting an iterator
On May 20, 2:48 pm, Jan wrote: Iterators can also be produced by iter(ITERABLE) which could mnufacture them with a __reset__. Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: reseting an iterator
On May 22, 9:46 am, "J. Cliff Dyer" wrote: > You don't need a reset method. There is no hard and fast rule that > __iter__ must return the object itself. It just needs to return an > iterator. I disagree. If ITRATOR is a true iterator, ITRATOR.__iter__() must return ITERATOR. If ITERABLE is an iterable (but not necessarily an iterator) ITRABLE.__iter__() must return an iterator. > For example: > > >>> l = [1,2,3] > >>> l.__iter__() > > >>> l is l.__iter__() > > False [1,2,3] is an iterable but not an iterator, so this False result is expected. Compare this with the following. >>> ii = iter([1,2,3]) # ii is an iterator. >>> next(ii) 1 >>> jj = ii.__iter__() # call __iter__ method on an iterator >>> ii is jj True >>> next(jj) 2 > Just create a class with an __iter__ method that returns a reset > iterator object. > > class X(object): > def __init__(self, max=3): > self.counter = 0 > self.max = max > def __iter__(self): > return self > def next(self): > if self.counter < self.max: > self.counter += 1 > return self.counter > else: > raise StopIteration > > class Y(object): > def __iter__(self): > return X() > > In this setup, X has the problem you are trying to avoid, but Y behaves > as a resettable iterable. > y = Y() This does not work. With this, y is not an interator, and not even an iterable. > for c in y: This produces an error because by definition of for-loops it is executed the same way as: temp_iterator = iter(y) # temp_iterator is y while True: try: print(next(temp_iterator)) # temp_iterator does not support __next__() except StopIteration: break Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Game Development?
On 07.06.2013 18:53, [email protected] wrote: I was planning on making a small 2D game in Python. Are there any libraries for this? I know of: • Pygame - As far as I know it's dead and has been for almost a year • PyOgre - Linux and Windows only(I do have those, but I want multi-platform) • Cocos2D - Won't install and cant find any support • PyCap - Can't find any documentation • Panda3D - Dead since 2011 + overkill for what I need • PyOpenGL - Overkill Any help on what to do with this would be appreciated. I am making games mainly in Lua but I'd like to make one in Python for fun. I also understand that Python isn't exactly the *BEST* choice programming a game, but I have heard it is possible. Tell me if it's true. Thanks! Hi, I only have looked closer in pygame. But before asking for an general overview of possible gaming libraries, I would start to answer the question of what kind of game you want to make and what features do you really need. For some space game for example it is most unlikely that you will face the requirement of having a bleeding edge physics engine. Especially if you make use of 2d objects versus 3d models of any type. I guess you can expand the latter to any extend here. Also it is a common thing I might guess bravely, that the basics of game programming are done similar in all game engines. - Setting up a game loop - Calculation present and future ob objects - Handling user input by using events - Redraw the screen And this is in pygame quite simply, but I also had trouble finding the right entrance to it, as you have to read a bit up on how components fit together in that library. An example basic setup looks like (with classing), I remove my code and limited it to basic event/input handling and also the drawing of a screen object in which you can add images and stuff. Sorry for the formatting, I copied from idle and formatted in my email client. # class gameApp: def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode( (640, 480), DOUBLEBUF|SRCALPHA ) self.run() def run(self): while not self.close_app: self.clock.tick(60) for event in pygame.event.get(): #print event if event.type == KEYUP: # Press tab for player info if event.key == 9: pass # Do something in tab key elif event.type == MOUSEBUTTONDOWN: if event.button == 1: pass # Left click, mouse button is pressend elif event.type == MOUSEMOTION: mx = event.rel[0] my = event.rel[1] continue elif event.type == QUIT: self.close_app = True self.screen.fill( (0,0,0) ) # Self interaction is a screen drawing object self.screen.blit(self.interactions, (0,0), special_flags=BLEND_RGBA_ADD) pygame.display.flip() pygame.quit() if __name__ == '__main__': import pygame from pygame.locals import * gameApp() #-------- Regards Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On 13.06.2013 20:00, Νικόλαος Κούρας wrote: if '-' not in name + month + year: cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) ) elif '-' not in name + year: cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, year) ) elif '-' not in month + year: cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) ) elif '-' not in year: cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year ) This finally worked! I spared myself to read the whole thread cause its super long and I find it admirable that some people took time to troubleshoot the issue and (even) added optimizations of what can be done differently/better.. even so it seems there was only a wrong char used in the ifs?.. And as a short note - you should add code which handles the worst-case scenario (everthing fails, nothing valid, avoid into code which might require variables/data which is not present and so forth..) But generally speaking: As a best practice in any language not just Python. If you have the option to print out evaluations and values, use it! As rule of thumb for debugging code: 1. Print out what values you get in (from user, in(to) a function) 2a. Test statements and logic either by setting a print (in your case inside each if) with something like "if1", "if2", ... "else fired" or what you prefer OR do a direct comparison if the evaluation statements are not super long (someone mentioned that..) 2b. In case of longer statements/calculations, break them into chunks, simplify the problem to smaller ones and try to verify the results as possible (being "far apart" and "getting closer" after each time is already a good hint in calculations..) 3. If you catch data from a database and you see now results -> print out if your search/query even can return anything at all or if your query itself has a flaw or similar. Optional but also useful: 4. On the end of a function, print if the output of the function is as expected This small technique costs minimal time, but brings a brilliant ability: 1. Understand the code flow 2. Understand mistakes 3. Save yourself a big time by searching targeted for code parts which are executed.. ..and ignore not directly connected code - for example when looking at other peoples code without documentation, comments or introduction. This can spare loads of headaches. And all this can be done in a couple of minutes.. Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On 26.06.2013 16:28, William Ray Wing wrote: On Jun 26, 2013, at 7:49 AM, Fábio Santos mailto:[email protected]>> wrote: On 26 Jun 2013 11:45, mailto:[email protected]>> wrote: > > On Tuesday, June 25, 2013 9:30:54 PM UTC+5:30, Ian wrote: > > In my experience the sorts of people who preach "one exit point" are > > also all about defining preconditions and postconditions and proving > > that the postconditions follow from the preconditions. I think that > > the two are linked, because the "one exit point" rule makes those > > sorts of proofs simpler. > > Ah! utopia! > > For every one who knows about pre/post/invariant conditions, there are 10 who follow goto-statement-is-harmful like a religious edict. > > > > I just checked and MISRA-C 2012 now allows gotos in specific, limited circumstances. I think it was the MISRA-C 1998 standard that caused all this trouble. So if MISRA now allows goto, why not Python :) > What is the matter? Just use the goto module... Wondered when that would be mentioned. Personally, I've never found that much use for GoTo, but as old timers know, that same module adds the Come_From entry point, which is priceless. ;-) Bill Actually, jumping to any place a program (I know it from QBasic :) ) is some kind of voodoo. At first it seems that any function calling itself or calling another function from another function solves the "goto" puzzle - called OO programming, objects in space and inheritance? But at 2nd glimpse, jumping in any place of code (function) or routine, at a given place precisely - and to avoid any checks and unrelated code which might occur on a regular function call and without the need to provide additional arguments - that's kinda cool (if variables are in scope by the target statements :) ) That's somehow how I remember it. But I guess if everything should run as in a factory, one entrance, one component, one result and independently from each other (isolated) and on many cores and such, a goto without argument passing or state variables might just end up in a big mess. What do you think? -- http://mail.python.org/mailman/listinfo/python-list
Basic question about speed/coding style/memory
Hello Pythonlist, I have one very basic question about speed,memory friendly coding, and coding style of the following easy "if"-statement in Python 2.7, but Im sure its also the same in Python 3.x Block #-- if statemente_true: doSomething() else: doSomethingElseInstead() #-- versus this block: #-- if statement_true: doSomething() return doSomethingElseInstead() #-- I understand the first pattern that I tell the interpreter to do: Check if the conditional is true, run "doSomething()" else go inside the else block and "doSomethingElseInstead()". while the 2nd does only checks: doSomething() if statement_true, if not, just go directly to "doSomethingElseInstead() Now, very briefly, what is the better way to proceed in terms of execution speed, readability, coding style? Letting out the fact that, in order to prevent "doSomethingElseInstead"-Block to execute, a return has to provided. Thank you for reading and hope someone brings light into that. Your fellow python programmer Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question about speed/coding style/memory
On 21.07.2012 11:02, Andrew Berg wrote: On 7/21/2012 2:33 AM, Jan Riechers wrote: Block ... versus this block: ... Now, very briefly, what is the better way to proceed in terms of execution speed, readability, coding style? Using if/else is the most readable in the general sense. Using return (or break or continue as applicable) in this manner would indicate (at least to me) that it's an exceptional or otherwise special case and that the function can't do what it's supposed to. In that case, I would try to catch an exception rather than use if/else whenever possible. I highly doubt there is a significant performance difference between them. Hello Andrew, Your answer is right, in other circumstances I also would stick to try/except, break-statements in loops and so forth. But the question was a bit more elementary. Cause, as I understand the interpreter chooses either the "else" (1st block) or just proceeds with following code outside the if. So if there is some overhead in some fashion in case we don't offer the else, assuming the interpreter has to exit the evaluation of the "if"-statement clause and return to a "normal parsing code"-state outside the if statement itself. I hope this explanation makes more sense in what I want to ask ;) Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question about speed/coding style/memory
On 21.07.2012 12:06, Steven D'Aprano wrote:
But in general, you're worrying too much about trivia. One way or the
other, any speed difference will be trivial. Write whatever style reads
and writes most naturally, and only worry about what's faster where it
actually counts.
Notice that I try to make each function do the same amount of work, so
that we're seeing only the difference between "else" vs "no else".
Now let's test the speed difference with Python 2.7. Because this is
timing small code snippets, we should use the timeit module to time the
code:
from timeit import Timer
setup = "from __main__ import with_else, without_else"
t1 = Timer("for i in (0, 1): result = with_else(i)", setup)
t2 = Timer("for i in (0, 1): result = without_else(i)", setup)
Each snippet calls the function twice, once to take the if branch, then
to take the else branch.
Now we time how long it takes to run each code snippet 100 times. We
do that six times each, and print the best (lowest) speed:
py> min(t1.repeat(repeat=6))
0.9761919975280762
py> min(t2.repeat(repeat=6))
0.9494419097900391
So there is approximately 0.03 second difference per TWO MILLION
if...else blocks, or about 15 nanoseconds each. This is highly unlikely
to be the bottleneck in your code. Assuming the difference is real, and
not just measurement error, the difference is insignificant.
So, don't worry about which is faster. Write whichever is more natural,
easier to read and write.
Hello Steven,
very nice example and thank you very much for also for the Timeit test!
Actually it confirms my assumption in some way:
[SNIP myself]
So if there is some overhead in some fashion in case we don't offer the
else, assuming the interpreter has to exit the evaluation of the
"if"-statement clause and return to a "normal parsing code"-state
outside the if statement itself.
[SNAP]
Without having looked at Andrew's bytecode excecution hint, using the
dis module, to see how the interpreter handles the task on lower level.
But fare enough for me :)
But I agree, the return in my example is misleading and it would be
illegal outside of a function call. I just added it to make clear that
the fellow code below the return should not be executed in comparison to
the 2nd example.
Thank you very much
Jan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Converting a list of strings into a list of integers?
On 22.07.2012 18:39, Alister wrote: On Sun, 22 Jul 2012 10:29:44 -0500, Tony the Tiger wrote: I came up with the following: # options.modus_list contains, e.g., "[2,3,4]" # (a string from the command line) # MODUS_LIST contains, e.g., [2,4,8,16] # (i.e., a list of integers) if options.modus_list: intTmp = [] modTmp = options.modus_list[1:-1] for itm in modTmp: intTmp.append(int(itm)) MODUS_LIST = intTmp TIA /Grrr looks like a classic list comprehension to me and can be achieved in a single line MODUS_LIST=[int(x) for x in options.modus_list] Hi, I am not sure why everyone is using the for-iterator option over a "map", but I would do it like that: MODUS_LIST= map(int, options.modus_list) "map" works on a list and does commandX (here "int" conversion, use "str" for string.. et cetera) on sequenceY, returning a sequence. More in the help file. And if I'm not completely mistaken, it's also the quicker way to do performance wise. But I can't completely recall the exact reason. Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a list of strings into a list of integers?
On 22.07.2012 20:03, David Robinow wrote: On Sun, Jul 22, 2012 at 12:20 PM, Jan Riechers wrote: On 22.07.2012 18:39, Alister wrote: looks like a classic list comprehension to me and can be achieved in a single line MODUS_LIST=[int(x) for x in options.modus_list] Hi, I am not sure why everyone is using the for-iterator option over a "map", but I would do it like that: MODUS_LIST= map(int, options.modus_list) "map" works on a list and does commandX (here "int" conversion, use "str" for string.. et cetera) on sequenceY, returning a sequence. More in the help file. And if I'm not completely mistaken, it's also the quicker way to do performance wise. But I can't completely recall the exact reason. Because if you don't have a functional background 'map' is unfamiliar. Although I've been aware of it for years I still can't remember if it's map(int, list) or map(list,int) and although with a small effort I could force it into my brain, I know that many of the people reading my code are as ignorant as I am. The list comprehension seems clearer to me. Hello, no offense by that, I just was wondering why everyone uses the list comprehension instead the built-in map in this case - I'm still using Python 2.7.3 so perhaps things might have changed a little. :) So far Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a list of strings into a list of integers?
On 22.07.2012 20:01, Steven D'Aprano wrote: [SNIP] map is faster than an ordinary for-loop if the function you are applying is a builtin like int, str, etc. But if you have to write your own pure- Python function, the overhead of calling a function negates the advantage of map, which is no faster than a for-loop. For example: results = map(int, sequence) # calls builtin `int` hoists the call to int into the fast C layer, instead of the slow Python layer, and should be faster than results = [] for x in sequence: results.append(int(x)) which runs at the speed of Python. But: results = map(lambda x: x+1, sequence) # calls pure Python function if no faster than a for-loop: results = [] for x in sequence: results.append(x+1) Note: this has*nothing* to do with the use of lambda. Writing the "+1" function above using def instead of lambda would give the same results. [SNAP] Hi Steven, besides that I testdrive Pypy (and still am impressed, other topic) - your answer was what I was picking for ;) Especially this part of you: > map is faster than an ordinary for-loop if the function you are applying > is a builtin like int, str, etc. [underlaying c-layer] But if you have to write your own pure- > Python function, the overhead of calling a function negates the advantage > of map [...] I did not know that the speed gain is up foremost present when using built-ins, but that's for sure something to keep in mind when writing code. Thanks for your explanation, clarifies a lot! Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: the meaning of rユ.......ï¾
On 23.07.2012 16:55, Henrik Faber wrote: On 23.07.2012 15:52, Henrik Faber wrote: but I would hate for Python to include them into identifiers. Then again, I'm pretty sure this is not planned anytime soon. Dear Lord. Python 3.2 (r32:88445, Dec 8 2011, 15:26:58) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. fööbär = 3 fööbär 3 I didn't know this. How awful. Regards, Johannes I can't understand at all why this (even as German) is supported. Programs and developments, and in particular Python, should not only be accessible but also understandable by everyone - meaning that I don't exclude folks by starting to write my code in Esperanto letters. Otherwise the next thing one might working on is a script normalizer which Engli-fies foreign variable names... similar to Py2to3. Outside for display usage it has a right place to make usage of Unicode, like for French with all the accents Danish, Swedish and other languages, but some "old"-standards should stay in place, meaning to use English, so it stays accessible and understandable. Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: New image and color management library for Python 2+3
On 14.08.2012 21:22, Christian Heimes wrote: Hello fellow Pythonistas, Performance === smc.freeimage with libjpeg-turbo read JPEGs about three to six times faster than PIL and writes JPEGs more than five times faster. [] Python 2.7.3 read / write cycles: 300 test image: 1210x1778 24bpp JPEG (pon.jpg) platform: Ubuntu 12.04 X86_64 hardware: Intel Xeon hexacore [email protected] with 24 GB RAM smc.freeimage, FreeImage 3.15.3 standard - read JPEG 12.857 sec - read JPEG 6.629 sec (resaved) - write JPEG 21.817 sec smc.freeimage, FreeImage 3.15.3 with jpeg turbo - read JPEG 9.297 sec - read JPEG 3.909 sec (resaved) - write JPEG 5.857 sec - read LZW TIFF 17.947 sec - read biton G4 TIFF 2.068 sec - resize 3.850 sec (box) - resize 5.022 sec (bilinear) - resize 7.942 sec (bspline) - resize 7.222 sec (bicubic) - resize 7.941 sec (catmull rom spline) - resize 10.232 sec (lanczos3) - tiff numpy.asarray() with bytescale() 0.006 sec - tiff load + numpy.asarray() with bytescale() 18.043 sec PIL 1.1.7 - read JPEG 30.389 sec - read JPEG 23.118 sec (resaved) - write JPEG 34.405 sec - read LZW TIFF 21.596 sec - read biton G4 TIFF: decoder group4 not available - resize 0.032 sec (nearest) - resize 1.074 sec (bilinear) - resize 2.924 sec (bicubic) - resize 8.056 sec (antialias) - tiff scipy fromimage() with bytescale() 1.165 sec - tiff scipy imread() with bytescale() 22.939 sec Christian Hello Christian, I'm sorry for getting out of your initial question/request, but did you try out ImageMagick before making use of FreeImage - do you even perhaps can deliver a comparison between your project and ImageMagick (if regular Python is used)? I ask cause: Im in the process of creating a web-app which also requires image processing and just switching from PIL (because it is unfortunately not that quick as it should be) to ImageMagick and the speeds are much better compared to it, but I didn't take measurements of that. Can you perhaps test your solution with ImageMagick (as it is used widely) it would be interesting so. :) But no offence by that and respect for you work so! Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: New image and color management library for Python 2+3
On 20.08.2012 20:34, Christian Heimes wrote: > Am 19.08.2012 19:35, schrieb Jan Riechers: > > Hello Jan, > > we decided against ImageMagick and pgmagick for several reasons. For one > we were already using FreeImage in other projects (Delphi projects and > through ctypes binding with FreeImagePy). > [SNIP] > > The Python bindings for ImageMagick weren't that good and today they are > still buggy. For example I'm not able to set the resize filter to a high > quality setting like Catmull-Rom-Spline with the most recent version of > pgmagick. filterType() doesn't do anything. The output image still has > the same MD5 hash. > > ImageMagick and PIL were missing important features, too. For example > both libraries don't support color management with lcms2 nor cached > color transformations nor introspection of ICC profiles. They use lcms1. > The color profiles explains - perhaps it would be interesting still to test out your library with regular images (without color profiles) against ImageMagick, just to compare the raw speed of both solutions. In my case I really would love to see if there is a even higher performance solution available as I plan to serve a lot of users a time and especially keeping the Input/Output during file writing low would be very helpful. > >> Can you perhaps test your solution with ImageMagick (as it is used >> widely) it would be interesting so. > > I've added some more benchmark results to the README.txt (PIL with > non-standard libjpeg-turbo and pgmagick). The results are available at > https://bitbucket.org/tiran/smc.freeimage > > Spoiler: pgmagick isn't faster and its resize filter settings don't work. > Thank you for the additional benchmarks, nice to read! I will try your library out to see how it compares to old-pendant ImageMagick with Pypy 1.9 | Wand / Pillow (Pil fork for pypy) and Python 2.7.3 PIL / ImageMagick - perhaps I can deliver you those numbers too - for those folks not completely in need of a color profile aware version but to compare raw numbers Perhaps it would also be nice to see if and how it works with Pypy too Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Objects in Python
On 8/23/12 06:11 , Steven D'Aprano wrote:
2) Related to the above, you can infinitely nest scopes. There's nothing
wrong with having six variables called 'q'; you always use the innermost
one. Yes, this can hurt readability
Well, there you go. There *is* something wrong with having six variables
called 'q'.
Sometimes you don't want only six variables called 'q' but a hundred
of them :-)
def fac(q):
if q < 1 :
return 1
else:
return q * fac(q-1)
print(fac(100))
Jan Kuiken
--
http://mail.python.org/mailman/listinfo/python-list
Re: Objects in Python
On 8/23/12 20:17 , Ian Kelly wrote: ... Well, there you go. There *is* something wrong with having six variables called 'q'. Sometimes you don't want only six variables called 'q' but a hundred of them :-) def fac(q): if q < 1 : return 1 else: return q * fac(q-1) print(fac(100)) That's only one variable called 'q', instantiated 100 times simultaneously. Bare with me, i come from a C world, and think of each variable, whatever its name or scope, as a piece of memory and therefore different. btw. I like the idea of simultaneously instantiation :-) Jan Kuiken -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes - python2.7.3 vs python3.2.3
On 8/28/12 23:51 , John Gordon wrote: In <[email protected]> Rolf writes: uint32_t myfunction (char ** _mydata) { char mydata[16]; strcpy(mydata, "Hello Dude!"); *_mydata = mydata; return 0; } mydata is an auto variable, which goes out of scope when myfunction() exits. *_mydata ends up pointing to garbage. I'm not completely sure, but i think this can be solved by using: static char mydata[16]; (Btw.: I don't know why you use char ** _mydata, i would use char * _mydata, but then again, i'm not very familiar with ctypes) Jan Kuiken -- http://mail.python.org/mailman/listinfo/python-list
z-buffer mlab
Hi Guys! I am plotting an object in mlab (isoSurface) and then I am adding 2 image_plane_widgets. Till now everything is ok but when I am changing the opacity of the object to lower than 1 it is suddenly appearing behind the planes? Why so? Is it dependant on the order of adding objects? But i cant add image_plane without having a surface I would be very gratefull for help. -- http://mail.python.org/mailman/listinfo/python-list
Re: pylint, was Re: pygame - importing GL - very bad...
On 05.01.2013 03:11, someone wrote:
On 01/03/2013 12:27 PM, Chris Angelico wrote:
On Thu, Jan 3, 2013 at 10:19 PM, someone wrote:
Doesn't this "[ ... ]" mean something optional?
What does {2,30}$ mean?
I think $ means that the {2,30} is something in the end of the
sentence...
You can find regular expression primers all over the internet, but to
answer these specific questions: [...] means any of the characters in
the range; the $ means "end of string"; and {2,30} means at least two,
and at most thirty, of the preceding character. So you have to have
one from the first group, then 2-30 from the second, for a total of
3-31 characters in your names.
Got it, thanks!
Just following the discussion which is very interesting, even so when
not working with OpenGL (which looks like a nightmare with that naming
space) :)
But about the regular expressions (a bit deeper look into that):
Like said of Chris:
[a-z]
defines a "catching group", in this case all ascii lowercase letters
ranging from "a" to "z". If noting else is provided, the rule matches
one letter if there is no range defined by something like:
{} -> Target a range of a match/hit
There are also a
? -> Lazy match
* -> Gready match
[A-Z][0-9]{1,3} means translated:
Look for any uppercase letter in ascii(!) (not "öäü" or similiar)
ranging from "A" to "Z".
Now look for any digit (2nd catching group) with the addition to satisfy
the rule ONLY if there are at least 1 to 3 digits found.
Note: If there are 4 or more digits - the catching rule is still
satisfied and will provide a match/hit.
If there is a follow up group, the next evaluation is gone through if
present and so forth. If the expression is satisfied, the match is returned.
The lazy "?" and greedy "*" matches try to satisfy, as the naming
implies, to match as less or as much of what you have asked for.
For example the regular expression is valid:
0* -> Look for a zero, and be greedy as of how many zeros you want match
which might follow.
Regular expressions don't have to include catching groups in order to work.
But when you use them yourself somehow, its quite simple I think.
I guess you are anyhow busy mangling with pyLint, PEP-Standards and
pyOpenGL - so good luck with that :)
Jan Riechers
--
http://mail.python.org/mailman/listinfo/python-list
Re: Need Pattern For Logging Into A Website
On Friday, January 25, 2013 2:29:51 AM UTC+1, Tim Daneliuk wrote: > I need to write a Python script to do the following: > > > >- Connect to a URL and accept any certificate - self-signed or > authoritative > >- Provide login name/password credentials > >- Fill in some presented fields > >- Hit a "Submit" button > > > > Why? Because I don't want to have to start a browser and do this > > interactively every time I authenticate with a particular server. > > I want to do this at the command line with no interactive intervention. > > > > I know Python pretty well. I don't quite know how to do this and > > was hoping someone had a simple pattern they could share for > > doing this. > > > > TIA, > Hello Tim, I think you may also want to take a look at python requests. http://docs.python-requests.org/en/latest/user/advanced/ >From my experience they do a much nicer job than urllib and anything I've >tried. You will probably get what you want out of them easily and in no time. -- cheers, john -- http://mail.python.org/mailman/listinfo/python-list
[RFC] PEP 3143: supplementary group list concerns
Hello, in the light of a recent spot in Python Paste [1], I've come across the python-daemon [2] implementation and found it also lacks support for supplementary groups. First, I just wanted to post a patch to the author, but realized the broader context of PEP 3143 that would probably deserve revisiting at the first place. As the target Python version seems not to be decided yet, I see a space for it. If the spirit of solution [2] was to be followed (i.e., initialize this list with all groups of which user derived from `uid` is a member + group derived from `gid` (regardless if `uid`/`gid` is explicit), no change of the PEP would be necessary. This fact of intented handling of supplementary groups under the hood still could be mentioned so the users and authors of compatible interfaces are aware of this "detail". Another way (in the spirit of systemd [3]) is to extend the interface with an option (named, e.g., supplementary_groups) for optional specification of supplemental groups. The default would be something as in the previous paragraph. To be honest, I am not sure how consistently is the concept of supplementary groups used across various *nixes. POSIX seems to admit variances, e.g. (via [4]): v The System Interfaces volume of IEEE Std 1003.1-2001 does not specify whether the effective group ID of a process is included in its supplementary group list. ^ But I believe this should be addressed before the PEP in question is brought into effect. [2] http://groups.google.com/group/paste-users/browse_thread/thread/2aa651ba331c2471 [3] http://0pointer.de/public/systemd-man/systemd.exec.html [4] http://pubs.opengroup.org/onlinepubs/95399/utilities/newgrp.html Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: [RFC] PEP 3143: supplementary group list concerns
On 12/03/12 09:27 +1100, Ben Finney wrote: Jan Pokorný writes: in the light of a recent spot in Python Paste [1], I've come across the python-daemon [2] implementation and found it also lacks support for supplementary groups. Thank you for your interest in ‘python-daemon’. To know specifically what you're referring to in most of this message, I think your reference ‘[1]’ is necessary; but you didn't provide it. My bad, I've sent it with unfinished renumbering. Please swap [1]+[2] in the quoted part and the missing reference is http://pypi.python.org/pypi/python-daemon/ (for some reason, this points to 1.5.5, even though 1.6 is also there: http://pypi.python.org/pypi/python-daemon/1.6 ). -- http://mail.python.org/mailman/listinfo/python-list
Re: functions which take functions
On 4/9/12 20:57 , Kiuhnm wrote: Do you have some real or realistic (but easy and self-contained) examples when you had to define a (multi-statement) function and pass it to another function? I don't use it daily but the first argument of list.sort, i.e. the compare function springs to mind. Jan Kuiken -- http://mail.python.org/mailman/listinfo/python-list
Appending to []
Can you explain why there is a difference between the following two statements? >>> a = [] >>> a.append(1) >>> print a [1] >>> print [].append(1) None Best regards, Jan Sipke -- http://mail.python.org/mailman/listinfo/python-list
Re: Help doing it the "python way"
On 5/24/12 22:22 , Scott Siegler wrote: I am an experienced programmer but a beginner to python. As such, I can figure out a way to code most algorithms using more "C" style syntax. I am doing something now that I am sure is a more python way but i can't quite get it right. I was hoping someone might help. So I have a list of grid coordinates (x, y). From that list, I want to create a new list that for each coordinate, I add the coordinate just above and just below (x,y+1) and (x,y-1) right now I am using a for loop to go through all the coordinates and then separate append statements to add the top and bottom. is there a way to do something like: [(x,y-1), (x,y+1) for zzz in coord_list] or something along those lines? If you have lot's of numerical data you can use the NumPy module (http://numpy.scipy.org/), your problem would reduce to something like this (copied from an IPython shell, could be shorter) Regards, Jan Kuiken In [1]: first_list = np.arange(0, 10).reshape((5,2)) In [2]: above = np.array([0,-1]) In [3]: below = np.array([0,+1]) In [4]: N,d = first_list.shape In [5]: second_list = np.empty((N*2,d)) In [6]: second_list[0::2] = first_list + above In [7]: second_list[1::2] = first_list + below In [8]: second_list Out[8]: array([[ 0., 0.], [ 0., 2.], [ 2., 2.], [ 2., 4.], [ 4., 4.], [ 4., 6.], [ 6., 6.], [ 6., 8.], [ 8., 8.], [ 8., 10.]]) In [9]: first_list Out[9]: array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Generator Frustration
On 06/04/2011 08:27 PM, TommyVee wrote: I'm using the SimPy package to run simulations. Anyone who's used this package knows that the way it simulates process concurrency is through the clever use of yield statements. Some of the code in my programs is very complex and contains several repeating sequences of yield statements. I want to combine these sequences into common functions. The problem of course, is that once a yield gets put into a function, the function is now a generator and its behavior changes. Is there any elegant way to do this? I suppose I can do things like ping-pong yield statements, but that solutions seems even uglier than having a very flat, single main routine with repeating sequences. In MyHDL, this is supported by the possibility to yield generators, which are then handled by the simulation engine. Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Python as a HDL: http://www.myhdl.org VHDL development, the modern way: http://www.sigasi.com Analog design automation: http://www.mephisto-da.com World-class digital design: http://www.easics.com -- http://mail.python.org/mailman/listinfo/python-list
Fwd:
error by starting up windows 10 i get this message -- Forwarded message - Van: Jan Poort Date: do 8 sep. 2022 om 15:49 Subject: To: -- *Jan Poort* -- https://mail.python.org/mailman/listinfo/python-list
RE: Python installation not full and python not working 3.11.0
Hello all, I would like to ask you for help. I have been using Python 3.8 for almost 2 years and I decided to update to 3.11. Initially everything was correct. But at some point Windows shows me that Python is being reinstalled (I don't have a message print screen ..), but from that time I cannot run Python at all on my PC. So I tried to reinstall it several times with no success. All the time I receive this "The system cannot find the file C:\Users...\AppData\Local\Programs\Python\Python311\python.exe." But files are there: [cid:[email protected]] Even when I try to run "python.exe" directly I receive this error: [cid:[email protected]] System Variables are right (added it to both PATH): 1) User Variables: [cid:[email protected]] 2) System Variables [cid:[email protected]] Strange thing is that after RE-Installing Python the "pip.exe" is missing in subfolder "Python/Scripts/" (it is simply empty - not installed but I mark pip to be installed): [cid:[email protected]] I tried also Repair - no success. Details: System: Windows 10 (21H2) Python: 3.11.0 (full 64bit installer from python.org) * Downloaded from: Python Release Python 3.11.0 | Python.org<https://www.python.org/downloads/release/python-3110/> cmd: [cid:[email protected]] This is resulting that I cannot use interpreter in VS Code and continue development. Any one Any Idea? Thank you S pozdravem Jan Vaško -- https://mail.python.org/mailman/listinfo/python-list
Re: Non-GUI, single processort inter process massaging - how?
On Sat, 2018-07-21 at 11:50 -0400, Dennis Lee Bieber wrote: > Each client would use the urllib (various names between v2 > and v3) to submit requests to the server, and process the returned > "page". Or the client could even be a bash script using curl, or any other HTTP client... -- Jan Claeys -- https://mail.python.org/mailman/listinfo/python-list
Re: Using Python on a fork-less POSIX-like OS
On Fri, 2018-07-27 at 19:13 +0200, Barath Aron wrote: > I intend to cross-compile Python v3.6.6 to Threos ( https://threos.io > ) operating system. Threos is supports a quite large set from > POSIX and C89/C99. Unfortunately, Threos lacks fork(2), but > provides posix_spawn(3) instead. I already made some local changes > in posixmodule.c to compile due to some features are detected > as present but actually not supported, like HAVE_FORK -- I blame > autotools for this :-). I don't know, however, whether the Python > shall cross-compile without issues. > > My question is that the _posixsubprocess.c can be prepared to > use posix_spawn(3) instead of fork(2)? Maybe the UNIX/Linux version > can also benefit from it, see: https://salsa.debian.org/ruby- > team/ruby-posix-spawn You might want to ask this on the python-dev mailing list. -- Jan Claeys -- https://mail.python.org/mailman/listinfo/python-list
Re: What is precision of a number representation? (was: Curious Omission In New-Style Formats)
On Tue, 12 Jul 2016 07:51:23 +1000 Chris Angelico wrote: [snip] > > Yep. Precision is also a property of a measurement, the same > way that a unit is. If I pace out the length of the main > corridor in my house, I might come up with a result of thirty > meters. The number is "30"; the unit is "meters", the > precision is two significant digits, and the accuracy depends > on how good I am at pacing distance. > > This is why it's important to be able to record precisions of > arbitrary numbers. If I then measure the width of this > corridor with a laser, I could get an extremely precise answer > - say, 2,147 millimeters, with a precision of four significant > digits, and excellent accuracy. But if I multiply those > numbers together to establish the floor area of the corridor, > the result does NOT have four significant figures. It would be > 64 square meters (not 64.41), and the accuracy would be pretty > low (effectively, the *in*accuracies of both measurements get > combined). But on the other hand, if you want to know whether > your new fridge will fit, you could measure it with the same > laser and come up with a figure of 1,973 mm (four sig fig), > which would mean your clearance is 174mm (four sig fig). How > do you record this? Is it 174.0? 0174? "174 with four > significant figures"? Thees all look good, but you may get into trouble if you trust a PC with them! If the language/PC uses floating point representation then it will assign a fixed number of bits for the fractional part, and this will be left aligned in all/most hardware. This fraction might be 52 bits long. Your example number has about 11 bits of precision. The floating point representation will then have ~40 bits appended which imply a precision which does not exist. Your program may still know that only 11 bits are significant, but the representation implies that 52 bits are significant, and provides no indication otherwise. Good news!: Unum is an alternate numeric representation that does indicate the precision of a number [1]. It also resolves other problems of current float representation. Bad news?:In doing so unums becomes incompatible with current hardware floating point engines. Jan Coombs -- [1] slides: http://sites.ieee.org/scv-cs/files/2013/03/Right-SizingPrecision1.pdf RichReport 54 minute interview: https://youtu.be/jN9L7TpMxeA -- https://mail.python.org/mailman/listinfo/python-list
Re: cell and row
Because you're inserting items into your existing list instead of a new list. What you probably mean is: b = [] for x in a: b.append(x) which creates a new list b that contains all elements whose length is greater than four. A better way to write this would be: b = [x for x in a if len(x) > 4] -- http://mail.python.org/mailman/listinfo/python-list
Re: cell and row
Doh, the first example should of cours be: b = [] for x in a: if len(x) > 4: b.append(x) -- http://mail.python.org/mailman/listinfo/python-list
modifying source at runtime - jython case
Hello folks I want to apply changes in my source code without stopping jython and JVM. Preferable are modifications directly to instances of classes. My application is a desktop app using swing library. Python solutions also interest me. Solution similiar to "lisp way" is ideal. Thanks for response, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying source at runtime - jython case
In article <[EMAIL PROTECTED]>, Alan Kennedy wrote:
> [Jan Gregor]
>> I want to apply changes in my source code without stopping jython
>> and JVM. Preferable are modifications directly to instances of
>> classes. My application is a desktop app using swing library.
>>
>> Python solutions also interest me.
>>
>> Solution similiar to "lisp way" is ideal.
>
> OK, I'll play 20 questions with you.
>
> How close is the following to what you're thinking?
I see.
Following try showed me that instances aren't affected by
modification in class definition.
but this helped
x.test = a().test OR x.test = y.test
The only thing left is how to initiate modification, it's a
swing application and i think interp.exec don't stop until
it's done. Maybe somehow call it from jython itself - but need
to pass PythonInterpreter instance.
Thanks.
class a:
def test(self):
print 'first'
x= a()
class a:
def test(self):
print 'second'
y= a()
x.test()
y.test()
>
> begin SelfMod.java ---
> //
> import org.python.util.PythonInterpreter;
> import org.python.core.*;
>
> class SelfMod
>{
>
>static String my_class_source =
> "class MyJyClass:\n" +
> " def hello(self):\n" +
> "print 'Hello World!'\n";
>
>static String create_instance = "my_instance = MyJyClass()\n";
>
>static String invoke_hello = "my_instance.hello()";
>
>static String overwrite_meth =
> "def goodbye():\n"+
> " print 'Goodbye world!'\n" +
> "\n" +
> "my_instance.hello = goodbye\n";
>
>public static void main ( String args[] )
> {
> PythonInterpreter interp = new PythonInterpreter();
> interp.exec(my_class_source);
> interp.exec(create_instance);
> interp.exec(invoke_hello);
> interp.exec(overwrite_meth);
> interp.exec(invoke_hello);
> }
>
>}
> //
> end SelfMod.java -
>
> need-to-complete-my-coursework-for-telepathy-101-ly y'rs
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: modifying source at runtime - jython case
In article <[EMAIL PROTECTED]>, Kent Johnson wrote: > Jan Gregor wrote: >> Hello folks >> >> I want to apply changes in my source code without stopping jython >> and JVM. Preferable are modifications directly to instances of >> classes. My application is a desktop app using swing library. > > Can you be more specific? Python and Jython allow classes to be modified at > runtime without changing the source code or compiling new code. For example > you can add and remove methods and attributes from a class and change the > base classes of a class. You can also modify individual instances of a class > to change their attributes and behaviour independently of other instances of > the class. What are you trying to do? For example see > http://groups.google.com/group/comp.lang.python/browse_frm/thread/8f7d87975eab0ca4/18215f7ce8f5d609?rnum=15#18215f7ce8f5d609 > http://groups.google.com/group/comp.lang.python/browse_frm/thread/a0b19b37ac48deaa/e599041de4b8feb0?rnum=22#e599041de4b8feb0 > > Kent thanks for links, I'll look at them. Alan showed me some possibilities, i'm not quite sure how to initiate modification and the way import keyword works in case of modified imported modules. my typical scenario is that my swing application is running, and i see some error or chance for improvement - modify sources of app, stop and run application again. so task is to reload class defitions (from source files) and modify also existing instances (their methods). Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying source at runtime - jython case
Kent Johnson wrote: > Jan Gregor wrote: > >> my typical scenario is that my swing application is running, and i see >> some error or chance for improvement - modify sources of app, stop and >> run >> application again. >> so task is to reload class defitions (from source files) and modify also >> existing instances (their methods). > > > Ok, I think my first reply completely missed the mark. IIUC what you > want is hard. This recipe might help: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > > Kent Yes, this is right way. And it's working. Thanks, Jan -- http://mail.python.org/mailman/listinfo/python-list
special method in module
Hello, can have modules special methods? althouht i think that no, i tried following example and i don't, why it don't works: file m2.py (imported module) class Module: def __getitem__(self,index): return index module=Module() __getitem__=module.__getitem__ --- file m1.py (main program): import m2 print m2.__getitem__(17) # prints 17 print m2[17] # raises error -- thanks Honza Prochazka -- http://mail.python.org/mailman/listinfo/python-list
Re: special method in module
Thanks, probably you are right, hacking python in my situation is not neccessary... >Jan Procházka wrote: > > > >>can have modules special methods? >> >> > >no, but you can replace the module object with something that can have >special methods: > >$ more module.py >import sys > >class Module: >def __getitem__(self, value): >return value > >sys.modules[__name__] = Module() > >$ python > > >>>>import module >>>>module[10] >>>> >>>> >10 > >as with any other introspection hack, you should only use this if you have >very good reasons. > >(saving some typing in import statements is not a good reason; creating a >module that's a transparent proxy to some external system might be. but >in such cases, you should stick to attribute hooks/descriptors, and make >sure that code that uses your proxy looks like code that uses an ordinary >module. Python always works better if you use it to write Python code...) > > > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: about polygon
Hi! Am Sun, 20 Nov 2005 03:55:21 -0800 schrieb Shi Mu: > Why I got a black polygon in the following code? > How can I make it no-color filled? Use create_line instead: c.create_line(60,60,100,60,100,100,60,120,60,60) Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: about polygon
Hi Am Sun, 20 Nov 2005 04:45:52 -0800 schrieb Shi Mu: > If so, what is the difference between create_line and create_polygon? create_polygon only creates closed polygons. Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Python XML Data Binding Utilities Avaiable?
SeSe wrote: Hi, every one, happy new year! I am working on XML with Python. I wonder if there is any XML Schema<-> Python Object mapping tools so that we can convert one to another. Thanks. You may want to look at generateDS. It can generate Python data structures from an XML Schema document. It supports only a subset of the schema spec, but is nonetheless quite useful. See http://www.rexx.com/~dkuhlman/generateDS.html There's also minixsv, which does something similar. I've never used it myself though. See http://www.leuthe.homepage.t-online.de/minixsv/minixsv_overview.html The most complete Schema validator in Python is probably XSV. It doesn't have the ability to generate Python object mappings though. See http://www.ltg.ed.ac.uk/~ht/xsv-status.html Another extensive schema parser is part of (and well hidden in) the wsdl toolset from the pywebsvcs project. It does support Python object mapping generation, but the usefulness of the result is limited outside the context of web services. See http://pywebsvcs.sourceforge.net/ Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Another look at language comparisons
[EMAIL PROTECTED] wrote: From the web site: "Why Microsoft can Blow-Off with C#? These people have thought up programming languages Fortran, Prologue, Ada." The author is ignorant. Fortran was invented by IBM in the late 1950s, long before Microsoft existed. Ada was commissioned by the U.S. Department of Defense in the 1970s. The Prolog programming language is not spelled "Prologue". I don't think that "these people" is refering to Microsoft. Instead, it is refering to the three pictures below the text. I assume they are the pictures of the respective authors of these languages. The bottom line of the article is that languages authored by men with beards are more successful than those authored by people without beards. At least the anecdotical evidence to that is overwhelming :-) And there is hope for Python, as Guido has recently been seen with a beard :-) http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Integration with java (Jpype vs. JPE)
Istvan Albert wrote:
Now I remember visiting this site, but never understood how it
actually worked. Examples such as:
from jpype import *
startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()
in three different versions are the only code examples
that to show "complete" working snippets. I'm still
clueless as to how would one say share a list between
python and java.
A while ago there was a thread in c.l.p about using JPype to access JMS
from within Python. IIRC someone then contributed a more elaborate real
life example of how to do this. Search Google Groups for more details.
Regards,
Jan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Solutions for data storage?
Leif K-Brooks <[EMAIL PROTECTED]> schreef: > > I've looked at SQLObject, and it's very nice, but it doesn't > provide certain features I really want, like the ability to store > lists of strings or integers directly in the database (using commas > in a varchar column or something). What exactly in SQLObject prevents you from doing this? You may have to pack/unpack the list into a comma separated string yourself, but surely the 2 line code function that requires can't be the problem. And SQLObject's support for properties makes this very clean. See: http://www.sqlobject.org/docs/SQLObject.html#adding-magic-attributes-properties Or am I missing something here? Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Luke Skywalker <[EMAIL PROTECTED]> schreef: > On Wed, 19 Jan 2005 14:13:47 -0500, Timothy Fitz > > While I agree that the Zen of Python is an amazingly concise list > > of truisms, I do not see any meaning in: > > For those interested, here's the list: > http://www.python.org/doc/Humor.html#zen Or you just type at the interactive prompt: >>> import this Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: redirect of standard output of jython to JTextArea
problem solved.
in class:
sys.stdout = StdOutRedirector(self)
class StdOutRedirector:
def __init__(self, console):
self.console = console
def write(self, data):
#print >> sys.stderr, ">>%s<<" % data
if data != '\n':
# This is a sucky hack. Fix printResult
self.console.textArea.append(data)
Jan
Jan Gregor wrote:
Hello
I want to redirect output of jython's functions print and println to
JTextArea component. Is it possible ?
I tried this (swingConsole.textArea is instance):
In my class
self.printStream= MyPrintStream(System.out)
System.setOut(self.printStream)
class MyPrintStream (PrintStream):
def println (str):
swingConsole.textArea.append(str)
def print (str):
swingConsole.textArea.append(str)
Output is still directed to standard output.
Thanks for help,
Jan
--
http://mail.python.org/mailman/listinfo/python-list
redirect of standard output of jython to JTextArea
Hello I want to redirect output of jython's functions print and println to JTextArea component. Is it possible ? I tried this (swingConsole.textArea is instance): In my class self.printStream= MyPrintStream(System.out) System.setOut(self.printStream) class MyPrintStream (PrintStream): def println (str): swingConsole.textArea.append(str) def print (str): swingConsole.textArea.append(str) Output is still directed to standard output. Thanks for help, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E01: The Java Failure - May Python Helps?
Fredrik Lundh wrote: Markus Wankus wrote: Google his name - he has been banned from Netbeans and Eclipse (and Hibernate, and others...) for good reason. Can you imagine how much of a Troll you need to be to *actually* get "banned" from the newsgroups of open source projects such as those? have Pythoneers ever "banned" anyone from a public forum? it's not like we haven't seen trolls and crackpots before, you know. Well, we don't have to ban them because we have the PSU eliminate them alltogether. So much more efficient. Or do you think it's a coincidence we've never seen or heard Timothy "autocoding" Rue again? Be afraid, Xah, be very afraid. Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Graphs/statistics using wxPython
Hello all, I wanted to plot some statistics, so I wrote a simple wxPython class to do it. Then I realized that I would like to draw bar graphs, so I added that too. Since I'm a complete Python newbie, I haven't done much of it the "Python way", I suspect. So, I'm wondering if someone would like to show me some of the tricks I should have used. You can find the code at: http://user.it.uu.se/~jada3673/drawtest.py It's not finished[*], but it is usable. Oh, you can do whatever you want with it. Since I had never touched wxPython before working with this, I used some doodle application as a starting point. Btw... Has anyone already written statistics classes for wxPython? If so, where can I find them? If nothing similar exists, I'll probably add support for loading data from a file, and a few other features. Feel free to make requests or enhancements. [*] There are some size/offset bugs which I am aware of, but they are easily fixed. I just haven't got around to it yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs/statistics using wxPython
Robert Kern wrote: >>I wanted to plot some statistics, so I wrote a simple wxPython class >> to do it. Then I realized that I would like to draw bar graphs, so I >> added that too. >> >>Since I'm a complete Python newbie, I haven't done much of it the >> "Python way", I suspect. So, I'm wondering if someone would like to show >> me some of the tricks I should have used. > > > Trick #1: > > import matplotlib Oh. :-) That's a pretty neat trick -- now can you make my embarrassment go away? I did do a quick search to see if anyone had done anything similar; but I guess I wasn't using the right keywords. > ;-) You may point and laugh. Damn, that's a neat toolkit! Thanks for pointing me to it! -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs/statistics using wxPython
Robert Kern wrote: [---] > It's okay. Just about every Pythonista in the sciences has, at one time > or another, started a plotting library. It's a rite of passage. Welcome > to the club. :-) Question: I need to install SciPy in order to use matplotlib, but on the download page I see that there are versions for Python 2.2.x and 2.3.x. I use 2.4.1 -- will bad things happen if I try to use the build for 2.3.x? -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs/statistics using wxPython
Robert Kern wrote: >> [---] >> >>> It's okay. Just about every Pythonista in the sciences has, at one time >>> or another, started a plotting library. It's a rite of passage. Welcome >>> to the club. :-) >> >> >>Question: I need to install SciPy in order to use matplotlib, > > No you don't. Ah.. I misread. I read http://matplotlib.sourceforge.net/installing.html, the section which describes what "enthought python" contains, and thought it meant "this is relevant to matplot lib". >> but on >> the download page I see that there are versions for Python 2.2.x and >> 2.3.x. I use 2.4.1 -- will bad things happen if I try to use the build >> for 2.3.x? > > Yes. Scipy has many extension modules; such modules built for 2.3.x > won't work for 2.4.x, etc. So, for future reference: I should *never* mix x and y versions in verion: x.y.z. I've wondered why there are versions of libraries for different versions of Python.. -- http://mail.python.org/mailman/listinfo/python-list
Question about Python
Hello all, I recently started using Python, and I must say I like it. Both the language and libraries available for it. Background: I have written an application which I use to keep track of my personal economy. I wrote it in Java because I wanted to learn the language for a course in programming at my university. Now that I have acquired an interrest in Python I was thinking about porting my program to Python. But then it occured to me.. I started writing my program in Java pre-1.5. Then came 1.5, I upgraded, and my program would still compile and run, though I did get three warnings. The language had changed a little bit; I had to assign a type to three arrays. That wasn't so bad. However, when I look at the various Python modules/libraries, I see that there are several versions of them, for different versions of python. I've seen everything from "for python 1.5" up to "for python 2.4" with all versions in between. This scares me a little bit. I assume that the reason for the different versions is because of new language features? Is Python showing any signs of "stabilizing"? (Yes, I know there are pros to an evolving language). Will there ever be a time when a new major version of python won't mean getting new versions of the modules? For my economy program, I used DB2 as a database backend. I can be reasonable sure that there will always be a DB2 API for Java. However, I have found a DB2 module for Python, but I don't even know if it works with Python 2.4, and if I compile and use it, I can't be sure it'll work with the next python release, as far as I can tell. I'd like to ask seasoned Python developers: - Are you comfortable in upgrading to the latest version of Python, or are you worried about what you have to fix in your existing programs? - Put aside any unconditional love for Python for a second, and be honest: Have you ever run into version related problems? - Have you ever relied on a module, upgraded python version for some new important feature, but realized that the module you rely on hasn't been updated yet? If not, do you consider a possibility? - Do the module developers, in general, keep up with the development versions of python, so you can expect to find newly updated modules as new versions of python hits the streets? - Did you have similar worries to mine when you started working with Python? Please be honest.. It's better that I find out any potential problems now, than rant about them in six months. Thanks in advance to anyone willing to answer. -- http://mail.python.org/mailman/listinfo/python-list
Stupid question: Making scripts python-scripts
Hello all, How do I make a python script actually a _python_ in unix:ish environments? I know about adding: #!/bin/sh ..as the first row in a shell script, but when I installed python on a NetBSD system, I didn't get a "python" executable; only a "python2.4" executable. Adding "#!/usr/pkg/bin/python2.4" as the first row in the script would probably work, but that would be too specific for the system I'm using, imho. I saw someone using "#!/usr/bin/env python", but that failed on the system I'm using, so I assume that's something specific too (or is the installation broken?). -- http://mail.python.org/mailman/listinfo/python-list
Data available on socket?
Hello all, How do I find out if a blocking socket has data available [for reading] on it? I assume I could do something like this: tmp = self.read(1, socket.MSG_PEEK) if len(tmp) > 0: # Data available But is there a better way? A call which specifically checks if data is available? -- http://mail.python.org/mailman/listinfo/python-list
Lists & "pointers"
Hello all,
I have written a simple whiteboard application. In my application, I
want to be able to set draw attributes. This part works. I have a
dictionary object which contains stuff like:
self.attr['Pen.Color'] = ...
self.attr['Pen.Thickness'] = ...
Now, the problem is that I want to be able to store attributes in a
list so they'll be easily accessed using the function keys. I.e. I have
the "current attributes" which I want to be able to store or retrieve
in/from a list,
The problem is that I have initialized the list like this:
self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr)
I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).
Also, how do I store/restore entries to the list?
I have found the "copy" module, and it's copy method. I assume this
would work:
for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))
However, the concept of "deep copy" confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.
Thankful for any advice.
--
http://mail.python.org/mailman/listinfo/python-list
First app, thanks people
Hello all, I have written my first Python application (apart from small test programs). It's a (distibuted) white board application. I'm going to assume that there already are a thousand of them, written in Python, but just in case someone would find it useful: http://user.it.uu.se/~jada3673/applications.php Direct link: http://user.it.uu.se/~jada3673/apps/whiteboard.py Since I'm a Python beginner, the code is very suboptimal. Anyway, I believe it may be good reference code for beginners. Oh, I do have one more question though. I'm using wxPython, and when I check for keys I use the evt.GetKeyCode() call, and compare it with integers which I have found by printing what event.GetKeyCode() returns. I would prefer a more portable way, since I assume that F1 doesn't have the same code on a Sparc Ultra10. (?) Is there a way to get "key codes" in wxPython in a portable manner? I'd also like to thank all of those who have helped me in this group, and thank everyone else for the interresting discussions. As for license: Do whatever you want with it, but don't blame me if it breaks anything or causes spontaneous pain, death or pregnancies. -- http://mail.python.org/mailman/listinfo/python-list
Re: First app, thanks people
Dark Cowherd wrote: [---] > In case you are interested in bug report. Always! > class LineTool > method OnLeftUp > needs > self.done = True > > or else if you are in Line mode and you just click with out moving the > mouse you get an error. Many thanks; I can't believe I hadn't stumbled across that bug myself while testing it. Though you are free to do whatever you want with the code, I wouldn't mind seeing any improvements made to it by others, so that I myself may learn from it. -- http://mail.python.org/mailman/listinfo/python-list
Re: First app, thanks people
Will McGugan wrote: [---] > You should use the keycode constants. > > http://www.wxwidgets.org/manuals/2.6.1/wx_keycodes.html#keycodes [---] Excellent! Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Escaping certain characters
Hello, I'd like to encode the string that outputs: Hello World! to 'Hello\x0aWorld!', and the string that outputs: Hello\World! to 'Hello\\World!'. Obviously, I want to be able to reverse the process. I'm going to assume this has already been solved in Python.. But how? -- http://mail.python.org/mailman/listinfo/python-list
Re: Escaping certain characters
Robert Kern wrote:
[---]
> In [3]: s.encode('string_escape')
> Out[3]: 'Hello\\nWorld!'
>
> In [4]: Out[3].decode('string_escape')
> Out[4]: 'Hello\nWorld!'
>
> Not *quite* what you asked for, but it ought to be close enough.
That'll do just fine. Many thanks!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Escaping certain characters
Jan Danielsson wrote:
>>In [3]: s.encode('string_escape')
>>Out[3]: 'Hello\\nWorld!'
>>
>>In [4]: Out[3].decode('string_escape')
>>Out[4]: 'Hello\nWorld!'
>>
>>Not *quite* what you asked for, but it ought to be close enough.
>
> That'll do just fine. Many thanks!
Hmm... On second thought, I need to escape more characters.
Is there no other way to escape characters in strings?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Escaping certain characters
Robert Kern wrote:
[---]
>> Hmm... On second thought, I need to escape more characters.
>>
>> Is there no other way to escape characters in strings?
>
> Which characters?
I need to escape '\n', '"', '[' and ']'. I finally went with a few of
these:
string.replace('\n', '\\n')
string.replace('"', '\\"')
...
I assume that's good enough, but I somehow expected there to exist
some form of "insert your conversion table here" built-in string escaper.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Escaping certain characters
Robert Kern wrote:
[---]
>>I need to escape '\n', '"', '[' and ']'. I finally went with a few of
>> these:
>> string.replace('\n', '\\n')
>> string.replace('"', '\\"')
>> ...
>>
>>I assume that's good enough, but I somehow expected there to exist
>> some form of "insert your conversion table here" built-in string escaper.
>
> Write a codec.
Is that what string.encode() uses? Some behind-the-scenes "codec"? I
tried searching for it, but could only find UTF/Unicode-related
information. Is it in the normal python documentation?
Semi-Offtopic: The "search" facility in the Python help has stopped
functioning for me (I'm using XP on this system). No matter what I
search for, I get no results. A week ago, I got a lot of hits for almost
anything I searched for. Anyone seen this behavior, and knows what to do
about it?
--
Kind Regards,
Jan Danielsson
Te audire no possum. Musa sapientum fixa est in aure.
--
http://mail.python.org/mailman/listinfo/python-list
Documentation
Hello all, What is the proper way to document a class in Python? I have written a few python libraries that I would like to document. I'm doing a lot of this: class Foo(object): """ This is a class which blah, blah, blah... It's features are blah, blah, blah... """ def addStuff(self): """ This method does blah, blah, blah... """ I'm going to assume that Python has some "official" tool which can be used to automatically create documentation for a .py-file (like Java does), but what do I need to do to support it, and how does it work? -- Kind Regards, Jan Danielsson Te audire no possum. Musa sapientum fixa est in aure. -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
> Xah is very well known as the resident troll in many NGs and his 'contributions' are less then useless. > > Best is to just ignore him. Did you know that some deranged people take sexual pleasure out of starting fires? Apparently some of the latest forest/bush fires in southern Europe were even started by firemen (with their pants down?). Maybe characters like Xah take some kind of sexual pleasure out of posting his kind of posts... the tought doesn't bear thinking, does it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
> +---+ .:\:\:/:/:. > | PLEASE DO NOT |:.:\:\:/:/:.: > | FEED THE TROLLS | :=.' - - '.=: > | | '=(\ 9 9 /)=' > | Thank you, | ( (_) ) > | Management | /`-vvv-'\ > +---+ / \ > | |@@@ / /|,|\ \ > | |@@@ /_// /^\ \\_\ >@x@@x@| | |/ WW( ( ) )WW >\/| |\| __\,,\ /,,/__ > \||/ | | | jgs (__Y__) > /\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ Please don't use ASCII art... not everyone uses a fixed-width font for his newsreader... (your picture looks all mangled here) -- http://mail.python.org/mailman/listinfo/python-list
Re: What are new-style classes?
Vaibhav wrote: > I recently heard about 'new-style classes'. I am very sorry if this > sounds like a newbie question, but what are they? I checked the Python > Manual but did not find anything conclusive. Could someone please > enlighten me? Thanks! In short: They have inherited "object" from somewhere. (This is probably technically inaccurate, but it's the only thing I have seen which defines a 'new-style class'). What it means *practically*, is that you can use properties. For a long while I didn't really understand the point or properties, until I needed them. I have written a flowcharting application in Python. All objects on the flowchat are derived from a base object which has the attribute "text" (all objects have some form of, sometimes internal only, title). Problem is that when some objects change text, I want to perform some recalculations. So I wrote a "text" property, which - in its settext-method - does all the calculations if required. That way, the application can till use: obj.text = 'Blah' ..and still have the chance to act on the text change. I could have simply written a setText() method, but imho properties are neater - but that's just a matter of opinion. -- Kind Regards, Jan Danielsson Te audire no possum. Musa sapientum fixa est in aure. -- http://mail.python.org/mailman/listinfo/python-list
python script under windows
Hello I run python script on another computer and want to "survive" that script after my logout. the script also uses drive mapping to network drive. Can you help me ? Or better is there some info for unix person how to survive with python on windows ;-) thanks, jan gregor -- http://mail.python.org/mailman/listinfo/python-list
Re: Pypy - Which C modules still need converting to py?
Caleb Hattingh wrote: Anyone have that page ref handy listing the C modules that the pypy team need translated into python? http://codespeak.net/pypy/index.cgi?doc/cmodules.html Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler
Ilias Lazaridis wrote: they above 2 questions are coherent, thus answering isolated [as you've done] makes not much sense. " >> Should I take answers serious? >> Answer from people which do not respect coherence of writings? " Except that the quote here above is NOT what was in your original posting. Here is the *real* quote (also note that Python uses """ instead of " for delimiting a multi-line string: """ Should I take answers serious? Answer from people which do not respect coherence of writings? """ If you insert a blank line between two sentences most people in this newsgroup (and in the western world in general) will interprete that as the start of a new paragraph, as an indication that what follows is something different than what precedes the blank line. If you want to obtain "coherence of writing" between two sentences, then maybe you shouldn't type them as different paragraphs. If you would have written: """ Should I take answers serious? Answer from people which do not respect coherence of writings? """ it would have been much more coherent. Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Install problem Windows xp HE
I have tried to install Python 2.4 on two pc-s and get this error when I follow the instruction and type python at the comand window or Idle window. I am running Windows xp home edition. What am I doing wrong? I have also ask for explanation on Googles and got the answer that there is such a problem but can'not understand the message. Sincerely Jan Ekström Here is the error.IDLE 1.1 >>> python Traceback (most recent call last): File "", line 1, in -toplevel-pythonNameError: name 'python' is not defined>>> -- http://mail.python.org/mailman/listinfo/python-list
[OT] Re: SysLogHandler is drivin me nuts PEBCAC
Slightly OT, but regarding the title, shouldn't it be PEBKAC, since it's keyboard and not ceyboard? Regards, Jan michael wrote: Vinay Sajip <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... michael wrote: Yep it was incomplete heres the complete config as it has to be [config file snipped] The complete file looks OK. Thx. with this file it is working. The syslogd configuration under AIX was buggy. regards Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Re: SysLogHandler is drivin me nuts PEBCAC
[Jan Dries] > Slightly OT, but regarding the title, shouldn't it be PEBKAC, > since it's > keyboard and not ceyboard? [Vinay Sajip] > PEBCAC: Problem Exists Between Chair And Computer Interesting. I thought it was "Problem Exists Between Keyboard And Chair". But this makes sensee too, of course. Nonetheless, Google has about 17000 references for PEBKAC, and only 381 for PEBCAC. Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: jython and concatenation of strings
Ok, thanks. I didn't think that += operator is nondestructive operation - but strings are immutable so this makes sense. On 2004-12-13, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: >> I found that price of += operator on string is too high in jython. For >> example 5000 such operations took 90 seconds (i generated html copy of >> table with 1000 rows and 5 columns). Generation of row data into separate >> string and joining after lead to time 13 seconds !!! > > Its generally not recommended to use simple string concatenation for > building larger strings - neither in python nor in java/jython. > > afaik there are two solutions to this: The java-way and the jython way: > > java: Use StringBuffer > python: use a list, and append the strings to that. Then, when you want the > result, do > > "".join(stringlist) > -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing DB2 with Python
Shawn Milo wrote: Is anyone doing this? I would like to access a DB2 database (IBM's database) with Python. I checked "Python in a Nutshell," and it refers to ftp://people.linuxkorea.co.kr/pub/db2, but I am unable to connect to that site, although it could be a firewall issue, as I am at work. Is there any commonly used module for this? You could try mxODBC. It has support for DB2. You can find it at: http://www.egenix.com/files/python/mxODBC.html You can download it for free and use it for a 30 day evaluation period. After that, you must pay for a commercial license. Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
jython and concatenation of strings
Hello I found that price of += operator on string is too high in jython. For example 5000 such operations took 90 seconds (i generated html copy of table with 1000 rows and 5 columns). Generation of row data into separate string and joining after lead to time 13 seconds !!! What's alternative way to do that ? (similiar parts of my code are terribbly slow and such simple solution as above didn't help). Thanks, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: jython and concatenation of strings
StringBuffer class from java was right solution - yours looses encoding, and in jython I was unable to get it back - in python it worked fine. Jan > I don't use Jython, but are you not able to do something like: > > string_list = [] > for ... in ...: > ... > string_list.append(...) > ... > string = ''.join(string_list) > > This is the usual Python idiom and is usually faster than the += idiom. > > Note too that +ing strings in Java also has this problem -- hence > StringBuffer or whatever it's called. > > Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Michael Hoffman wrote:
Gregor Horvath wrote:
> Or make any given standard python object accessible from MS Excel in 2
> minutes.
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0)
xlApp.Quit()
del xlApp
(stolen from <http://www.markcarter.me.uk/computing/python/excel.html>)
Nice, but not really what the OP asked for. You make Excel accessible
from Python, instead of the other way round.
Regards,
Jan
--
http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Andrew Dalke wrote: [snip] It looks like FMOD/PySonic is the closest to what I'm thinking of, and Snack coming in second. I didn't look too deeply. Most of them only play sound clips (mp3, wav, etc.) and don't have a way to specify what notes to play. If you just want to play notes, you could look at MIDI. There's a Python module out there somewhere that reads and writes MIDI-files. And there's plenty of programs (such as Windows Media Playes) that can play MIDI files or can convert them to mp3 or wav or whatever. In fact, I used all of these a while ago to enable me to write something like: import midi notes = ( "MySong", """ instrument(piano) key(4b) vol(mf) tempo(4=100) F4 A4 A4 A2 A4- A4 G4 F4 G2 G2 r4 F4 F4 F4 A2- A4 A4 G2 G4 B4 B4 A4 B4 C'2. r32 A4 C'2 C'2 C'4 C'4 C'4 B4 A4 B2 B2 r16 C'2 A2 G4 B2 B4 A4 F2. G4 E2 F2. """ ) midi.generate(somefilepath,notes) to generate MIDI-files from a simple notes description. Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: MIDI library recommendations, please?
Andrew Koenig wrote: Are there widely used and recommended Python libraries that will let me 1) Interpret and generate MIDI messages easily? I'm not sure this is "widely used and recommended" but I've used the following in the past: http://sgce.cbse.uab.edu/SoundOfSequence/midi/midi.py It's simple, but it handles the basics (reading and writing MIDI). I've easily built the rest I needed on top of it. Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Andrew Dalke wrote: Jan Dries If you just want to play notes, you could look at MIDI. [snip] It's hard to compare that to the current era. Sound clips are much more common, it's easy to record audio, keyboards and other specialized devices are cheap, and there's plenty of mixer and recording software. Were I to have started now I would have taken a different course and perhaps one of these newer things would have interested me more. The funny thing is, for me, MIDI is dead old. One of my first computers, back in 1986, was an Atari ST. It came equiped with a MIDI port. And the MIDI file format was created in those days, on Atari. The Atari also had a Yamaha YM2149 sound chip on it that one could mess with in the way you describe, and I did play with that too. But the cool thing about MIDI was that it came with additional stuff, such as multiple voices, and different timbres for different instruments. And I didn't have to bother with the attack-decay-sustain-release envelope in order to make my notes sound like notes instead of beeps. Playing with the sound chip was like assembler, while playing with MIDI was more like a higher level language. At the time I was a teenager and couldn't afford my own keyboard though, and the Atari didn't have a sufficiently sophisticated audio system for playback of MIDI files. Back in 1995 my then girlfriend wrote a thesis on AI where she did an analysis of Rachmaninov's Ampico rolls in an attemt to try to extract characteristics from that that could be applied to any piece of music to make it sound more "human" than when played by a computer. I helped her out by writing a "notes to MIDI" converter, to make the results of her work audible. I seem to remember that even then we still had to rely on a keyboard or so to do the playback. But nowadays even the cheapest PC comes with "multi-media" sound hardware, and playback of MIDI files is easy. And the nice thing for me to find out is that the good old file format from back in the days on Atari is still out there, and well supported by programs like Windows Media Player. Frankly I share your sentiment and "these newer things" like sound clips, mixers, recording software and so have never managed to interested me either. But MIDI is not among those, at least not for me. Because of my particular background, MIDI has for about 20 years now been the "serious" way to playing notes. And in fact, to the best of my knowledge it is still the easiest way to get decent notes out of my PC. A while ago I bought a few software packages that enable one to enter notes and play them back. After trying out half a dozen of these, I ended rolling my own solution in just 400 lines of Python, plus a Python module to read/write MIDI files. Regards, Jan Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
python2.6 needed as an aptitude package as dependency
Hello, I need to install a program (MACS: http://liulab.dfci.harvard.edu/MACS/) for which I need to have Python2.6 installed. I do have two other Pythons installed but not this version. 1) So I tried apt-get install... python2.6 is not there as a package (I am running Linux Mint 15). 2) Okay, I added some repos to the /etc/apt/sources.list: deb http://packages.linuxmint.com/ debian main upstream import deb http://debian.linuxmint.com/latest testing main contrib non-free deb http://debian.linuxmint.com/latest/security testing/updates main contrib non-free deb http://debian.linuxmint.com/latest/multimedia testing main non-free I ran apt-get update... python2.6 not there 3) I downloaded python2.6 as a source tar and compiled it and installed with make altinstall... Python2.6 is installed. When I enter "python" in the command line and hit Tab, I can see there now all three versions of python. Still I get the same error: dpkg: dependency problems prevent configuration of macs: macs depends on python2.6; however: Package python2.6 is not installed. I will be grateful for your suggestions, Jan -- https://mail.python.org/mailman/listinfo/python-list
How do I get curses to work in Python 3.2 on win-64?
How do I get curses to work in Python 3.2 on win-64? I'm new to Python and when exploring Python in console I want to use some simple functions for console programming that don't emulate a typewriter terminal but rather a text screen terminal. I want to be able to clear the screen, position the cursor and do unbuffered reading from the keyboard. Also setting different colors for the text and background. That could in Windows be accomplished by the handy WConio (http:// newcenturycomputers.net/projects/wconio.html) which contains just about everything that is needed for a console application to become useful. However I want to accomplish it in Python 3.2 because I lack the experience to build it myself. Now an alternative would be to use some flavor of curses. Although having a plethora of unnecessary functions it has the advantage of existing for different platforms. I'm currently running Python 3.2.2 on win-64 When Python is installed there is a Python32/Lib/curses library. As I understand it this is only a some sort of wrapper for a curses module to be downloaded and installed later?? So I downloaded and installed a curses module I that found and which seemed appropriate: curses-2.2.win-amd64-py3.2.exe from http://www.lfd.uci.edu/~gohlke/pythonlibs/ It installed some stuff directly in Python32/lib/sitepackages. Now when I try in a program to do things like: import curses stdscr = curses.initscr Python complains it can't find curses. However if I do import _curses stdscr = _curses.initscr etc., everything works fine. I shouldn't have to write the underscores though?? How can I fix that? Should I try to find some other version of curses? It seems I haven't yet grasped how to install a Python module? /John -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get curses to work in Python 3.2 on win-64?
On 16 Okt, 06:59, Christoph Gohlke wrote: > On Oct 15, 1:13 pm, Jan Sundström wrote: > > > > `import curses` should work. What exactly is the error message? Does > `import curses` work outside your program/program directory? > > The curses package is part of the standard library and usually > installed in Python32\Lib\curses. On Windows the _curses.pyd files is > missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe > installs the missing _curses.pyd file into Lib/site-packages. Thanks for the tip to check in what library it works, that set me on track tofind a silly mistake that I had done. Now everything works fine. But, how come that the Windows distribution for Python doesn't include the _curses.pyd file? -- http://mail.python.org/mailman/listinfo/python-list
Re: "monty" < "python"
From the docs[0]: "Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior." [0] http://docs.python.org/2/reference/expressions.html#not-in On 20.03.2013, at 14:33, franzferdinand wrote: "Monty" < "Python" > True "Z" < "a" > True "Monty" < "Montague" > > False > What's the rule about that? Is it the number of letters or what? > thanks > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: "monty" < "python"
Interesting. Thanks! On 20.03.2013, at 15:17, Ian Foote wrote: > On 20/03/13 13:38, Jan Oelze wrote: > >> "Strings are compared lexicographically using the numeric equivalents >> (the result of the built-in function ord()) of their characters. Unicode >> and 8-bit strings are fully interoperable in this behavior." > > This isn't true in python 3: > > Python 3.2.3 (default, Oct 19 2012, 19:53:57) > [GCC 4.7.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> b'bytes' < 'unicode' > Traceback (most recent call last): > File "", line 1, in > TypeError: unorderable types: bytes() < str() > > Ian F > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python GUI questions
On 19.03.2013 21:01, maiden129 wrote: Hello, I'm using python 3.2.3 and I'm making a program that show the of occurrences of the character in the string in Tkinter. My questions are: How can I make an empty Entry object that will hold a word that a user will enter? How to make an empty Entry object that will hold a single character that the user will enter? [..] Hello, here is a very good documentation about Tkinter and its most likely that the same principals of coding apply to Python 3.x when it comes down to the Tkinter part: http://www.pythonware.com/library/tkinter/introduction/index.htm Also as an tip, you can make use of a StringVar object for example - those are (if Im not completely wrong) meant to hold values which you can then access from the interface. Alike a binding to any element holding text. Which should take care of the updating part if you call a proper "StringVar/yourVariableName".set method of that particular class. As for the UI creation, have a look at that documentation, its very easy to navigate inside if you know what you are looking for. Regards Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorating functions without losing their signatures
On 03.04.2013 04:05, Rotwang wrote: Hi all, Here's a Python problem I've come up against and my crappy solution. Hopefully someone here can suggest something better. I want to decorate a bunch of functions with different signatures; for example, I might want to add some keyword-only arguments to all functions that return instances of a particular class so that the caller can create instances with additional attributes. So I do something like this: [...] It seems to work, but I don't like it. Does anyone know of a better way of doing the same thing? Hi, I think you might want to check out that Pycon2013 Video about Metaclass Prgoramming of David Beazley: http://www.pyvideo.org/video/1716/python-3-metaprogramming He explains how to passing attributes, such creating custom classes on demand and returning there signatures even when wrapped. I think that was what you wanted to archive? Regards Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: can anyone help me in developing a simple webpage in jinja2
On 06.04.2013 01:41, Satabdi Mukherjee wrote:
i am a rookie in python and i am trying to develop a simple webpage using
jinja2.
can anyone please help me how to do that
i am trying in this way but showing invalid syntax error
[...]
{% for item in navigation %}
{{ item.caption }}
{% endfor %}
My Webpage
{{ a_variable }}
[...]
Hello,
the jinja2 syntax is correct that way, see also this for reference for
variable naming:
http://jinja.pocoo.org/docs/templates/index.html#variables
The invalid syntax is raised when? Can you post the error a bit more
detailed, this will help giving you any advice.
If you know the code part raising the error and you post it, this will
also help.
Jan
--
http://mail.python.org/mailman/listinfo/python-list
Puzzled by py.test output
I'm seeing a strange difference between error reporting on local versus global variables, when using py.test. Upon error, the actual value of a local is reported, but not of a global. Does anyone know why? I'm using the latest development version of py.test (from subversion). Example code in file test.py: -- def test_h(): h = 0 assert h == 1 g = 0 def test_g(): assert g == 1 -- py.test output: = test process starts testing-mode: inprocess executable: /usr/local/bin/python (2.4.2-final-0) using py lib: /usr/local/lib/python2.4/site-packages/py test.py[2] FF __ _ entrypoint: test_h __ def test_h(): h = 0 E assert h == 1 > assert 0 == 1 [/home/jand/project/myhdl/example/cookbook/stopwatch/test.py:3] _ entrypoint: test_g __ def test_g(): E assert g == 1 > assert g == 1 [/home/jand/project/myhdl/example/cookbook/stopwatch/test.py:7] _ == tests finished: 2 failed in 0.02 seconds == Regards, Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium From Python to silicon: http://myhdl.jandecaluwe.com -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANNOUNCE] MyHDL 0.5 released
Michael wrote: > Jan Decaluwe wrote: > > >>I'm pleased to announce the release of MyHDL 0.5. >> >>MyHDL is an open-source package for using Python as a hardware >>description and verification language. Moreover, it can convert >>a design to Verilog. Thus, MyHDL provides a complete path >>from Python to silicon. > > > Jan, > > > I'm not sure if you read c.l.p, but if you do... > > I'm looking at the website and I see that you've now got an example showing > translation to verilog - which is really cool. I also saw that someone's > done what I view as a complex example - specifically the MU0 example [*] > (which is a tutorial I remember from student days!) as a MyHDL simulation. > >* http://article.gmane.org/gmane.comp.python.myhdl/19/match=mu0 > > One question I've got, mainly because it strikes me as very intriguing is > do you know if the MU0 processor as described is synthesisable or have a > feeling as to how much work would be needed for it to be synthesisable? This is a fairly "old" project (2003). At that time, MyHDL didn't yet have conversion to Verilog. After reviewing the code again, it's clear that it's written in RTL (register-transfer level) style. This means that the building blocks are combinatorial, or triggered on clock edges, closely reflecting an actual implementation. As it is, it's not convertible to Verilog (see the MyHDL manual for conversion constraints), but it's close. To someone with some synthesis experience, it should be fairly straightforward to make the code synthesizable. I don't expect that this would make the code more verbose or less clear. > I've been watching your project grow over the past couple of years with > great interest though little actual need at the moment, but for me seeing > MU0 crop up piques my interest because that shows that MyHDL is getting up > to a very interesting level. As your interest was apparently triggered by an example, this tells me that I should put more emphasis on publishing practical examples, as conversion to Verilog was already introduced some time ago (beginning of 2004). Note also that by now, there are designers that use MyHDL in real projects, showing that you really can use it to go from Python to an FPGA (or ASIC). Moreover, with development tools such as Xilinx WebPack (now on Linux also) that start from Verilog, this can be done using a zero-cost development environment. Regards, Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium From Python to silicon: http://myhdl.jandecaluwe.com -- http://mail.python.org/mailman/listinfo/python-list
Re: MyHDL 0.5 released
Randall Parker wrote: > Jan, > > What do you see as the main advantage for using MyHDL rather than VHDL > for coding up a chip design? The fact that MyHDL is technically just another Python application. So it makes all typical Python advantages available to hardware designers. No need to discuss those in this forum :-). An additional advantage for this case may be that Python is a "mainstream" language, while VHDL/Verilog are really niche languages. Those who agree with the above may still have two questions: 1) is it meaningful? 2) can it be done? I believe it's meaningful because in my view digital hardware design can be regarded as just another specialized software engineering discipline. Of course, things have to be learned, but it's not more difficult than other application domains. I should add that this is not the mainstream view of the hardware design community :-) I also believe that MyHDL convincingly shows that it can be done: in other words, that it has all features of a true HDL. Technically, the principal idea is the use Python generators to model concurrency. Actually, I have also tried hard to make it a *better* HDL, and I believe it is :-) Regards, Jan -- Jan Decaluwe - Resources bvba - http://www.jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium From Python to silicon: http://myhdl.jandecaluwe.com -- http://mail.python.org/mailman/listinfo/python-list
Component framework
Hi all, some time ago I've seen an interesting component framework for Python but I don't remember the name. I remember only one example. There were two components: Wheel and Car, Wheel were then inserted four times into Car and so on. This framework has had lazy instantiation of child components. Does anybody know the name of this framework? Thanks, Honza -- http://mail.python.org/mailman/listinfo/python-list
Re: Read a file with open command
Hi,
simply use file_obj = open ("D:\My documents\File.ods",'rb') for
opening file in binary access mode, which is required for binary files
on MS Windows.
Honza
jean-jeanot wrote:
> I can access to a file with the command:
> file_obj = open ( " D:\My documents\Textfile.txt",'r')
>
> When I now try to read a file with the following command:
>
> file_obj = open ("D:\My documents\File.ods",'r') it doesn't function.
> The extension ods is coming from OpenOffice.org Calc.
>
> Why ?
>
> jean-jeanot
--
http://mail.python.org/mailman/listinfo/python-list
Newbie: trying to twist my head around twisted (and python)
Hoi all,
Please see below a small piece of python code that resembles a
smtpserver using the twisted framework. The code is based on the example
smtp server discussed in Twisted Network Programming Essentials.
The unmodified example code can be found on the O'Reilly website:
(http://examples.oreilly.com/twistedadn/, in ch08 subdir).
I've removed all the code I don't (the original example write an email
received with SMTP to a Maildir; I'll do something else with it). For
the sake of the example, the only thing I'll do in eomReceived is print
whether the message had any attachments or not, then return a "failed"
if a message had any attachments and a "success" if not.
According to the book, I need to return a "Deferred result" from the
function eomReceived (see below).
In eomReceived, I intend to process the email then either return success
or failure. I've been looking at the twisted way of using twisted :-).
According to the book "its a little confusing for a start" and I have to
agree :-)
Does anyone know how I need to complete the code below so it returns
this mysterious "Deferred result" and runs?
Many thanks in advance,
Jan
#!/usr/bin/python
from twisted.mail import smtp, maildir
from zope.interface import implements
from twisted.internet import protocol, reactor, defer
import os
from email.Header import Header
from email import message_from_string
class MessageHandler(object):
implements(smtp.IMessage)
def __init__(self, userDir):
self.lines = []
#end __init__
def lineReceived(self, line):
self.lines.append(line)
#end lineReceived
def eomReceived(self):
# message is complete, store it
self.lines.append('') # add a trailing newline
messageData = '\n'.join(self.lines)
emailMessage = message_from_string (messageData)
# return a Deferred result so the client knows whether the
# message has been successfully processed
if emailMessage.is_multipart():
print "email has attachments"
return ?? failed ???
else:
print "email has no attachments"
return ?? success ???
#end eomReceived
def connectionLost(self):
print "Connection lost unexpectedly!"
# unexpected loss of connection; don't save
del(self.lines)
del(self.email)
#end connectionLost
#end MessageHandler
class LocalDelivery(object):
implements(smtp.IMessageDelivery)
def __init__(self):
pass
#end __init__
def receivedHeader(self, helo, origin, recipients):
myHostname, clientIP = helo
headerValue = "by %s from %s with ESMTP ; %s" % (myHostname,
clientIP, smtp.rfc822date())
# email.Header.Header used for automatic wrapping of long lines
return "Received: %s" % Header(headerValue)
#end receivedHeader
def validateFrom(self, helo, originAddress):
# accept mail from anywhere. To reject an address, raise
# smtp.SMTPBadSender here.
return originAddress
#end validateFrom
def validateTo(self, user):
print "Accepting mail for %s" % user.dest
return lambda: MessageHandler()
#end validateTo
#end LocalDelivery
class SMTPFactory(protocol.ServerFactory):
def __init__(self):
pass
#end __init__
def buildProtocol(self, addr):
delivery = LocalDelivery()
smtpProtocol = smtp.SMTP(delivery)
smtpProtocol.factory = self
return smtpProtocol
#end buildProtocol
#end SMTPFactory
if __name__ == "__main__":
import sys
reactor.listenTCP(10025, SMTPFactory())
from twisted.internet import ssl
# SSL stuff here... and certificates...
reactor.run()
--
http://mail.python.org/mailman/listinfo/python-list
