ANN: SQLObject 0.7.1rc1
Hello! I'm pleased to announce the 0.7.1rc1 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.1rc1 News and changes: http://sqlobject.org/docs/News.html What's New == Features Interface * Added support for psycopg2 and MSSQL. * Added TimeCol. * Implemented RLIKE (regular expression LIKE). Small Features -- * Select over RelatedJoin. * SQLite foreign keys. * Postgres DB URIs with a non-default path to unix socket. * Allow the use of foreign keys in selects. * Implemented addColumn() for SQLite. * With PySQLite2 use encode()/decode() from PySQLite1 for BLOBCol if available; else use base64. Bug Fixes - * Fixed a longstanding problem with UnicodeCol - at last you can use unicode strings in .select() and .selectBy() queries. There are some limitations, though. * Cull patch (clear cache). * .destroySelf() inside a transaction. * Synchronize main connection cache during transaction commit. * Ordering joins with NULLs. * Fixed bugs with plain/non-plain setters. * Lots of other bug fixes. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: Leo 4.4.1.1 final released
Leo 4.4.1.1 final is available at: http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106 Leo 4.4.1.1 corrects a last-minute unicode bug in Leo 4.4.1. This version also adds the new slideshow plugin. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.1: - Leo outputs decorators correctly, provided that the decorator is not a Leo directive. - A new colorizer plugin controlled by jEdit language description files. - A new shadow files plugin that allows derived files not to have sentinel lines. - Multiple editors in Leo's body pane. - Search commands now support regex replace patterns: \1, \2, etc. - Support for external debuggers: see http://webpages.charter.net/edreamleo/debuggers.html - The scripting plugin now creates a Debug Script button. - Several new commands including run-unit-test, python-help, toggle-invisibles, and scroll-outline-left/right. - The help-for-command commands now contains information for almost all commands. - A new shortcut_button plugin. Quote of the month: --- Thanks for creating the most useful and amazing application that I've come across in years. I use Leo every day. Links: -- 4.4.1:http://webpages.charter.net/edreamleo/new-4-4-1.html 4.4: http://webpages.charter.net/edreamleo/new-4-4.html Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: how do you get the name of a dictionary?
Dennis Lee Bieber wrote: id() returns, in C based Python, the memory address at which an object is stored. That is all... Names in Python are mapped to the object -- essentially they are mapped to the address of the object. There is NO intermediate hidden identifier. [snip] Object 1 has two names bound to it. But the only way to find out what those names are requires first having some other reference bound to the object, and then asking each name if the id() (the address) matches the id() of the reference in question. Ahh! I see. That makes sense. Thanks for taking the time to explain it to a noob. :) Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes listing dll functions
[EMAIL PROTECTED] wrote: hi all and before I start I apologise if I have this completely muddled up but here goes. I'm trying to call functions from a dll file in a python script but I can't work out what functions are available. I'm using ctypes. I've tried using dir(ctypes_object) but the resultant output looks like a list of standard functions and not the ones I'm looking for. As far as I know, there is no way with ctypes to enumerate the functions exported by a DLL. If you have Visual C++, you can use link.exe to do this: link /dump /exports x.dll Also how can I tell if the dll was written in C or C++ as I understand C++ dlls can't be used. Well, DLLs that use C++ features cannot be used. If the exported names are decorated, then they can't be used. I have a header file that starts; #ifndef __DIRAC__ #define __DIRAC__ // Prototypes const char *DiracVersion(void); void *DiracCreate(long lambda, long quality, long numChannels, float sampleRate, long (*readFromChannelsCallback)(float **data, long numFrames, void *userData)); void *DiracCreate(long lambda, long quality, long numChannels, float sampleRate, long (*readFromChannelsCallback)(float *data, long numFrames, void *userData)); That's called function overloading: two functions with the same name but slightly different parameters. That is only available with C++, so I'm afraid you are out of luck. You may be able to use SWIG to generate an interface for this; I've had good luck with SWIG. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: best split tokens?
It depends on the language as it was suggested, and it also depends on how a token is defined. Can it have dashes, underscores, numbers and stuff? This will also determine what the whitespace will be. Then the two main methods of doing the splitting is to either cut based on whitespace (specify whitespace explicitly) or pick out only valid token symbols uninterrupted by any whitespace (specify valid symbols explicitly). Nick V. Tim Chase wrote: rgx = re.compile('\W+') if you don't mind numbers included you text (in the event you have things like fatal1ty, thing2, or pdf2txt) which is often the case...they should be considered part of the word. If that's a problem, you should be able to use rgx = re.compile('[^a-zA-Z]+') This is a bit Euro-centric... I'd call it half-asscii :-) groan... :) Given the link you provided, I correct my statement to Ango-centric, as there are clearly oddball cases in languages such as French. textbox = He was wont to be alarmed/amused by answers that won't work Well, one could do something like s He was wont to be alarmed/amused by answers that won't work s2 The two-faced liar--a real joker--can't tell the truth r = re.compile((?:(?:[a-zA-Z][-'][a-zA-Z])|[a-zA-Z])+) r.findall(s), r.findall(s2) (['He', 'was', 'wont', 'to', 'be', 'alarmed', 'amused', 'by', 'answers', 'that', won't, 'work'], ['The', 'two-faced', 'liar', 'a', 'real', 'joker', can't, 'tell', 'the', 'truth']) which parses your example the way I would want it to be parsed, and handles the strange string I came up with to try similar examples the way I would expect that it would be broken down by words... I had a hard time comin' up with any words I'd want to call words where the additional non-word glyph (apostrophe, dash, etc) wasn't 'round the middle of the word. :) Any more crazy examples? :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Get CPU usage of a single process in Windows
Tor Erik [EMAIL PROTECTED] wrote: This should be possible as Taskmanager tracks CPU usage for every process... Anyone know how this can be done? I answered this in the python-win32 mailing list. Task manager and perfmon do this by using the performance counter APIs. Python-Win32 includes an interface for that (import win32pdh), but I've never used it. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLwaterheadretard3 (Was: Is it just me, or is Sqlite3 goofy?)
Paul McNett wrote: [EMAIL PROTECTED] wrote: Do you know what INNER JOIN means? Do you know how important it is to a relational database? Can you explain how an INNER JOIN can even work, in theory, with dynamic data types? Let's stop the pissing contest and just see how it works. After all, this is Python and we can easily just try it out. Here's my example. Please tell me how this causes unexpected results, When we use a best case scenario, we get what we expect. and why it isn't SQL. It isn't SQL simply because SQL won't let you insert text into a numeric field. Please modify my example to get it to cause a catastrophe, Make it worse case? Sure, I can do that. and post it here so we can see the errors of our ways and be properly humbled. #-- Preliminaries: ## from pysqlite2 import dbapi2 as sqlite import sqlite3 as sqlite ## con = sqlite.connect(test.db) con = sqlite.connect(:memory:) cur = con.cursor() #-- Create 3 tables for a M:M relationship between customers #-- and categories: cur.execute(create table customers (id integer primary key autoincrement, name char)) cur.execute(create table categories (id integer primary key autoincrement, name char)) cur.execute(create table cust_cat (id integer primary key autoincrement, cust_id integer, cat_id integer)) ##cur.execute(create table cust_cat (id integer, cust_id, cat_id)) ##cur.execute(create table customers (id, name char)) ##cur.execute(create table categories (id, name char)) ## ### Ok, THIS fails. Because the JOINs were originally made against fields ### that were cast as integers so the 'hinting' of sqlite must operate in a JOIN ### allowing ints to JOIN against strings. Take away the casts and the JOIN ### fails. Unfortunately, not every situation will involve JOINing primary keys. ## ##[(1, u'Ziggy Marley'), (2, u'David Bowie')] ##[(1, u'Glam Rock'), (2, u'Nuevo Reggae'), (3, u'Male Singers')] ##[(None, 1, 3), (None, 1, u'2'), (None, u'2', u'1'), (None, u'2', u'3')] ## ##[(1, u'Ziggy Marley', 3, u'Male Singers')] ##[] ##[] ##[] ##[] ##[(1, u'Ziggy Marley', 3, u'Male Singers')] #-- Insert some test data into customer and categories: cur.execute(insert into customers (name) values ('Ziggy Marley')) cur.execute(insert into customers (name) values ('David Bowie')) cur.execute(insert into categories (name) values ('Glam Rock')) cur.execute(insert into categories (name) values ('Nuevo Reggae')) cur.execute(insert into categories (name) values ('Male Singers')) ## # if int cast removed, manually insert ids ##cur.execute(insert into customers (id, name) values (1,'Ziggy Marley')) ##cur.execute(insert into customers (id, name) values (2,'David Bowie')) ##cur.execute(insert into categories (id, name) values (1,'Glam Rock')) ##cur.execute(insert into categories (id, name) values (2,'Nuevo Reggae')) ##cur.execute(insert into categories (id, name) values (3,'Male Singers')) cur.execute(select * from customers) #-- Take a look at the data (and retrieve the pk's): print cur.fetchall() #[(1, u'Ziggy Marley'), (2, u'David Bowie')] cur.execute(select * from categories) print cur.fetchall() #[(1, u'Glam Rock'), (2, u'Nuevo Reggae'), (3, u'Male Singers')] #-- Relate some customers to some categories. Note how I send strings #-- in some places and ints in others: ##cur.execute(insert into cust_cat (cust_id, cat_id) values (1, 3)) ##cur.execute(insert into cust_cat (cust_id, cat_id) values (1, '2')) ##cur.execute(insert into cust_cat (cust_id, cat_id) values ('2', '1')) ##cur.execute(insert into cust_cat (cust_id, cat_id) values ('2', 3)) ##cc = [(1,3),(1,'2'),('2','1'),('2','3')] cc = [(1,3),(1,'2'),('2','1'),('2','3')] ### And this also fails (differently). The 'hinting' of sqlite that operates ### during a JOIN only works if the string looks like an integer. And, no, ### the use of the '' is not a contrived example like 'fred'. I often get a ### result like '200' in what is supposed to be a numeric field. ## ##[(1, u'Ziggy Marley'), (2, u'David Bowie')] ##[(1, u'Glam Rock'), (2, u'Nuevo Reggae'), (3, u'Male Singers')] ##[(1, 1, 3), (2, 1, u'2'), (3, u'2', u'1'), (4, u'2', u'3')] ## ##[(1, u'Ziggy Marley', 3, u'Male Singers')] ##[] ##[] ##[] ##[(1, u'Ziggy Marley', 3, u'Male Singers')] ##[(1, u'Ziggy Marley', 3, u'Male Singers')] cur.executemany(insert into cust_cat (cust_id, cat_id) values (?,?),cc) cur.execute(select * from cust_cat) print cur.fetchall() print #-- Run some queries: cur.execute( select customers.id as cust_id, customers.name as cust_name, categories.id as cat_id, categories.name as cat_name from customers inner join cust_cat on cust_cat.cust_id = customers.id inner join categories on categories.id = cust_cat.cat_id order by 2,4) print cur.fetchall() #[(2, u'David Bowie', 1, u'Glam Rock'), # (2, u'David Bowie', 3, u'Male
Re: Using Beautiful Soup to entangle bookmarks.html
Hallo George, thanks a lot! This is exactly the direction I had in mind. Your script demonstrates nicely how Beautiful Soup works. Regards, Martin. George Sakkis wrote: Francach wrote: Hi George, Firefox lets you group the bookmarks along with other information into directories and sub-directories. Firefox uses header tags for this purpose. I'd like to get this grouping information out aswell. Regards, Martin. Here's what I came up with: http://rafb.net/paste/results/G91EAo70.html. Tested only on my bookmarks; see if it works for you. For each subfolder there is a recursive call that walks the respective subtree, so it's probably not the most efficient solution, but I couldn't think of any one-pass way to do it using BeautifulSoup. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
James Stroud a écrit : [EMAIL PROTECTED] wrote: Hello I am looking for python code that takes as input a list of strings (most similar, but not necessarily, and rather short: say not longer than 50 chars) and that computes and outputs the python regular expression that matches these string values (not necessarily strictly, perhaps the code is able to determine patterns, i.e. families of strings...). Thanks for any idea I'm not sure your application, but Genomicists and Proteomicists have found that Hidden Markov Models can be very powerful for developing pattern models. Perhaps have a look at Biological Sequence Analysis by Durbin et al. Also, a very cool regex based algorithm was developed at IBM: http://cbcsrv.watson.ibm.com/Tspd.html Indeed, this seems cool! Thanks for the suggestion I have tried their online Text-symbol Pattern Discovery with these input values: cpkg-3 cpkg-31008 cpkg-3000A cpkg-30006 nsug-300AB nsug-300A2 cpdg-30001 nsug-300A3 But I think HMMs are the way to go. Check out HMMER at WUSTL by Sean Eddy and colleagues: http://hmmer.janelia.org/ http://selab.janelia.org/people/eddys/ I will look at that more precisely, but at my first look it seems this is more specialized and less accessible for the common mortal... James Thanks. This may help me. In addition I continue to look for other ideas, notably because I want code that I can change myself, and exclusively python code -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it just me, or is Sqlite3 goofy?
[EMAIL PROTECTED] wrote: I wouldn't be at all surprised if the pysqlite author operated under that assumption. That the Python developers didn't pick up on the issue is not surprising. I'm not sure how many of them are (py)sqlite users, probably relatively few. Skip Who has reviewed sqlite/pysqlite after all? Reading the passage in the sqlite FAQ I can hardly believe that passing errors silently and coercing everything to string when it fails to be coerced to INTEGER although INTEGER was an invariant declared in the create command is on par with Pythons design philosophy. In other cases doctoral dissertations are written about whether a keyword or some punctuation shall be used for decorator syntax and in this case everything must be rushed into the code base of the standard library? -- http://mail.python.org/mailman/listinfo/python-list
Re: Minidom XML output - attributes in wrong order ?
Peter Møllerud wrote: I'm very new to Python then you might want to consider using ElementTree or lxml, not necessarily minidom. c = doc.createElement(sometest) doc.appendChild(c) tmp = doc.createElement(info) tmp.setAttribute(vehicle, car) tmp.setAttribute(x-ray , 100-1) tmp.setAttribute(age, 30) c.appendChild(tmp) print doc.toprettyxml(indent= ) What it then prints out is : ?xml version=1.0 ? sometest info age=30 vehicle=car x-ray =100-1/ /sometest What I expected was : info vehicle=car x-ray=100-1 age=30/ Attributes in XML are not ordered and no XML library will keep the order. All you could do is serialise by hand, which is not that difficult either. Is there any reason why you might want to keep the order? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python Based Web Application
The most modest way is to use pure Python and interface via CGI with the web. I would start there. As you code you will find yourself saying I wonder if a framework is out there that already has automated this specific process (say templating)?, well then you can search and find such a framework. If you pick a framework you are not familiar with right from the start then besides your original problem that you want o solve, you have another problem -- that of learning a new framework. You will end up molding your problem to some framework (this is not necessarily a very bad thing) rather than finding a framework that helps you solve the problem. --Nick V. John Henry wrote: Hi folks. I am interested on this topic as well. If my application is not database related, what would be a good choice? I have clients that wish to use my Python applications but I am not willing to give them the code. So, I am thinking about setting it up as a web based application and let them run it from their browser. If things go well, may be I can charge them for usage later. The application will involve getting a data file from the user, do some processing, and return a result file to the user. Very modest - to start. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
[EMAIL PROTECTED] wrote: snip Thanks for that, Carl. I think that using the loop is probably what I'll end up doing. I had no idea that the listcomp thing would be quite a complicated as it is appearing. I had it in my mind that I was missing some obvious thing which would create a simple solution :) Mind you, there are some interesting bits and pieces of code in this thread! List (and generator) comprehensions are not as bad as all that, although it took me a little while to figure them out too. ;-) They are basically normal for loops with optional if statements: res = [expression1 for var in some_iter if expression2] is just like: res = [] for var in some_iter: if expression2: res.append(expression1) More complex comprehensions can be broken down the same way (like Rob Williscroft did for his fourth attempt): res = [i for i, x in enumerate(seq) for _ in xrange(x)] becomes: res = [] for i, x in enumerate(seq): for _ in xrange(x): res.append(i) Doing this can help you puzzle out variables and if statements in complex list comps, as the following, admittedly contrived, examples indicate: R = range(10) res = [] for n in R: if n % 2: for m in range(n): res.append(m) print res == [m for n in R if n % 2 for m in range(n)] res2 = [] for n in R: for m in range(n): if n % 2: res2.append(m) print res2 == [m for n in R for m in range(n) if n % 2] res3 = [] for n in R: for m in range(n): if m % 2: res3.append(m) print res3 == [m for n in R for m in range(n) if m % 2] # The above prints True three times. Of course, if your loops get much more complicated than this you should probably spell them out anyway. HTH, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Map with an extra parameter
ml1n wrote: [EMAIL PROTECTED] wrote: This may be what you need: class foo: def __init__(self, a, b): self.a = a self.b = b vars = [1,2,3,4,5,6] objects = [foo(a, 1) for a in vars] Note that in Python the new is expressed wit the () at the end: f = new foo() Bye, bearophile (Not sure if this group likes top or bottom posts, sorry) Thanks for the reply, In the interests of speed my thinking was that using map would move the loop out of Python and into C, is that the case when using list comprehension? I'd always thought it was just syntatic short hand for a Python loop. M. Your thinking is correct. :-) Check out http://groups.google.ca/group/comp.lang.python/msg/7a56cf1a052b9c5d wherein Fredrik Lundh shows the difference by bytecode disassembly. Peace, ~Simon P.S. Bottom posts. -- http://mail.python.org/mailman/listinfo/python-list
Re: best split tokens?
Tim Chase wrote: I had a hard time comin' up with any words I'd want to call words where the additional non-word glyph (apostrophe, dash, etc) wasn't 'round the middle of the word. :) Any more crazy examples? :) 'ey, 'alf a mo, wot about when 'enry 'n' 'orace drop their aitches? -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
Diez B. Roggisch wrote: [EMAIL PROTECTED] schrieb: Hello I am looking for python code that takes as input a list of strings (most similar, but not necessarily, and rather short: say not longer than 50 chars) and that computes and outputs the python regular expression that matches these string values (not necessarily strictly, perhaps the code is able to determine patterns, i.e. families of strings...). For matching the exact set, of course a concatenation can be used. However, this is of limited use, because then simple string find will suffice. In general, this can't be done. It might be possible that the underlying structure of the language isn't regular at all - for example, the simple language of palindromes isn't. And even if it was - the search space is just to large to explore. You could generate a bazillion matching expressions, but .* will always match - so how do you prevent the generator from converging towards that? If all you have are those strings, you are better off trying to infer some structure yourself. Diez Here is how regular expressions raise confusion. One starts with a relatively simple matching problem and before long finds oneself in a search space too large to explore, having to formulate the right expression out of a bazillion permutations with a syntax replete with potential traps: backslashes, special characters, precedence order, etc. The fact emerges (once more) that a regular expression does not spare the effort of acquiring a crystal clear conception of what needs to be done as an absolute prerequisite of writing code that in the end can be relied upon to do what it is supposed to do. In order to acquire that crystal clear conception a space too large to explore is hardly a working environment one should be eager to get into. Yet regular expressions seem to exert a strange attraction and are often sought for problems that don't really require them. I suspect this is because the regular expression parsers are made by highly qualified experts and so they may recommend themselves to the programmer with a less than perfect understanding of a task as a sort of magic bullet that does it right all by itself. Regex eding as a substitute for problem analysis so to speak ... Most OPs are rather sketchy and leave it up to their readers to guess purpose, requirements, incidentals, environmentals, restrictions, etc. Accordingly, threads often veer off topic very quickly into lofty realms of academic interest, the OP never to be heard from again. So I would suggest that the OP explain what he intends to do with his regular expression. A lot depends on it. In the interim I'd like to resize the search space to a manageable dimension with the proven hypothesis that the number of useless permutations of the kind being discussed is a bazillion minus one, because, fortunately, there is only one that makes sense. It follows these two rules: 1. First come first serve. And 2. Of two contending targets the longer prevails. That is not to say other rules never make sense. It is to say that in ninety-nine percent of the cases this rule applies and that the other one percent can also be understood in terms of these two rules plus exception rules. Chapter 3.1. from the SE doc visualizes the point by replacing a set of overlapping targets with their upper-cased selves: overlapping_targets = 'be=BE being=BEING been=BEEN bee=BEE belong=BELONG long=LONG longer=LONGER' high_strung_bee_story = There was a bee belonging to hive nine longing to be a beetle and thinking that being a bee was okay, but she had been a bee long enough and wouldn't be one much longer. SE.SE (overlapping_targets)(high_strung_bee_story) There was a BEE BELONGing to hive nine LONGing to BE a BEEtle and thinking that BEING a BEE was okay, but she had BEEN a BEE LONG enough and wouldn't BE one much LONGER. The matches appear correct, though BELONGing, LONGing and BEEtle exemplify unintended matches. These could be avoided by refinement of the target set. The partially successful result points out the direction the refinement has to take. Precedence being unrelated to the order of the definitions, editing the set is carefree in that it does not impose precedence considerations. The benefit in terms of modularity is substantial, as module sets can be combined. Doing the example with a regular expression: r = re.compile ('be|being|been|bee|belong|long|longer') r.findall (high_strung_bee_story) ['be', 'be', 'long', 'long', 'be', 'be', 'be', 'be', 'be', 'be', 'long', 'be', 'long'] The regular expression also applies rule one: first come first serve, but applies a different rule two, defining precedence in the order in which the targets line up in the expression, left to right. In order to implement the SE rule of sensibility, the patterns should be lined up reverse-sorted, which places the longer ones to the left. r = re.compile
Re: pyserial problem: script stops reading
Frederic Wenzel [EMAIL PROTECTED] wrote: | I wrote a script on Linux that uses pyserial to read status messages | from a serial line using readlines(). For now, it just displays what | it gets on stdout: | | 17:42 | 0005 | 02 | | 5 |Rack Abs.| - | --210 | 17:42 | 0008 | 02 | | 5 |Rack Abs.| - | --210 | 17:42 | 0001 | 02 | | 5 |Rack Abs.| - | --210 | 17:43 | 0008 | 02 | | 5 |Rack Abs.| - | --210 | 17:43 | 0001 | 02 | | 5 |Rack Abs.| - | --210 | 17:43 | 0005 | 02 | | 5 |Rack Abs.| - | --210 | 17 | | After a few hours, or sometimes days, of listening, the script stops | in the middle of the line and does not display any further output (as | you can see with the 17 in the last line above). That happens, even | though I set a timeout of 10s when opening the line, and on timeout it | displays the lines and reopens the port: | | ser = serial.Serial(port=1, | baudrate=1200, | rtscts=1, if this is enabling hardware flow control try turning it off - at 1200 baud you should not need it | timeout=10) | | while 1: | lines = sh.readLines() | for line in lines: | print line | ser.close() | ser.open() | | If the script does not time out there, I am not sure what else it is | doing. It seems to be in a wait state it does not get out of. Sounds more and more like flow control hassle - can you lay your hands on a break out box or a datascope? | | So even if the line received turned out to have some sort of error, I | think it should time out after a while? Maybe there is some sort of | buffer overrunning (even though the traffic is quite low: a line every | few minutes on average)? | | Does anyone see any obvious error? Any hint how I can further debug the problem? | | Thanks | Fred - HTH Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter listbox:get
[EMAIL PROTECTED] wrote in email: | Hi,and sorry I forget tell you what I want exactly. | | My problem is | | example: | | when I write like you tell me: | | idx=lb.curselection() | StringValue=lb.get(idx) === This | | THEN,ERROR IS: | | Traceback (most recent call last): | File pyshell#18, line 1, in -toplevel- | StringValue=b.get(idx) == is not the same as this | File C:\Python24\lib\lib-tk\Tkinter.py, line 2432, in get | return self.tk.call(self._w, 'get', first) | TclError: bad listbox index : must be active, anchor, end, @x,y, or a | number | | ...which index I must write to listbox get just clicked row. | | | THANKS | Just use the print statement to see what is going on - use : print idx after getting the idx with the curselection - it must be the number of the row that was clicked - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Unable to make python work properly
In [EMAIL PROTECTED], Benjamin Grant wrote: Hi all, I'd greatly appreciate any help. I can configure, make and install everything fine. I'm using python 2.4 I have ubuntu dapper drake. I am trying to install hplip which requires python. When I do this, this also works but while running the following error occurs: Traceback (most recent call last): File /usr/local/bin/hp-setup, line 31, in ? import readline, gzip ImportError: No module named readline `hplip` is available as package in the Ubuntu repositories. Why do you install it from sources? It appears as though for some reaosn the readline module is not being installed on my system. It's a dependency of the Python packages. That's odd. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: ubuntu crash
Jay wrote: Here are some commands to try: apt-get install ubuntu-standard apt-get install ubuntu-desktop Also, I'd recommend trying Ubuntu's official forums website. I've found their community to be extremely helpful. http://www.ubuntuforums.org/ Plus, why on earth would you want to ax Python? Because you trust the experts on c.l.py? http://mail.python.org/pipermail/python-list/2006-September/360376.html Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode / cx_Oracle problem
Richard Schulman schrieb: Sorry to be back at the goodly well so soon, but... ...when I execute the following -- variable mean_eng_txt being utf-16LE and its datatype nvarchar2(79) in Oracle: cursor.execute(INSERT INTO mean (mean_id,mean_eng_txt) VALUES (:id,:mean),id=id,mean=mean) I not surprisingly get this error message: cx_Oracle.NotSupportedError: Variable_TypeByValue(): unhandled data type unicode But when I try putting a codecs.BOM_UTF16_LE in various plausible places, I just end up generating different errors. Show us the alleged plausible places, and the different errors. Otherwise it's crystal ball time again. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Map with an extra parameter
ml1n wrote: I'm not really sure how to explain this so maybe some example code is best. This code makes a list of objects by taking a list of ints and combining them with a constant: class foo: def __init__(self): self.a = 0 self.b = 0 def func(a,b): f = new foo() f.a = a f.b = b return f constants = [1]*6 vars = [1,2,3,4,5,6] objects = map(func,vars,constants) In the real world I need to do this as quick as possible (without resorting to c) and there are several constants. (The constant is only constant to each list so I can't make it a default argument to func.) My question is, can anyone think of a way to do this efficiently without having to use the `dummy` list of constants and would it be quicker? Here are two more ways to achieve what you want, but you have to time them youself. from itertools import starmap, izip, repeat class Foo: ... def __init__(self, a, b): ... self.a = a ... self.b = b ... def __repr__(self): ... return Foo(a=%r, b=%r) % (self.a, self.b) ... constants = repeat(1) vars = [1, 2, 3] list(starmap(Foo, izip(vars, constants))) [Foo(a=1, b=1), Foo(a=2, b=1), Foo(a=3, b=1)] This requires Python 2.5: from functools import partial map(partial(Foo, b=1), vars) [Foo(a=1, b=1), Foo(a=2, b=1), Foo(a=3, b=1)] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it just me, or is Sqlite3 goofy?
Kay Schluehr wrote: [Quoting Marc 'BlackJack' Rintsch...] If you are so fond of static typing, why are you using Python in the first place? Just see it as consistency -- dynamically typed language → dynamically typed DB columns. ;-) I have to admit I find this bogus too. It has by no means anything to do with static typing but letting errors pass silently i.e. deactivating runtime type checks as well. If the questioner had been talking about Perl, most respondents would rightly have said that Perl's silent coercion or conversion of values is an irritating source of potential errors. Here, the behaviour of SQLite, whilst not as bad as Perl - values are not converted into something different which is then erroneous - does contradict the naive expectations of users who expect the data type declarations to mean something and for such constraints to be enforced. Of course, the criticism of the questioner should be more forgiving in this debate, since I imagine that most people with experience of SQLite know of its loose data typing model, and that many assume that everyone else is aware of this feature or limitation, even though that may not be the case. Thus, the priority should be on emphasizing this in the module documentation (in order to avoid unnecessary confusion), along with mentioning other possible strategies for emulating other database system behaviours: Other Affinity Modes in the SQLite documentation [1] may be helpful here, if the future tense can be replaced with the present tense whilst preserving the factual content of that section. Paul [1] http://www.sqlite.org/datatype3.html -- http://mail.python.org/mailman/listinfo/python-list
search and replace in a file :: newbie help
hi... i m now updating an sql file old file contains lines insert into mobilebill values ('Apr 01, 03', 'OUT', '91804103253', 34, 3.2); insert into mobilebill values ('Apr 01, 03', 'OUT', '91806392475', 84, 5.2); insert into mobilebill values ('Apr 01, 03', 'OUT', '918317048193', 76, 7.6); i want to replace Apr 01,03 with 2003-01-03 etc... and my script is import re lines=open('mb.sql').readlines() #mb.sql contains the above lines months={} months['Jan']='01';months['Feb']='02';months['Mar']='03';months['Apr']='04' months['May']='05';months['Jun']='06';months['Jul']='07';months['Aug']='08' months['Sep']='09';months['Oct']='10';months['Nov']='11';months['Dec']='12' for line in lines: #print line inp=line cre2=re.search('.*(\w{3}\s+\d+\,\s+\d+).*',line) (month,day,year)=cre2.group(1).split(); cre3=re.compile(',') day=cre3.sub(,day) year='20'+year repstr=year+'-'+months[month]+'-'+day cre4=re.compile('.*(\w{3}\s+\d+\,\s+\d+).*') line=cre4.sub(repstr,line) print line = but the output is just 2003-01-04 and not insert into mobilebill values ('2003-01-04', 'OUT', '91804103253', 34, 3.2); help me in this regard, what did i do wrong... thanks and regards gowthaman B -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python Based Web Application
James Stroud wrote: Hello All, I am interested in setting up a modest invoicing system for some consulting I am doing. I like the idea of managing this on the web and creating invoices and printing them from a browser. However, I'm not really sure where to start. I've played with some CMS applications, but they seem more for blogging (mamba, wordpress, etc.). Ideally, I would like to interface with mySQL (or whatever the favorite web-flavor database app is these days). I would like to be able to use my python skills. I confident that if I set out to write this from scatch, I will be seriously re-inventing the wheel, perhaps several times over. So, my question is, does anyone know of a book and/or some kind of framework that would make the best sense for what I am describing here? I've heard of Zope, but I would like to make sure its appropriate for the job before I spend 2 or 3 days getting acquainted with it. I'm adept at HTML, python, CSS, python-CGI, and interfacing with mySQL through DBI. I'm sure I could get something to work with these skills, but I want to minimize wheel re-invention as much as possible. Basically, I want a jump start on data-base oriented web development with a focus on applying my python skills. Any suggestions will be greatly appreciated. James Once you solve the web data maintenance part (which I do using wxPython on the desktop) you might be interested in my Python db-to-pdf invoice generator, which I've been using now for several years. If so, drop me a line and I'll send you a copy. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLwaterheadretard3 (Was: Is it just me, or is Sqlite3 goofy?)
[EMAIL PROTECTED] wrote: Paul McNett wrote: [EMAIL PROTECTED] wrote: Do you know what INNER JOIN means? Do you know how important it is to a relational database? Can you explain how an INNER JOIN can even work, in theory, with dynamic data types? Let's stop the pissing contest and just see how it works. After all, this is Python and we can easily just try it out. Here's my example. Please tell me how this causes unexpected results, When we use a best case scenario, we get what we expect. and why it isn't SQL. It isn't SQL simply because SQL won't let you insert text into a numeric field. Yup, I have to agree that's pretty crappy. (Makes mental note to limit use of SQLite). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
[EMAIL PROTECTED] wrote: [...] Cool ... and damn but you guys are fast with the answers. This appears to work find, but in a quick and dirty test it appears that the [list] version takes about 2x as long to run as the original loop. Is this normal? No hard and fast information, but as a general rue of thumb replacing calls to a c function like list.extend() with iteration inside a list comprehension is very likely to be slower. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
[EMAIL PROTECTED] wrote: Carl Banks wrote: [EMAIL PROTECTED] wrote: Paul Rubin wrote: [EMAIL PROTECTED] writes: print sum( ([i]*n for i,n in enumerate(seq)), []) Wow, I had no idea you could do that. After all the discussion about summing strings, I'm astonished. Me too ... despite what bearophile said, this is faster than the 2nd example. Nearly as fast as the original loop :) See if it's still faster if the original sequence is length 1000. (Hint: it won't be.) Adding lists with sum has the same performance drawback that adding strings does, so it should be avoided. sum is for adding numbers; please stick to using it that way. FWIW, the original loop looked perfectly fine and readable and I'd suggest going with that over these hacked-up listcomp solutions. Don't use a listcomp just for the sake of using a listcomp. Thanks for that, Carl. I think that using the loop is probably what I'll end up doing. I had no idea that the listcomp thing would be quite a complicated as it is appearing. I had it in my mind that I was missing some obvious thing which would create a simple solution :) Your original solution was the simplest, in that it's easy to understand and maintain. Mind you, there are some interesting bits and pieces of code in this thread! Right. But Python in general is designed to encourage straightforward expression of straightforward ideas, while retaining the ability to solve complex problems in innovative ways. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: search and replace in a file :: newbie help
techie2go wrote: i m now updating an sql file = but the output is just 2003-01-04 and not insert into mobilebill values ('2003-01-04', 'OUT', '91804103253', 34, 3.2); help me in this regard, what did i do wrong... You can find out yourself if you throw in some print statements: for line in lines: #print line inp=line cre2=re.search('.*(\w{3}\s+\d+\,\s+\d+).*',line) (month,day,year)=cre2.group(1).split(); cre3=re.compile(',') day=cre3.sub(,day) year='20'+year repstr=year+'-'+months[month]+'-'+day print X, repstr # OK, so far cre4=re.compile('.*(\w{3}\s+\d+\,\s+\d+).*') print X, cre4.search(line).group(0) # Oops, matches the whole line # so it will be replaced by the # reformatted date line=cre4.sub(repstr,line) print line The minimal fix is to change cre4 cre4=re.compile('(\w{3}\s+\d+\,\s+\d+)') And here is an alternative: import re import sys lines = open('mb.sql') months = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, # ... } r = re.compile(r(\w{3})\s+(\d+)\,\s+(\d+)) def fix_date(match): month, day, year = match.groups() return 20%02s-%02d-%02s % (year, months[month], day) for line in lines: sys.stdout.write(r.sub(fix_date, line)) You might also consider performing the conversion in the database. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
I recommend Scribes. http://scribes.sf.net Flash Demo: http://scribes.sf.net/snippets.htm GIF Demo: http://www.minds.may.ie/~dez/images/blog/scribes.html Omar wrote: I'd love the perfect editor that would be: a) free b) enable me to drag and drop code snippets from a sort of browser into the code c) can run programs right from within d) can edit - PYTHON - Javascript - HTML - actionscript (since I'm also learning flash) e) easy to learn suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Bug in the documentation (?)
Hi, Snake Tamers According to http://www.python.org/doc/2.4.1/lib/typesseq-strings.html (and next releases): The conversion types are: Conversion Meaning Notes [...] x Unsigned hexadecimal (lowercase). (2) X Unsigned hexadecimal (uppercase). (2) But actually: Python 2.4.1 (#1, Apr 10 2005, 22:30:36) [GCC 3.3.5] on linux2 Type help, copyright, credits or license for more information. '%x' % -123456 '-1e240' so it is a _signed_ hexadecimal. However, sometimes it would be convinient to get the unisgned conversion (especially, since id(..) can return a negative value). This way is rather clumsy: '%x' % (id('abcd')+0x1) 'b7b75380' Do you see any better solution? p.o. -- http://mail.python.org/mailman/listinfo/python-list
Re: super and __init__
Jason [EMAIL PROTECTED] wrote: As far as I can tell, the best way to use super() with an __init__ function is to stick to a rigid function signiture. ... Unfortunately, I don't see a way of avoiding this problem with super(). An easy way to avoid changing the method signature is to use a multi-stage construction. So if your class hierarchy uses: def __init__(self, foo, bar): super(ThisClass, self).__init__(foo, bar) ... whatever ... and you are adding another class to the hierarchy, but that needs a 'baz' as well, don't change the signature for __init__, add another method: def set_baz(self, baz): ... Then at the point you construct the objects you can call: x = DerivedClass(foo, bar) x.set_baz(baz) If set_baz isn't called then you either use a default value or throw an error when something depends on it having been set. -- http://mail.python.org/mailman/listinfo/python-list
PIL cannot open TIFF image in Windows
Hello, I have installed PIL 1.1.5 on Windows with Python 2.4. I'm unable to open .tiff images that I can open and view using Windows Explorer. In other words, this simple test fails: import Image im = Image.open('small.tif') with an 'cannot identify image file' error message. I'm able to open .jpg images. Is PIL's support for TIFF images dependent on something else in Windows? -- Andres Corrada-Emmanuel Lecturer in Physics/Physics Department Research Fellow/Computer Science Department University of Massachusetts at Amherst -- -- http://mail.python.org/mailman/listinfo/python-list
[Fwd: Problems with PyGridTableBase]
- Mensaje reenviado De: Mario Lacunza [EMAIL PROTECTED] Para: Lista Python Ing python-list@python.org Asunto: Problems with PyGridTableBase Fecha: Sat, 09 Sep 2006 00:03:20 -0500 Hello, I attach two files:frmClientes and frmClientesNE. frmClientes charge a Grid with resume Costumers data: Name, Commercial ID, address, etc. and edition options. frmClientes in Line 178 def OnBtnNuevoButton(self, event): call to frmClientesNE. Its append a new record to the database and clear all controls and when I close it, the grid in frmClientes: grClte must be recharge with the new data, but that dont work. Only work when a Delete some record. I couldnt send yours a runable .py version, because both of them files pickup data from a Firebird's database. I try to implement the wxPython Demo model: Grid_MegaExample, follow that my class Grilla must be: Line 224: class Grilla(Grid.Grid): but for the Boa Constructors controls creation I couldnt inherit from Grid.Grid, thats my problem, I need your help I try for two days and nothing :-( ... some ideas?? Thanks in advance!! == FILE: FRMCLIENTES.PY == # -*- coding: utf8 -*-# #Boa:Frame:frmClientes __version__='0.5' __autor__='Mario Lacunza Vasquez [EMAIL PROTECTED]' import wx import wx.grid import modGlobals from Conectar import Conectar import errores def create(parent): return frmClientes(parent) [wxID_FRMCLIENTES, wxID_FRMCLIENTESBRNSALIR, wxID_FRMCLIENTESBTNBORRAR, wxID_FRMCLIENTESBTNEDIT, wxID_FRMCLIENTESBTNNUEVO, wxID_FRMCLIENTESGRCLTE, wxID_FRMCLIENTESLBLTITULO, wxID_FRMCLIENTESPANEL1, ] = [wx.NewId() for _init_ctrls in range(8)] class frmClientes(wx.Frame): def _init_coll_fsGrid_Growables(self, parent): # generated method, don't edit parent.AddGrowableRow(0) def _init_coll_fsGrid_Items(self, parent): # generated method, don't edit parent.AddWindow(self.grClte, 0, border=2, flag=wx.EXPAND | wx.ALL) def _init_coll_fsBtn_Items(self, parent): # generated method, don't edit parent.AddWindow(self.btnNuevo, 0, border=2, flag=wx.EXPAND | wx.ALL) parent.AddWindow(self.btnEdit, 0, border=2, flag=wx.EXPAND | wx.ALL) parent.AddWindow(self.btnBorrar, 0, border=2, flag=wx.EXPAND | wx.ALL) parent.AddWindow(self.brnSalir, 0, border=2, flag=wx.EXPAND | wx.ALL) def _init_coll_fsTit_Items(self, parent): # generated method, don't edit parent.AddWindow(self.lblTitulo, 0, border=6, flag=wx.EXPAND) def _init_coll_bsClte_Items(self, parent): # generated method, don't edit parent.AddWindow(self.panel1, 1, border=0, flag=wx.EXPAND) def _init_coll_fsTit_Growables(self, parent): # generated method, don't edit parent.AddGrowableRow(0) def _init_coll_fsClte_Growables(self, parent): # generated method, don't edit parent.AddGrowableRow(0) parent.AddGrowableRow(1) parent.AddGrowableRow(2) parent.AddGrowableCol(0) def _init_coll_fsClte_Items(self, parent): # generated method, don't edit parent.AddSizer(self.fsTit, 1, border=5, flag=wx.ALIGN_CENTER_HORIZONTAL) parent.AddSizer(self.fsGrid, 1, border=10, flag=wx.ALIGN_CENTER_HORIZONTAL) parent.AddSizer(self.fsBtn, 1, border=5, flag=wx.ALIGN_CENTER_HORIZONTAL) def _init_sizers(self): # generated method, don't edit self.bsClte = wx.BoxSizer(orient=wx.VERTICAL) self.fsClte = wx.FlexGridSizer(cols=1, hgap=0, rows=0, vgap=0) self.fsTit = wx.FlexGridSizer(cols=1, hgap=0, rows=0, vgap=0) self.fsGrid = wx.FlexGridSizer(cols=1, hgap=5, rows=0, vgap=5) self.fsBtn = wx.FlexGridSizer(cols=4, hgap=0, rows=0, vgap=0) self._init_coll_bsClte_Items(self.bsClte) self._init_coll_fsClte_Growables(self.fsClte) self._init_coll_fsClte_Items(self.fsClte) self._init_coll_fsTit_Growables(self.fsTit) self._init_coll_fsTit_Items(self.fsTit) self._init_coll_fsGrid_Growables(self.fsGrid) self._init_coll_fsGrid_Items(self.fsGrid) self._init_coll_fsBtn_Items(self.fsBtn) self.SetSizer(self.bsClte) self.panel1.SetSizer(self.fsClte) def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_FRMCLIENTES, name=u'frmClientes', parent=prnt, pos=wx.Point(352, 148), size=wx.Size(589, 514), style=wx.DEFAULT_FRAME_STYLE, title=u'Clientes') self.SetClientSize(wx.Size(589, 514)) self.panel1 = wx.Panel(id=wxID_FRMCLIENTESPANEL1, name='panel1', parent=self, pos=wx.Point(0, 0), size=wx.Size(589, 514), style=wx.TAB_TRAVERSAL) self.lblTitulo =
What algorithm does Python use to evaluate: if substring in string
I would be surprised if it is the naive: m = 0 s1 = me s2 = locate me s1len = len(s1) s2len = len(s2) found = False while m + s1len = s2len: if s1 == s2len[m:m+s1len]: found = True break m += 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python Based Web Application
James Stroud wrote: Hello All, I am interested in setting up a modest invoicing system for some consulting I am doing. I like the idea of managing this on the web and creating invoices and printing them from a browser. However, I'm not really sure where to start. I've played with some CMS applications, but they seem more for blogging (mamba, wordpress, etc.). Ideally, I would like to interface with mySQL (or whatever the favorite web-flavor database app is these days). I would like to be able to use my python skills. I confident that if I set out to write this from scatch, I will be seriously re-inventing the wheel, perhaps several times over. So, my question is, does anyone know of a book and/or some kind of framework that would make the best sense for what I am describing here? I've heard of Zope, but I would like to make sure its appropriate for the job before I spend 2 or 3 days getting acquainted with it. I'm adept at HTML, python, CSS, python-CGI, and interfacing with mySQL through DBI. I'm sure I could get something to work with these skills, but I want to minimize wheel re-invention as much as possible. Basically, I want a jump start on data-base oriented web development with a focus on applying my python skills. Any suggestions will be greatly appreciated. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ James, Karrigell is serving me well at the moment for a low-traffic intranet/library-cataloguing site. There are different ways of creating your app (html inside python, python inside html, or Karrigell services) - personally, I use services exclusively, so: library/books.ks/add, library/books.ks/edit, library/books.ks/delete library/authors.ks/add, library/authors.ks/edit, library/authors.ks/delete etc. ( I think - to the best of my knowledge - these would equate to 'controllers' in other frameworks - BookController, AuthorController... ) Karrigell will also serve static pages with a simple Include( 'mypage.html' ) I've recently set up 'lighttpd' webserver ( http://www.lighttpd.net ), and this proxies easily to Karrigell with the following in 'lighttpd.conf': server.modules = ( mod_proxy ) static-file.exclude-extensions = ( .ks ) $HTTP[url] =~ \.ks { proxy.server = ( = (( host = 127.0.0.1, port = 8081 )) ) } ie. if there is a '.ks' in the url, ask Karrigell, otherwise it's static so serve it yourself I'm also using 'leonardo' (http://leonardo.pyworks.org) as a 'Latest News' cms - it runs as a cgi script ( which lighttpd will serve via mod_cgi: server.modules = ( mod_proxy, mod_cgi) static-file.exclude-extensions = ( .ks, .py, .cgi ) cgi-assign = ( .py = /usr/local/bin/python) (Also useful is my trusty , if imperfect, html generator, htmlbuilder.py: http://gflanagan.net/site/python/htmlbuilder/htmlbuilder.py ) Hope that helps. Gerard -- http://mail.python.org/mailman/listinfo/python-list
pyparsing listAllMatches problem
hello, I'm using pyparsing and trying to parse something like: test=Q(x,y,z):-Bloo(x,Mitsis,y),Foo(y,z,1243),y28,x12,x3 and also have all comparison predicates in a separate list apart from the parse tree. So my grammar has this line in it: Comparison_Predicate = Group(variable + oneOf( ) + integer).setResultsName(pred,listAllMatches=True) but it doesn't work at all... only the last comp.pred. gets in the pred attribute... here's the full listing: from pyparsing import Literal, Word, nums, Group, Dict, alphas, quotedString, oneOf, delimitedList, removeQuotes, alphanums lbrack = Literal(().suppress() rbrack = Literal()).suppress() integer = Word( nums ) variable = Word( alphas, max=1 ) relation_body_item = variable | integer | quotedString.setParseAction(removeQuotes) relation_name = Word( alphas+_, alphanums+_ ) relation_body = lbrack + Group(delimitedList(relation_body_item)) + rbrack Goal = Dict(Group( relation_name + relation_body )) Comparison_Predicate = Group(variable + oneOf( ) + integer).setResultsName(pred,listAllMatches=True) Query = Goal.setResultsName(head) + :- + delimitedList(Goal | Comparison_Predicate) test=Q(x,y,z):-Bloo(x,Mitsis,y),Foo(y,z,1243),y28,x12,x3 print Query.parseString(test).pred P.S. another weird thing is that, depending on if I setResultsName(head) in the first Goal match, the first Goal, gets inside an extra list!What I mean is that the parsed token without setResultsName(head) is this: ['Q', ['x', 'y', 'z']] and with setResultsName(head) is this: [['Q', ['x', 'y', 'z']]] -- Χρησιμοποιώ κάποια δόση υπερβολής... -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL cannot open TIFF image in Windows
Andres Corrada-Emmanuel wrote in news:[EMAIL PROTECTED] in comp.lang.python: I have installed PIL 1.1.5 on Windows with Python 2.4. I'm unable to open .tiff images that I can open and view using Windows Explorer. In other words, this simple test fails: import Image im = Image.open('small.tif') with an 'cannot identify image file' error message. I'm able to open .jpg images. Is PIL's support for TIFF images dependent on something else in Windows? I downloaded some test images from: url:http://www.remotesensing.org/libtiff/images.html I then ran a test: LIBTIFFPIC = r.\libtiffpic import Image, os def main(): ok = error = 0 for root, sub, files in os.walk( LIBTIFFPIC ): for i in files: if i.endswith( '.tif' ): full = os.path.join( root, i ) try: tiff = Image.open( full ) except: print error:, full[ len( LIBTIFFPIC ) + 1 : ] error += 1 else: print ok: , full[ len( LIBTIFFPIC ) + 1 : ] ok +=1 print ok:, ok, \terror:, error, \ttotal:, ok + error main() The final line gave: ok: 28 error: 33 total: 61 So I only managed to load 28 of the 61 test images, AFAIK I have never installed anything special to get PIL to work with tiff images. As a side note The GIMP url:http://www.gimp.org/ wouldn't load some of the images too (I didn't test all), it had problems with 64 bit floating point images and images with RBGA data in them. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: mysqldb + multi-threading
hg wrote: Hi, I am writing a transaction server (socket-based) under windows. I use mysqldb to log info into MySQL. It is all working and I need now to decide whether to use forks (CreateProcess I guess) or threads. I saw in another thread that some db engines did have issues with being called from threads. My gut feeling is to use threads (note: each transaction is finite, so the process/thread die fairly quickly). Any insight ? hg A thread on the mysqldb forum: By: Rob Steele - robsteele RE: Do I need to enable thread safe mysql lib 2002-10-18 11:35 Yup. You also need to either synchronize the reading and writing threads so that only one can get at the database at a time or else open a second connection. You should probably use sepearate connections, one for each thread. hg -- http://mail.python.org/mailman/listinfo/python-list
Re: What algorithm does Python use to evaluate: if substring in string
Tor Erik [EMAIL PROTECTED] wrote: I would be surprised if it is the naive: Yep -- it's a mix between Boyer-Moore and Horspool with a few more bells and whistles on the top, as documented and implemented in Objects/stringlib/fastsearch.h in the Python sources and well discussed and explained at http://effbot.org/zone/stringlib.htm . Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: What algorithm does Python use to evaluate: if substring in string
In [EMAIL PROTECTED], Tor Erik wrote: I would be surprised if it is the naive: Why? I guess it simply calls an appropriate C library function. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: What algorithm does Python use to evaluate: if substring in string
Alex Martelli wrote: Tor Erik [EMAIL PROTECTED] wrote: I would be surprised if it is the naive: Yep -- it's a mix between Boyer-Moore and Horspool with a few more bells and whistles on the top, as documented and implemented in Objects/stringlib/fastsearch.h in the Python sources and well discussed and explained at http://effbot.org/zone/stringlib.htm . Alex Ok. Two questions: 1. Is a in b simply an alias for b.find(a)? 2. Is this algorithm exclusive to Python 2.5, or is it contained in 2.4 aswell? -- http://mail.python.org/mailman/listinfo/python-list
newbie: datastructure `dictionary' question
Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. I am trying to fill a nested dictionary from parsing a logfile. However each time there is only one key entry created and that's it. Just one entry, while the keys are different. That's 100% sure. I think therefore that it is an assignment error in my part. [there we have it...] To give an static example of the datastructure that I am using to clear any confusion on the datastructure part: records = { 'fam/jason-a' : { 'date': 'Fri Sep 8 16:45:55 2006', 'from': 'jason', 'subject' : 'Re: Oh my goes.', 'msize' : '237284' }, 'university/solar-system' : { 'date': 'Fri Sep 8 16:45:46 2006', 'from': 'jd', 'subject' : 'Vacancies for students', 'msize' : '9387' } } Looping over this datastructure is no problem. rkeys = ['date', 'from', 'subject', 'msize'] for folder in records.keys(): print '--' print folder for key in rkeys: print records[folder][key] Now for the actual program/dynamic part - assignment in the loop I use the following function. Note `datum' is not a date object, just a string. def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): str = line.strip() if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom elif str[:4] == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} else: other += 1 displrec(records) Note, this is not ment as a collision type datastructure, all initial data entries are unique. My question: Where is my assignment e.g. records = {folder wrong ? Thankx in advance for any tips, hints and answers. Cheers, Jason. -- http://mail.python.org/mailman/listinfo/python-list
Re: ubuntu crash
Oh.. Sorry about that, then. Did my suggestions work at all? Peter Otten wrote: Jay wrote: Here are some commands to try: apt-get install ubuntu-standard apt-get install ubuntu-desktop Also, I'd recommend trying Ubuntu's official forums website. I've found their community to be extremely helpful. http://www.ubuntuforums.org/ Plus, why on earth would you want to ax Python? Because you trust the experts on c.l.py? http://mail.python.org/pipermail/python-list/2006-September/360376.html Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem on getting various character set from pop3.retr
GM wrote: Dear all, The problem that I am facing now is that, when I use poplib to get a email message with chinese character set like big5, the character string is changed automatically to sth like =B8=D5=ACQ=AAM...the OS I am using is red hat ES4 and the python version I am using is 2.3.4 (it seems python 2.4 is not available for red hat). My application goal is to receive the email and convert all character set to UTF-8 and then store in file. Solong way to go for me, please give me some help for that, thx~ It's not being changed automatically at your end. It arrived like that. Check out the Content-Transfer-Encoding: message header. These may help: http://en.wikipedia.org/wiki/Quoted-printable http://docs.python.org/lib/module-quopri.html http://docs.python.org/lib/module-email.html Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: best split tokens?
Any more crazy examples? :) 'ey, 'alf a mo, wot about when 'enry 'n' 'orace drop their aitches? I said crazy...not pathological :) If one really wants such a case, one has to omit the standard practice of nesting quotes: John replied Dad told me 'you can't go' but let Judy However, if you don't have such situations and to want to make 'enry and 'orace 'appy, you can change the regexp to s=He was wont to be alarmed/amused by answers that won't work s2=The two-faced liar--a real joker--can't tell the truth s3='ey, 'alf a mo, wot about when 'enry 'n' 'orace drop their aitches? r = re.compile((?:(?:[a-zA-Z][-'])|(?:[-'][a-zA-Z])|[a-zA-Z])+) It will also choke using double-dashes: r.findall(s), r.findall(s2), r.findall(s3) (['He', 'was', 'wont', 'to', 'be', 'alarmed', 'amused', 'by', 'answers', 'that', won't, 'work'], ['The', 'two-faced', 'liar--a', 'real', joker--can't, 'tell', 'the', 'truth'], ['ey, 'alf, 'a', 'mo', 'wot', 'about', 'when', 'enry, 'n, 'orace, 'drop', 'their', 'aitches']) Or you could combine them to only allow infix dashes, but allow apostrophes anywhere in the word, including the front or back, one could use: r = re.compile((?:(?:[a-zA-Z]')|(?:'[a-zA-Z])|(?:[a-zA-Z]-[a-zA-Z])|[a-zA-Z])+) r.findall(s), r.findall(s2), r.findall(s3) (['He', 'was', 'wont', 'to', 'be', 'alarmed', 'amused', 'by', 'answers', 'that', won't, 'work'], ['The', 'two-faced', 'liar', 'a', 'real', 'joker', can't, 'tell', 'the', 'truth'], ['ey, 'alf, 'a', 'mo', 'wot', 'about', 'when', 'enry, 'n, 'orace, 'drop', 'their', 'aitches']) Now your spell-checker has to have the dropped initial or terminal letter locale... :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
jason schrieb: Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. I am trying to fill a nested dictionary from parsing a logfile. However each time there is only one key entry created and that's it. Just one entry, while the keys are different. That's 100% sure. I think therefore that it is an assignment error in my part. [there we have it...] To give an static example of the datastructure that I am using to clear any confusion on the datastructure part: records = { 'fam/jason-a' : { 'date': 'Fri Sep 8 16:45:55 2006', 'from': 'jason', 'subject' : 'Re: Oh my goes.', 'msize' : '237284' }, 'university/solar-system' : { 'date': 'Fri Sep 8 16:45:46 2006', 'from': 'jd', 'subject' : 'Vacancies for students', 'msize' : '9387' } } Looping over this datastructure is no problem. rkeys = ['date', 'from', 'subject', 'msize'] for folder in records.keys(): print '--' print folder for key in rkeys: print records[folder][key] Now for the actual program/dynamic part - assignment in the loop I use the following function. Note `datum' is not a date object, just a string. def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): str = line.strip() if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom elif str[:4] == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} else: other += 1 displrec(records) Note, this is not ment as a collision type datastructure, all initial data entries are unique. My question: Where is my assignment e.g. records = {folder wrong ? What you essentially do is this: records = {some : dict} records = {some other : dict} You rebind the name records to a new dictionary. So all your previously stored data is garbage collected. What you most probably want to do (I'm a bit confused about your code too lazy to dig deeper): records = {} records[folder] = {'date' : ...} Notice that the dict[key]=value syntax mutates the existing dictionary. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
jason wrote: Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. I am trying to fill a nested dictionary from parsing a logfile. However each time there is only one key entry created and that's it. Just one entry, while the keys are different. That's 100% sure. I think therefore that it is an assignment error in my part. [there we have it...] To give an static example of the datastructure that I am using to clear any confusion on the datastructure part: records = { 'fam/jason-a' : { 'date': 'Fri Sep 8 16:45:55 2006', 'from': 'jason', 'subject' : 'Re: Oh my goes.', 'msize' : '237284' }, 'university/solar-system' : { 'date': 'Fri Sep 8 16:45:46 2006', 'from': 'jd', 'subject' : 'Vacancies for students', 'msize' : '9387' } } Looping over this datastructure is no problem. rkeys = ['date', 'from', 'subject', 'msize'] for folder in records.keys(): print '--' print folder for key in rkeys: print records[folder][key] Now for the actual program/dynamic part - assignment in the loop I use the following function. Note `datum' is not a date object, just a string. def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): str = line.strip() if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom elif str[:4] == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} You are *assigning* records = blahblah each time around. records will end up being bound to the blahblah related to the *last* record that you read. You can do it item by item: records[folder]['date'] = datum etc or as a oneliner: records[folder] = {'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1} When you find yourself using a dictionary with constant keys like 'date', it's time to start thinking OO. class LogMessage(object): def __init__(self, date, .) self.date = date etc then later: records[folder] = LogMessage( date=datum, mesgbytes= extrmsize(str[8:]), mesgcount=1, ) [snip] HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: mysqldb + multi-threading
Bryan == Bryan Olson [EMAIL PROTECTED] writes: Bryan [EMAIL PROTECTED] wrote: Bryan Go with your gut. Python threads are reasonably portable, and Bryan work well on modern MS-Windows. Maybe ignore your gut and read the documentation. ;-) Bryan What in the documentation do you think answers the question? The part where it says that if MySQLdb.threadsafety == 1 it's not safe to share connections. Bryan You can't share them among processes either, so I don't see Bryan any advantage either way on that. Sure, but its difficult to do so. With threads it's trivial to share a connection and wind up getting bitten in the butt. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: best split tokens?
Tim Chase wrote: Any more crazy examples? :) 'ey, 'alf a mo, wot about when 'enry 'n' 'orace drop their aitches? I said crazy...not pathological :) If one really wants such a case, one has to omit the standard practice of nesting quotes: John replied Dad told me 'you can't go' but let Judy However, if you don't have such situations and to want to make 'enry and 'orace 'appy, you can change the regexp to s=He was wont to be alarmed/amused by answers that won't work s2=The two-faced liar--a real joker--can't tell the truth s3='ey, 'alf a mo, wot about when 'enry 'n' 'orace drop their aitches? r = re.compile((?:(?:[a-zA-Z][-'])|(?:[-'][a-zA-Z])|[a-zA-Z])+) It will also choke using double-dashes: r.findall(s), r.findall(s2), r.findall(s3) (['He', 'was', 'wont', 'to', 'be', 'alarmed', 'amused', 'by', 'answers', 'that', won't, 'work'], ['The', 'two-faced', 'liar--a', 'real', joker--can't, 'tell', 'the', 'truth'], ['ey, 'alf, 'a', 'mo', 'wot', 'about', 'when', 'enry, 'n, 'orace, 'drop', 'their', 'aitches']) Or you could combine them to only allow infix dashes, but allow apostrophes anywhere in the word, including the front or back, one could use: r = re.compile((?:(?:[a-zA-Z]')|(?:'[a-zA-Z])|(?:[a-zA-Z]-[a-zA-Z])|[a-zA-Z])+) r.findall(s), r.findall(s2), r.findall(s3) (['He', 'was', 'wont', 'to', 'be', 'alarmed', 'amused', 'by', 'answers', 'that', won't, 'work'], ['The', 'two-faced', 'liar', 'a', 'real', 'joker', can't, 'tell', 'the', 'truth'], ['ey, 'alf, 'a', 'mo', 'wot', 'about', 'when', 'enry, 'n, 'orace, 'drop', 'their', 'aitches']) Now your spell-checker has to have the dropped initial or terminal letter locale... :) Too complicated for string.bleedin'_split(), innit? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode table of character implementation in python
Tim Roberts schrieb: 0530..058F; Armenian 0590..05FF; Hebrew ... This is a fabulously useful list, Martin. Did you get this from a web page? Can you tell me where? It's part of the Unicode Consortium's database (UCD, Unicode Character Database). This specific table is called code blocks: http://www.unicode.org/Public/UNIDATA/Blocks.txt Python currently has this table not compiled in, but it should be trivial to compile this into a pure-Python table (either as a dictionary, or a list of triples). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
EyeDB Object Database (ODBMS) - Python wrapper
EyeDB is a free ODBMS based on the ODMG 3 specification with programming interfaces for C++ and Java. It is very powerfull, mature, safe and stable. In fact, it was developed in 1992 for the Genome View project althought rewritten in 1994, and has been used in a lot of bioinformatics projects http://www.eyedb.org/ Python does not have any programming interface to ODBMS and I believe that it would be very interesting that the Python community could access to a great object database like this one. If somebody is interested could to using SIP as Python wrapper. PyQT4 bindings were made with SIP http://www.riverbankcomputing.co.uk/sip/ These are the conclusions of several Python wrappers that shows that SIP generates the fastest wrappers: http://people.web.psi.ch/geus/talks/europython2004_geus.pdf * Manual wrapping is still fastest and most versatile * SIP, Boost and Babel generate native extension modules with low overhead * SWIG-generated modules rely on pure Python wrapper module and introduce a large overhead * Wrapper tool highlights: - SIP generates the fastest wrappers - SWIG is mature and well documented - Boost.Python most elegant integration of C++ and Python - Babel supports languages as both target and source If you want to know more about ODBMS here you have some interesting links: http://en.wikipedia.org/wiki/Object_database http://www.dacs.dtic.mil/techs/oodbms2/oodbms-toc.shtml http://www.kuro5hin.org/?op=displaystory;sid=2001/5/3/32853/11281 http://www.odbms.org/introduction_whenODBMS.html http://archive.devx.com/dbzone/articles/sf0801/sf0801-1.asp -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: GMPY binaries for Windows 2.5
Marc 'BlackJack' Rintsch schrieb: Interesting subject line. I think I still have a set of Win 3.11 for workgroups disks lying around somewhere, but where do I get Windows 2.5? ;-) IIRC, there was no Windows 2.5 release. There was a Windows 2.1 release; it was released in May '88, but then the next release was Windows 3.0. The new feature in Windows 2.1 was support for the extended address space of 80286 and 80386 processors. I don't think there was a Python port to Windows 2.x. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: os.name under Win32
Igor Kravtchenko schrieb: My question is whether that is supposed to be totally impossible. Under Win32, we are indeed supposed to have os.name = nt. Is that value hardcoded in Win32 binaries distribution themself? Can it potentially change? I can't test it right now, but I would expect that Cygwin Python binaries on Win32 have os.name == posix. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: How to build extensions on Windows?
Kevin D. Smith schrieb: Then there is Mike Fletcher's web page (http://www.vrplumber.com/programming/mstoolkit/) that describes in detail how to build extensions, but most of the links to external software are no longer valid. I think it's safe to say that I am completely lost, as there appears to be no authoritative, up-to-date description on how to make this work. If all else fails, buy a copy of Visual Studio 2003. They are available fairly cheap at Ebay. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
Paul Rubin wrote: [EMAIL PROTECTED] [EMAIL PROTECTED] writes: FWIW, the original loop looked perfectly fine and readable and I'd suggest going with that over these hacked-up listcomp solutions. Don't use a listcomp just for the sake of using a listcomp. Thanks for that, Carl. I think that using the loop is probably what I'll end up doing. I had no idea that the listcomp thing would be quite a complicated as it is appearing. I had it in my mind that I was missing some obvious thing which would create a simple solution :) I think even if you code a loop, it's still cleaner to use enumerate: seq = [2, 3, 1, 9] tmp = [] for i,a in enumerate(seq): tmp.extend([i]*a) Oh, good! Yes, cleaner ... and in my little test a tiny bit faster. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyserial problem: script stops reading
On 9/9/06, Hendrik van Rooyen [EMAIL PROTECTED] wrote: | I wrote a script on Linux that uses pyserial to read status messages | from a serial line using readlines(). For now, it just displays what | it gets on stdout: | (...) | ser = serial.Serial(port=1, | baudrate=1200, | rtscts=1, if this is enabling hardware flow control try turning it off - at 1200 baud you should not need it Okay I disabled this for once. | | If the script does not time out there, I am not sure what else it is | doing. It seems to be in a wait state it does not get out of. Sounds more and more like flow control hassle - can you lay your hands on a break out box or a datascope? Unfortunately not. I will run a few more tests without rtscts though. I am actually not horribly worried about kicking the serial reading service every once in a while, but it would be better if it detected the stall state itself... Thanks Fred -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python Based Web Application
Adam Jones wrote: John Henry wrote: Hi folks. I am interested on this topic as well. If my application is not database related, what would be a good choice? I have clients that wish to use my Python applications but I am not willing to give them the code. So, I am thinking about setting it up as a web based application and let them run it from their browser. If things go well, may be I can charge them for usage later. The application will involve getting a data file from the user, do some processing, and return a result file to the user. Very modest - to start. For that kind of usage I don't know if any of the big name web frameworks would be worth the effort, especially if returning a result file entails making it available for download instead of handing it back in the form of an HTML page. At that point all you would really need is a controller to handle most of the details of working in HTTP and maybe a templating system to help out with the HTML. The only controller that is available independently that I can comment on usefully is Cherrypy. It works pretty well, can run its own web server if you like, and seems like it would be simple enough to use for what you are talking about. Without knowing more about your requirements that would be my suggestion. I am sure there are other people on this group with more experience here who could give more useful commentary. -Adam Thanks, I am checking out CherryPie -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for tips on my first python script.
Lex Hider wrote: try: opts, args = getopt.getopt(sys.argv[1:], l:, [latest=, notfound]) except getopt.GetoptError: sys.exit(2) #usage() for opt, arg in opts: if opt in (-l, --latest): latest = int(arg) elif opt in (--notfound): ignoreNotFound = True #add notfound files to log You should definitely consider using optparse or argparse_. Here's a rewrite using argparse:: parser = argparse.ArgumentParser(description='podcast aggregator') parser.add_argument('-l', '--latest', type=int) parser.add_argument('--notfound', action='store_true') values = parser.parse_args() Then just use ``values.latest`` and ``values.notfound`` instead of ``latest`` and ``ignoreNotFound`` in the rest of your code. Using argparse also allows you to easily add your other directories as command line options, e.g.:: parser.add_argument('podDir', nargs='?', default=os.path.join(HOME, 'Podcasts')) If you then use ``values.podDir`` instead of ``podDir`` throughout your code, your users can invoke your script in either of the following ways:: GodCast.py# no args, use $HOME/Podcasts GodCast.py podcast_dir# podDir specified, use podcast_dir If I were writing your script, I would add optional or positional arguments for all of ``maxChecksPerDay``, ``myTemp``, ``downDir``, ``logFile``, ``cacheDir`` and ``feedList``. (If you'd like your code to look more like the Python standard, I'd use `PEP 8`_ compliant names, e.g. ``pod_dir`` instead of ``podDir`` and ``make_dirs`` instead of ``makeDirs``.) .. _argparse: http://argparse.python-hosting.com/ .. _PEP 8: http://www.python.org/dev/peps/pep-0008/ HTH, STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: What algorithm does Python use to evaluate: if substring in string
Tor Erik [EMAIL PROTECTED] wrote: Alex Martelli wrote: Tor Erik [EMAIL PROTECTED] wrote: I would be surprised if it is the naive: Yep -- it's a mix between Boyer-Moore and Horspool with a few more bells and whistles on the top, as documented and implemented in Objects/stringlib/fastsearch.h in the Python sources and well discussed and explained at http://effbot.org/zone/stringlib.htm . Alex Ok. Two questions: 1. Is a in b simply an alias for b.find(a)? The 'in' operator can be minutely better optimized, but they share the underlying algorithm (in 2.5). 2. Is this algorithm exclusive to Python 2.5, or is it contained in 2.4 aswell? It's 2.5 novelty. Look at the performance on the same machine (my 2.0 GHz MBP, MacOSX 10.4.7): brain:~ alex$ python2.4 -mtimeit -s'x=foo;y=bar*99+x+baz*77' 'x in y' 10 loops, best of 3: 9.04 usec per loop brain:~ alex$ python2.4 -mtimeit -s'x=foo;y=bar*99+x+baz*77' 'y.find(x)!=-1' 10 loops, best of 3: 2.01 usec per loop brain:~ alex$ python2.5 -mtimeit -s'x=foo;y=bar*99+x+baz*77' 'x in y'100 loops, best of 3: 0.452 usec per loop brain:~ alex$ python2.5 -mtimeit -s'x=foo;y=bar*99+x+baz*77' 'y.find(x)!=-1' 100 loops, best of 3: 0.842 usec per loop find used to be way faster than 'in' -- now they share algorithms and 'in' can be more optimized (no need to track ``where'' it finds a match, so to speak;-), so find is over twice as fast as it used to be, 'in' is about 20 times as fast as it used to be, in this example -- it gets even better if you look at larger and larger strings, e.g...: brain:~ alex$ python2.4 -mtimeit -s'x=foo*123;y=bar*999+x+baz*777' 'x in y' 1 loops, best of 3: 91.9 usec per loop brain:~ alex$ python2.5 -mtimeit -s'x=foo*123;y=bar*999+x+baz*777' 'x in y' 10 loops, best of 3: 3.01 usec per loop here, we're going _30_ times as fast, not just 20;-). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
On Sat, 09 Sep 2006 09:00:35 -0700, John Machin wrote: jason wrote: Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. cut ... /cut Owww.. Of course... ! Thankx for the answer and the suggestion. It really helped me a lot. I defintely going to take the OO approach later on. thankx again for the quick reply. Jason. You are *assigning* records = blahblah each time around. records will end up being bound to the blahblah related to the *last* record that you read. You can do it item by item: records[folder]['date'] = datum etc or as a oneliner: records[folder] = {'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1} When you find yourself using a dictionary with constant keys like 'date', it's time to start thinking OO. class LogMessage(object): def __init__(self, date, .) self.date = date etc then later: records[folder] = LogMessage( date=datum, mesgbytes= extrmsize(str[8:]), mesgcount=1, ) [snip] HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Secure Postgres access
On Thu, 07 Sep 2006 18:36:32 -0700, Paul Rubin wrote: Reid Priedhorsky [EMAIL PROTECTED] writes: Wouldn't they need a database password? Well, right now, no. I have Postgres configured to trust the OS on who is who. You trust the OS on the client machine, but not the client machine's users? Does it run identd? Maybe you could use that. I'd consider this shaky for any real security application, but it might be better than nothing depending on what you're doing. Hi Paul, Thanks for your help. No -- I suppose I wasn't clear. There are two machines involved: A) Database server. Run by me. I trust the OS on who is who, and there is only one user (me). So database clients run on this box don't require a password. B) Work machine. Run by others, many users. I'd like to also run my database client (Python) here. SSH tunnel is unsatisfactory because other folks can slip down the tunnel after I set it up and then connect to the DB as me. Having the DB on (A) listen to the Internet as well as localhost for connections is also unsatisfactory, because I don't want to set up database passwords. What I'd like is functionality similar to what Subversion does with svn+ssh:// URLs: an SSH tunnel that accepts only one connection and doesn't have race conditions. Thanks again, Reid -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing listAllMatches problem
don pasquale [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] hello, I'm using pyparsing and trying to parse something like: test=Q(x,y,z):-Bloo(x,Mitsis,y),Foo(y,z,1243),y28,x12,x3 and also have all comparison predicates in a separate list apart from the parse tree. So my grammar has this line in it: Comparison_Predicate = Group(variable + oneOf( ) + integer).setResultsName(pred,listAllMatches=True) but it doesn't work at all... only the last comp.pred. gets in the pred attribute... Thanks for posting this test case. This is a bug in pyparsing. I'll have a fix ready shortly. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
Omar wrote: thanks for the suggestions, fellas Would be kind of you to tell us which one you have decided to use and why? Claudio Grondi P.S. If you don't like any of already mentioned you can give SciTe a try. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about subclassing - version 2
Maric Michaud a écrit : Le vendredi 08 septembre 2006 10:15, Bruno Desthuilliers a écrit : You mentioned NotImplementedError, which is indeed the usual way to make something abstract in Python. Hummm, some more thoughts about this. I can imagine class hierarchies where the presence of not implemented methods doesn't mean that the class is actually an abstract one. I can imagine this too - as well as I can imagine the nightmarish spaghetti code that could use this class hierarchie. Even if partial implementation is not a common scheme it can save you from writing a lot of classes. A partial implementation should return default values, not raise (aka NullObjectPattern). Well, IMHO at least. (snip) And this can become a true spider net for more complicated cases. Obviously, in practice we will choose alternatives to inheritance (strategies, visitors, ...) Composition/delegation... to work with such complex situations, Indeed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python Based Web Application
James Stroud a écrit : Hello All, I am interested in setting up a modest invoicing system for some consulting I am doing. I like the idea of managing this on the web and creating invoices and printing them from a browser. However, I'm not really sure where to start. I've played with some CMS applications, but they seem more for blogging (mamba, wordpress, etc.). Ideally, I would like to interface with mySQL (or whatever the favorite web-flavor database app is these days). I would like to be able to use my python skills. I confident that if I set out to write this from scatch, I will be seriously re-inventing the wheel, perhaps several times over. So, my question is, does anyone know of a book and/or some kind of framework that would make the best sense for what I am describing here? Web-base front-end to a SQL database... Pylons, Turbogears or Django comes to mind. Or a custom-made stack (see link below)... I've heard of Zope, but I would like to make sure its appropriate for the job before I spend 2 or 3 days getting acquainted with it. Lol. Make it 2 or 3 monthes. And before you loose your time: Zope is certainly not the best choice here. I'm adept at HTML, python, CSS, python-CGI, and interfacing with mySQL through DBI. I'm sure I could get something to work with these skills, but I want to minimize wheel re-invention as much as possible. Basically, I want a jump start on data-base oriented web development with a focus on applying my python skills. Any suggestions will be greatly appreciated. This serie of articles may be of interest to you: http://adminspotting.net/building-web-pages-with-python/ HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
jason a écrit : Just some more suggestions: def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): for line in data.split('\n'): str = line.strip() This will shadow the builtin 'str' type. You could reassign to 'line' instead, or manage to get stripped lines already: for line in map(str.strip, data.split('\n'): if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom Mixing processing with IO may not be a good idea... elif str[:4] == 'Fold': line_type = line[:4] if line_type == 'From': # code here elif line_type == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} You now know that it should be: records[folder] = {...} else: other += 1 displrec(records) As a last note, you may want to pay more attention to your namings... ie, 'display_records()' is much more readable than 'displrec()' and still not to long to type !-) My 2 cents (and a half) -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python Based Web Application
Karrigell can really be recommended. Simple, but powerful. No need for SQL (though it can), just use the pure Python buzhug, Karrigell services and (Cheetah) templates. Works great.regardsAndre -- http://mail.python.org/mailman/listinfo/python-list
Re: Unable to make python work properly
Benjamin Grant wrote: Hi all, I'd greatly appreciate any help. I can configure, make and install everything fine. I'm using python 2.4 I have ubuntu dapper drake. I am trying to install hplip which requires python. When I do this, this also works but while running the following error occurs: Traceback (most recent call last): File /usr/local/bin/hp-setup, line 31, in ? import readline, gzip ImportError: No module named readline If you want Python 2.4 on Ubuntu, you should just install the python2.4 package (with, e.g. apt-get), rather than trying to compile it. Doing so should resolve the dependency problems using the package manager. For one thing, I'm pretty sure that the Ubuntu standard package is going to have readline included. If you must compile the hplip package, and it needs to build Python extensions, then you will likely need to also install the package python2.4-dev (which will include the C headers and stuff that dependent packages will need to compile). That should be a whole lot easier than trying to recompile Python with readline support on Ubuntu yourself (the package managers have probably done the work for you). I only say 'probably' because I'm guessing this from knowing Debian, which Ubuntu is based on, and guessing that no one would go out of their way to *remove* readline support. Cheers, Terry -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
makepy, ADO and dynamic.py
I'm trying to track down a performance issue in my Windows code, and hotshot is telling me that the most time and calls are spent in these methods ncalls tottime percall cumtime percall filename:lineno(function) 75975 63982.7790.842 124464.4191.638 c:\python24\lib\site-packages\win32com\client\dynamic.py:285(_make_method_) 71294 47871.4240.671 50629.2240.710 c:\python24\lib\site-packages\win32com\client\__init__.py:444(_ApplyTypes_) If I understand correctly, running makepy on the appropriate COM class should get rid of the dynamic stuff and let it be called directly. I use ADODB to talk to my database server, and I've run makepy for Microsoft Active X Data Objects 2.8 Library [1] and on Microsoft ActiveX Data Objects Recordset 2.8 Library, but I'm still seeing the call to the dynamic.py class. Am I right that seeing the calls in dynamic.py implies that I'm running makepy on the wrong thing? Any idea what I should be running makepy on? [1] I seem to have a bunch of versions of Microsoft ActiveX Data Objects Library, is there a chance that another ADO library is being used? -- http://mail.python.org/mailman/listinfo/python-list
Can I make unicode in a repr() print readably?
I still run into my own ignorance a lot with unicode in Python. Is it possible to define some combination of __repr__, __str__, and/or __unicode__ so that the unicode() wrapper isn't necessary in this statement: print unicode(jp.concepts['adjectives']['BLUE'][0]) GLOSS: 青い, cl=None, {'wd': u'\u9752\u3044'} (i.e. can I make it so that the object that print gets is already unicode, so that the label '青い' will print readably?) Or, put another way, what exactly does 'print' do when it gets a class instance to print? It seems to do the right thing if given a unicode or string object, but I cant' figure out how to make it do the same thing for a class instance. I guess it would've seemed more intuitive to me if print attempted to use __unicode__() first, then __str__(), and then __repr__(). But it apparently skips straight to __str__(), unless the object is already a unicode object. (?) The following doesn't bother me: jp.concepts['adjectives']['BLUE'][0] GLOSS: \u9752\u3044, cl=None, {'wd': u'\u9752\u3044'} And I understand that I might want that if I'm working in an ASCII-only terminal. But it's a big help to be able to read/recognize the labels when I'm working with localized encodings, and I'd like to save the extra typing if I'm going to be looking at a lot of these So far, I've tried overriding the __unicode__ method to return the unicode representation (doesn't seem like print calls it, though), and I've tried returning the same thing from __repr__, but the latter causes this unpleasant result: print jp.concepts['adjectives']['BLUE'][0] Traceback (most recent call last): File stdin, line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128) so I don't think I want to do that. Advice? Terry -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
OT: What encoding is this?
Way off-topic for Python, but can someone tell me what encoding was used in this web page: http://www.loppen.dk/side.php?navn=getin I'm guessing ISO-8859-15, but the page doesn't indicate and it's none of the ones available in Safari. Thanks, Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: What encoding is this?
[EMAIL PROTECTED] wrote: Way off-topic for Python, but can someone tell me what encoding was used in this web page: http://www.loppen.dk/side.php?navn=getin I'm guessing ISO-8859-15, but the page doesn't indicate and it's none of the ones available in Safari. Thanks, Skip ISO-8859-1 per Mozilla -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a regexp generator based on a set of known string representative of a string set
[EMAIL PROTECTED] wrote: I have tried their online Text-symbol Pattern Discovery with these input values: cpkg-3 cpkg-31008 cpkg-3000A cpkg-30006 nsug-300AB nsug-300A2 cpdg-30001 nsug-300A3 Well, in the realm of sequence analysis, it is trivial to devise a regex for these values because they are already aligned and of fixed length. This is a couple of more lines than it needs to be, only so its easier to follow the logic. This uses throw-away groups to avoid bracketed sets, becuase you have dashes in your items. You might need to tweak the following code if you have characters special to regex in your sequences or if you want to use bracketed sets. The place to do this is in the _joiner() function. values = cpkg-3 cpkg-31008 cpkg-3000A cpkg-30006 nsug-300AB nsug-300A2 cpdg-30001 nsug-300A3 .split() # python 2.5 has new list comp features to shorten this test, but # the resulting list comp can begin to look ugly if the alternatives # are complicated def _joiner(c): if len(c) == 1: # will raise KeyError for empty column return c.pop() else: return (?:%s) % '|'.join(c) columns = [set(c) for c in zip(*values)] col_strs = [_joiner(c) for c in columns] rgx_str = .join(col_strs) exact_rgx_str = ^%s$ % rgx_str # '(?:c|n)(?:p|s)(?:k|u|d)g-3(?:1|0)0(?:A|0)(?:A|B|1|0|3|2|6|8)' print rgx_str But, if you get much more complicated that this, you will definitely want to check out hmmer, especially if you can align your sequences. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyparsing listAllMatches problem
On Sat, 09 Sep 2006 20:46:29 +0300, Paul McGuire [EMAIL PROTECTED] wrote: Thanks for posting this test case. This is a bug in pyparsing. I'll have a fix ready shortly. -- Paul Ur welcome, I hope you find the bug and squash it :). I temporalily solved my problem (in case anyone else has it) by changing another definition and including a second call to setResultsName. I modified the Goal definition from Goal = Dict(Group( relation_name + relation_body )) to Goal = Dict(Group( relation_name + relation_body )).setResultsName(glist,listAllMatches=True) if an extra .setResultsName(glist,listAllMatches=True) is added, then both calls to setResultsName (in Goal and Comparison_Predicate) suddenly work as planned! weird huh? I don't think this generally works, but it's worth a try until the bug is fixed... -- Χρησιμοποιώ κάποια δόση υπερβολής... -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
I've been using scite the last few days, and have also been experimenting with ulipad. thanks, again -- http://mail.python.org/mailman/listinfo/python-list
Re: Secure Postgres access
Reid Priedhorsky [EMAIL PROTECTED] writes: B) Work machine. Run by others, many users. I'd like to also run my database client (Python) here. Well, just how much do you distrust that machine? If you think it's totally pwned by attackers who will stop at nothing to subvert your client, you shouldn't run the client there. How do you propose to open an SSH connection from a completely untrusted box, for example? You can't type an SSH password into it since you have to assume that the keystrokes are being logged. If you only partially distrust the machine, then figure out what operations on it you do trust, and work from there. What I'd like is functionality similar to what Subversion does with svn+ssh:// URLs: an SSH tunnel that accepts only one connection and doesn't have race conditions. That doesn't sound like the right answer. It means you have to carefully arrange your application to open just one db connection and use it throughout its run. Many applications are somewhat cavalier about opening and closing db conns, and and it's sometimes convenient to write in that style. Some apps (e.g. multi-threaded ones) inherently require multiple db conns. And even if you have an SSH mode that accepts just one connection, since your db app is separate and has to connect to the forwarding port after you use a separate program open the port, how do you stop someone else from grabbing it first? I think what you really want is normal, multi-connection SSH port forwarding to the db server, but that works only for you and doesn't work for others. That seems to mean one of: 1) authentication (like a db password) in the db client, maybe using another process that the db client gets a credential from 2) authentication through SCM_CREDENTIALS on a PF_UNIX socket 3) authentication via identd on the client machine (i.e. you trust the admins on that machine to keep malicious stuff off of the privileged ports) 4) some other scheme yet to be identified Actually, looking at the doc for ssh-agent(1), it looks like it might do something like #2 above. If I understand it, you would run your db client as something like ssh-agent your-client and the ssh agent would start your client, exporting an env variable that your client can use to start ssh without a password and connect to the db server. The env variable points to a PF_UNIX socket where the doc says the socket is made accessible only to the current user. Although the docs aren't totally clear, this sounds sort of like what we're discussing, so I'd say it's worth looking into. Finally, lately for unrelated reasons I've been looking at Vtun (vtun.sf.net), a simple VPN program that might be easier to modify than OpenSSH. Its security features look worse than ssh's, but maybe they're enough for your purpose. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.name under Win32
Martin v. Löwis wrote: Igor Kravtchenko schrieb: My question is whether that is supposed to be totally impossible. Under Win32, we are indeed supposed to have os.name = nt. Is that value hardcoded in Win32 binaries distribution themself? Can it potentially change? I can't test it right now, but I would expect that Cygwin Python binaries on Win32 have os.name == posix. That's correct. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: pyserial problem: script stops reading
Frederic Wenzel wrote: On 9/9/06, Hendrik van Rooyen [EMAIL PROTECTED] wrote: | I wrote a script on Linux that uses pyserial to read status messages | from a serial line using readlines(). For now, it just displays what | it gets on stdout: | (...) | ser = serial.Serial(port=1, | baudrate=1200, | rtscts=1, if this is enabling hardware flow control try turning it off - at 1200 baud you should not need it Okay I disabled this for once. | | If the script does not time out there, I am not sure what else it is | doing. It seems to be in a wait state it does not get out of. Sounds more and more like flow control hassle - can you lay your hands on a break out box or a datascope? Unfortunately not. I will run a few more tests without rtscts though. I am actually not horribly worried about kicking the serial reading service every once in a while, but it would be better if it detected the stall state itself... You could maybe have another program monitoring it - I seem to remember the APSN database holding a UDP heartbeat program that might be readily adaptable. No time to Goog^w use a popular search engine to look for it just now, but you should have all the keywords ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: What encoding is this?
http://www.loppen.dk/side.php?navn=getin I'm guessing ISO-8859-15, but the page doesn't indicate and it's none of the ones available in Safari. It decodes to the same text using ISO-8859-1, ISO-8859-15, or Windows-1252. More pages without declarations are produced on Windows so I'd guess that its Windows-1252. To tell, look for prices in Euros (€) on the site. If there are \x80 characters in front of prices then it is Windows-1252, if \xa4 then it is ISO-8859-15. ISO-8859-1 does not have a Euro sign. It isn't Mac-Roman as decoding with Mac-Roman produces non-alphabetics in unusual places: H¯jde rather than Højde. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: IronPython on Mono howto
[EMAIL PROTECTED] wrote: One thing I did find especially annoying though was that none of the editing keys worked. Seo It is a known problem. It is a Mono bug. (ncurses-based colored Seo console is not really complete.) There is a workaround. Thanks, it worked perfectly. I guess the white text on the white background prevented the Mono developers from seeing that the editing characters were self inserting. ;-) On MacOSX, my workaround for the white-on-white behavior of IronPython+Mono on Apple's Terminal was to try other terminal emulators -- Terminator worked fine (display-wise). But the editing remains off, so I'll be glad to try the suggested workaround (if and when sparcs.kaist.ac.kr responds...:-). Thaks, Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Html character entity conversion
[EMAIL PROTECTED] wrote: danielx wrote: [EMAIL PROTECTED] wrote: Here is my script: from mechanize import * from BeautifulSoup import * import StringIO b = Browser() f = b.open(http://www.translate.ru/text.asp?lang=ru;) b.select_form(nr=0) b[source] = hello python html = b.submit().get_data() soup = BeautifulSoup(html) print soup.find(span, id = r_text).string OUTPUT: #1087;#1088;#1080;#1074;#1077;#1090; #1087;#1080;#1090;#1086;#1085; -- In russian it looks like: привет питон How can I translate this using standard Python libraries?? -- Thank you for response. It doesn't matter what is 'BeautifulSoup'... However, the best solution is to ask BeautifulSoup to do that for you. if you do soup = BeautifulSoup(your_html_page, convertEntities=html) you should not be worrying about the problem you had. this converts all the html entities (the five you see as soup.entitydefs) and all the #xxx; stuff to their python unicode string. yichun General question is: How can I convert encoded string sEncodedHtmlText = '#1087;#1088;#1080;#1074;#1077;#1090; #1087;#1080;#1090;#1086;#1085;' into human readable: sDecodedHtmlText == 'привет питон' -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] geopy: a Geocoding Toolbox for Python
Brian Beck wrote: I'm happy to announce the first (alpha) release of geopy, a geocoding toolbox for Python: http://exogen.case.edu/projects/geopy/ For anyone interested, there is now a mailing list on Google Groups: http://groups.google.com/group/geopy geopy also now supports the Virtual Earth geocoder and better support for UK addresses using the Google geocoder. -- Brian Beck Adventurer of the First Order -- http://mail.python.org/mailman/listinfo/python-list
Function metadata (like Java annotations) in Python
Hi, I'm trying to attach some attributes to functions and methods, similar to Java annotations and .NET attributes. I also want to use a convenient decorator for it, something along the lines of @attr(name=xander, age=10) def foo(): ... Assigning attributes to the function will work, as will assigning keys and values to a dictionary in an attribute. But if there are more decorators in the way, this could fail: @onedec @attr(...) @twodec def foo(): ... Given 'foo' now, how do I find the attributes? Assigning to a global attribute registry (some interpreter-global dictionary), although less desirable, might have been acceptable, but then how do I identify the function after it's been wrapped in more decorators? Also, it may be nice to have the following work as well: @attr(name=Xander) @attr(age=10) @somedec @attr(hobby=knitting) def foo(): ... Any thoughts? Am I rehashing something old that my search skills didn't uncover? Thanks! Ori. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
At 01:10 PM 9/8/2006, Doug Stell wrote: Try www.TextPad.com. I've used it for years and love it. It understands many programming language constructs and can be taught to understand python so that things show up in color. Any tips on how to teach TextPad to understand python? Thanks, Dick Moores -- http://mail.python.org/mailman/listinfo/python-list
Re: Function metadata (like Java annotations) in Python
oripel: Maybe this is a silly suggestion, the docstring is already overloaded, but it may be used for this too: def foo(): ... ... @ATTR name=Xander @ATTR age=10 @ATTR hobby=knitting ... (Or somethins similar without the @). Later you can retrive the attributes from the docstring, for example using a verbose RE like: r\s* @ATTR \s+ (\w*) \s* = \s* (.*) And you use it to create a dict of attributes. The decorators you apply to foo() must keep its docstring too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode / cx_Oracle problem
cursor.execute(INSERT INTO mean (mean_id,mean_eng_txt) VALUES (:id,:mean),id=id,mean=mean) ... cx_Oracle.NotSupportedError: Variable_TypeByValue(): unhandled data type unicode But when I try putting a codecs.BOM_UTF16_LE in various plausible places, I just end up generating different errors. Diez: Show us the alleged plausible places, and the different errors. Otherwise it's crystal ball time again. More usefully, let's just try to fix the code above. Here's the error message I get: NotSupportedError: Variable_TypeByValue(): unhandled data type unicode Traceback (innermost last): File c:\pythonapps\LoadMeanToOra.py, line 1, in ? # LoadMeanToOra reads a UTF-16LE input file one record at a time File c:\pythonapps\LoadMeanToOra.py, line 23, in ? cursor.execute(INSERT INTO mean (mean_id,mean_eng_txt) What I can't figure out is whether cx_Oracle is saying it can't handle Unicode for an Oracle nvarchar2 data type or whether it can handle the input but that it needs to be in a specific format that I'm not supplying. - Richard Schulman -- http://mail.python.org/mailman/listinfo/python-list
pyExcelerator question - dates map to floats?
I'm experimenting with pyExcelerator and am reading an XLS file which contains dates. In Excel on my Mac they look like 09/13/06. After parsing them out of the .XLS file they are floats, e.g. 38973.0. I assume that's an offset in days. Doing a little date math I come up with a base date of approximately (though not quite) 1900-01-01: import datetime dt = datetime.timedelta(days=-38973) datetime.date(2006, 9, 13) + dt datetime.date(1899, 12, 30) datetime.date(1900, 1, 1) - dt datetime.date(2006, 9, 15) Is there some way to get pyExcelerator from doing this conversion and instead return dates as strings? If I'm reading an arbitrary worksheet and don't know which columnn might be a date, it's kind of hard to guess. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: pyExcelerator question - dates map to floats?
skip Doing a little date math I come up with a base date of skip approximately (though not quite) 1900-01-01: ... Reading the code in BIFFRecords.py I saw this docstring: This record specifies the base date for displaying date values. All dates are stored as count of days past this base date. In BIFF2-BIFF4 this record is part of the Calculation Settings Block. In BIFF5-BIFF8 it is stored in the Workbook Globals Substream. Record DATEMODE, BIFF2-BIFF8: Offset SizeContents 0 2 0 = Base is 1899-Dec-31 (the cell = 1 represents 1900-Jan-01) 1 = Base is 1904-Jan-01 (the cell = 1 represents 1904-Jan-02) Shifting my base date from 1900-01-01 to 1899-12-31 leaves me off by one. I take it then that count of days past this base date must include that date. It's too late for me to do any more poking around. Does anyone know if I might get date floats which are offset from 1904-01-01 (I think that was the traditional Mac start-of-epoch) or are they normalized to all be offsets from 1899-12-31? I noticed that there are two items on the pyExcelerator to-do list. Number one is documentation. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Function metadata (like Java annotations) in Python
oripel wrote: I'm trying to attach some attributes to functions and methods, similar to Java annotations and .NET attributes. ... Assigning attributes to the function will work, as will assigning keys and values to a dictionary in an attribute. But if there are more decorators in the way, this could fail: @onedec @attr(...) @twodec def foo(): ... Given 'foo' now, how do I find the attributes? ... Any thoughts? Am I rehashing something old that my search skills didn't uncover? There are past discussions about this; google for python-dev decorator metadata. For example: http://thread.gmane.org/gmane.comp.python.devel/77506/focus=77507 Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: pyExcelerator question - dates map to floats?
[EMAIL PROTECTED] wrote: skip Doing a little date math I come up with a base date of skip approximately (though not quite) 1900-01-01: ... Reading the code in BIFFRecords.py I saw this docstring: This record specifies the base date for displaying date values. All dates are stored as count of days past this base date. In BIFF2-BIFF4 this record is part of the Calculation Settings Block. In BIFF5-BIFF8 it is stored in the Workbook Globals Substream. Record DATEMODE, BIFF2-BIFF8: Offset SizeContents 0 2 0 = Base is 1899-Dec-31 (the cell = 1 represents 1900-Jan-01) 1 = Base is 1904-Jan-01 (the cell = 1 represents 1904-Jan-02) Shifting my base date from 1900-01-01 to 1899-12-31 leaves me off by one. You have found Microsoft's What do you mean, 1900 was not a leap year? bug. I take it then that count of days past this base date must include that date. It's too late for me to do any more poking around. Does anyone know if I might get date floats which are offset from 1904-01-01 (I think that was the traditional Mac start-of-epoch) or are they normalized to all be offsets from 1899-12-31? I noticed that there are two items on the pyExcelerator to-do list. Number one is documentation. Check out my xlrd package. http://cheeseshop.python.org/pypi/xlrd/0.5.2 (1) It has docs, including an extensive rant about Excel dates which will answer all of your above questions. (2) It has an helper functions for converting between Excel dates and tuples (which can then be converted into datetime, time, and mxDateTime dates). Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import xlrd xlrd.xldate_as_tuple(38973.0, datemode=0) (2006, 9, 13, 0, 0, 0) (3) It tracks the number formats applied to floats, and automatically classifies them as number and date. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
[ python-Bugs-1551432 ] __unicode__ breaks for exception class objects
Bugs item #1551432, was opened at 2006-09-03 05:24 Message generated for change (Comment added) made by bcannon You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1551432group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: Python 2.5 Status: Closed Resolution: Fixed Priority: 9 Submitted By: Marcin 'Qrczak' Kowalczyk (qrczak) Assigned to: Brett Cannon (bcannon) Summary: __unicode__ breaks for exception class objects Initial Comment: PyObject_Unicode and the unicode function stopped working on class objects of subclasses of BaseException in Python 2.5. unicode(ImportError) Traceback (most recent call last): File stdin, line 1, in module TypeError: descriptor '__unicode__' of 'exceptions.BaseException' object needs an argument It should work analogously to str: str(ImportError) type 'exceptions.ImportError' -- Comment By: Brett Cannon (bcannon) Date: 2006-09-09 00:20 Message: Logged In: YES user_id=357491 rev. 51837 and rev. 51838 have the fix in the trunk and 2.5, respectively. -- Comment By: Marcin 'Qrczak' Kowalczyk (qrczak) Date: 2006-09-05 15:08 Message: Logged In: YES user_id=50234 I think the way which is consistent with the current Python implementation is adding the tp_unicode slot. (Parenthetical remark. In the binding between Python and my language Kogut I'm exposing various standard APIs between the two languages automatically. And __unicode__ happened to be the *only* method which I needed to treat specially by tp_getattro. It's the only method I've encountered so far which is called by Python on lots of ordinary objects, and which doesn't have a C slot (and the consequence is that my default wrapper shouldn't forward it to the __unicode__ attribute in the other language, but to the appropriate API of the other language which obtains a Unicode rendition). This was a different issue than the topic of this bug, was solvable, but it was another suggestion that the way of handling __unicode__ is inconsistent with other *similar* attributes, similar in the sense of the amount of genericity and magicness, and should have a C slot. The present problem is somewhat dual: now it's me who calls __unicode__ (even if indirectly), and it's Python who provides __unicode__ implementation of its objects. End of parenthetical remark.) Anyway, I'm afraid the issue is a symptom of a deeper problem. I was some time ago wondering how does Python distinguish whether x.foo, when x happens to be a class object (or type object), is meant to be an unbound method to be called with instances of that class, or a bound method to operate on the class object itself. It seems that Python doesn't attempt to use the second interpretation at all. Despite this, various standard operations are dressed in magic methods with names surrounded by double underscores do work for class objects! And while str(x) is the same as x.__str__() for most objects, it's not true for class objects and type objects: str(x) goes through the C slot while x.__str__() doesn't work. The set of methods which have C slots would seem to be just a shortcut for performance, but actually it has a semantic significance. Namely class objects and type objects can have specialized implementations of those methods, but not of ordinary methods. Fortunately it doesn't matter much in practice because the set of methods supported by class objects is fixed, and it just happens to be the subset of the methods with C slots. Unless some other objects can play the role of classes, and then the problem might reappear; I'm completely ignorant about Python metaclasses. -- Comment By: Brett Cannon (bcannon) Date: 2006-09-05 11:22 Message: Logged In: YES user_id=357491 This is because exceptions now define a proper __unicode__() method in the PyMethodDef array. This is what gets called and it requires an exception instance. Before it just fell through to the tp_str slot and that didn't complain. Unless some knows a better way (short of defining a tp_unicode slot), the only way to make this work would be to rip out the __unicode__() method. This would then require the function in the tp_str slot to have to detect if its arguments need to be Unicode or not (and I don't know how to do that off the top of my head; is their a PyUnicode_Check()?). -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1551432group_id=5470 ___ Python-bugs-list mailing list Unsubscribe:
[ python-Bugs-718532 ] inspect, class instances and __getattr__
Bugs item #718532, was opened at 2003-04-10 01:31 Message generated for change (Comment added) made by baijum81 You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=718532group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 6 Submitted By: Stefan Schwarzer (sschwarzer) Assigned to: Ka-Ping Yee (ping) Summary: inspect, class instances and __getattr__ Initial Comment: inspect.isclass(class_instance) fails if the corresponding class uses a quot;wildcardquot; implementation of __getattr__. Example: Python 2.2.2 (#1, Nov 13 2002, 22:53:57) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type quot;helpquot;, quot;copyrightquot;, quot;creditsquot; or quot;licensequot; for more information. gt;gt;gt; import inspect gt;gt;gt; class X: ... def __getattr__(self, name): ... if name == 'foo': ... return 1 ... if name == 'bar': ... return 2 ... else: ... return quot;defaultquot; ... gt;gt;gt; x = X() gt;gt;gt; inspect.isclass(x) 1 The problematic expression in inspect.isclass is hasattr(object, '__bases__') which returns a true value. -- Comment By: Baiju M (baijum81) Date: 2006-09-09 18:44 Message: Logged In: YES user_id=565450 Due to this bug, 'pydoc modulename' is not working. pydoc tries to access __name__ attribute of classes, so it raises attribute error. (actually it is not a class, but an instance only). So please increase the priority of this bug. And this case is also not working (same issue): class X: __bases__ = () x = X() -- Comment By: Raymond Hettinger (rhettinger) Date: 2005-08-24 10:55 Message: Logged In: YES user_id=80475 Ping, do you have a few minutes to look at this one and make sure its the right thing to do. -- Comment By: Facundo Batista (facundobatista) Date: 2005-05-31 00:45 Message: Logged In: YES user_id=752496 Don't know yet if it's a bug or not, but in Py2.4.1 inspect.isclass() is still returning True in these cases... -- Comment By: Stefan Schwarzer (sschwarzer) Date: 2005-01-28 22:14 Message: Logged In: YES user_id=383516 Hi Facundo The problem still exists in both Python 2.3.4 and 2.4. A possible test case is: import inspect import unittest class TestIsclass(unittest.TestCase): def test_instance_with_getattr(self): class Cls: def __getattr__(self, name): return not important obj = Cls() # obj is not a class self.failIf(inspect.isclass(obj)) -- Comment By: Facundo Batista (facundobatista) Date: 2005-01-15 23:20 Message: Logged In: YES user_id=752496 Please, could you verify if this problem persists in Python 2.3.4 or 2.4? If yes, in which version? Can you provide a test case? If the problem is solved, from which version? Note that if you fail to answer in one month, I'll close this bug as Won't fix. Thank you! .Facundo -- Comment By: Raymond Hettinger (rhettinger) Date: 2003-04-15 16:10 Message: Logged In: YES user_id=80475 Ping, if this change is made, will isclass() still be able to find extension classes? The addition of the hasattr(object, '__bases__') was made by you in ver 1.11 about two years ago. -- Comment By: Walter Dörwald (doerwalter) Date: 2003-04-15 15:31 Message: Logged In: YES user_id=89016 type(object) in (types.TypeType, types.ClassType) won't work with custom metaclasses. isinstance(object, (type, types.ClassType)) would be better. -- Comment By: Stefan Schwarzer (sschwarzer) Date: 2003-04-15 13:31 Message: Logged In: YES user_id=383516 Hello Raymond, thanks for your reply. In fact, I'm also not sure if it counts as a bug. I also suggested a patch (handle __getattr__ requests for __bases__ with an AttributeError) for for the SF project which causes/d the problem. I think, if there's a better way to decide on quot;class-nessquot; than now, the code in inspect should be changed. Fortunately, it doesn't have to be backward-compatible, because the module is always distributed with a certain interpreter version. -- Comment By: Raymond Hettinger (rhettinger) Date: 2003-04-15 06:06 Message: Logged
[ python-Bugs-1542949 ] idle in python 2.5c1 freezes on macos 10.3.9
Bugs item #1542949, was opened at 2006-08-19 01:51 Message generated for change (Comment added) made by diggableme You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1542949group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: IDLE Group: Python 2.5 Status: Open Resolution: None Priority: 6 Submitted By: David Strozzi (dstrozzi) Assigned to: Ronald Oussoren (ronaldoussoren) Summary: idle in python 2.5c1 freezes on macos 10.3.9 Initial Comment: Hi, I installed python 2.5b3 on a powerbook ppc laptop running macos 10.3.9 a few days ago. python and idle worked. Now I installed 2.5c1. python works fine from a terminal. When I start idle, it loads, puts up its menu bar, opens a shell window, displays usual startup info, and gives me a prompt. But, I can't type or get a cursor. Whenever I move the mouse over the idle window or menu bar, I get a spinning color wheel and can't do anything. I deleted the whole /library/python tree, reinstalled 2.5c1, and exactly the same thing happened. Oh, and I rebooted :) Not sure what is happening, or how to diagnose. -- Comment By: diggableme (diggableme) Date: 2006-09-09 17:18 Message: Logged In: YES user_id=1594326 I am a new user that is experiencing the same exact problem. I have OSX.3.9 and everytime I start IDLE, it freezes and the colorwheel somes up. When I view the console output, there are no errors or alert messages. I have also tried uninstalling and re-installing from the beginning with the same result. I have been using the instructions given at this site: http://www.python.org/download/mac/ desp I'm very interested to see if there is in fact a resolution to this problem. I'm at my wit's end. -dig -- Comment By: Ronald Oussoren (ronaldoussoren) Date: 2006-08-28 16:59 Message: Logged In: YES user_id=580910 I've created a new installer from the head of the release25-maint branch and that works correctly. I'm keeping this issue open because I want to investigate why 2.5c1 doesn't work while the current head of the 2.5 branch does work. -- Comment By: David Strozzi (dstrozzi) Date: 2006-08-28 15:48 Message: Logged In: YES user_id=1056922 Well, if there's anything I can do as a 10.3.9 user to test this, let me know. Too busy to delve into the python source code though... -- Comment By: Ronald Oussoren (ronaldoussoren) Date: 2006-08-28 15:22 Message: Logged In: YES user_id=580910 I can reproduce this on 10.3.9: IDLE starts and opens the interactive window, but then completely blocks (spinning cursor). If I start IDLE from the commandline (/Applications/MacPython\ 2.5/ IDLE.app/Contents/MacOS/IDLE) I get a message about 'console' not being a valid command name. That requires further looking into, but is a red herring for this particular problem, removing the Tk-console hiding code in macosxSupport.py results in the same behaviour, without any further output on the console as well. Upgrading aquatk to the latest version (8.4.10.0) on tcltkaqua.sf.net didn't help, IDLE still hangs (Duh, that's because there's a /System/Library/ Frameworks/Tk.framework, which means a user install won't be used for IDLE). The problem is also unrelated to my IDLE.app work, the same problem occurs when starting $prefix/lib/python2.5/idlelib/idle.py. According to gdb the IDLE process is handing in a semaphore call inside the Tcl mainloop. Time to get into serious debugging mode I guess :-( BTW. IDLE does work correctly on a 10.4.7 system. -- Comment By: Kurt B. Kaiser (kbk) Date: 2006-08-28 13:59 Message: Logged In: YES user_id=149084 Maybe priority should be higher? Hopefully Ronald has time to look at this; I don't have access to a Mac. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1542949group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1555496 ] Bug in the match function
Bugs item #1555496, was opened at 2006-09-09 22:02 Message generated for change (Tracker Item Submitted) made by Item Submitter You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1555496group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Regular Expressions Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: wojtekwu (wojtekwu) Assigned to: Gustavo Niemeyer (niemeyer) Summary: Bug in the match function Initial Comment: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import re as = re.compile((a|((a|b)*))) wynik = as.match(aabaa) wynik.end() 1 as = re.compilea|b)*)|a)) wynik = as.match(aabaa) wynik.end() 5 -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1555496group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1555496 ] Bug in the match function
Bugs item #1555496, was opened at 2006-09-09 20:02 Message generated for change (Comment added) made by gbrandl You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1555496group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Regular Expressions Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: wojtekwu (wojtekwu) Assigned to: Gustavo Niemeyer (niemeyer) Summary: Bug in the match function Initial Comment: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import re as = re.compile((a|((a|b)*))) wynik = as.match(aabaa) wynik.end() 1 as = re.compilea|b)*)|a)) wynik = as.match(aabaa) wynik.end() 5 -- Comment By: Georg Brandl (gbrandl) Date: 2006-09-09 20:06 Message: Logged In: YES user_id=849994 IMHO that's not a bug, since we have a leftmost alternative strategy, not a longest match. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1555496group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1555501 ] Please include pliblist for all plattforms
Bugs item #101, was opened at 2006-09-09 22:07 Message generated for change (Tracker Item Submitted) made by Item Submitter You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=101group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.5 Status: Open Resolution: None Priority: 5 Submitted By: Guido Guenther (guidog) Assigned to: Nobody/Anonymous (nobody) Summary: Please include pliblist for all plattforms Initial Comment: Hi, plistlib which is currently under ./Lib/plat-mac/plistlib.py is usefull on other platforms too (e.g. in apples calendar server which runs on OS X and Linux). Could this be moved to Lib/ for 2.5 so that other platforms can benefit from it too? Cheers, -- Guido -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=101group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1555496 ] Bug in the match function
Bugs item #1555496, was opened at 2006-09-09 16:02 Message generated for change (Comment added) made by tim_one You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1555496group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Regular Expressions Group: Not a Bug Status: Closed Resolution: Invalid Priority: 5 Submitted By: wojtekwu (wojtekwu) Assigned to: Gustavo Niemeyer (niemeyer) Summary: Bug in the match function Initial Comment: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import re as = re.compile((a|((a|b)*))) wynik = as.match(aabaa) wynik.end() 1 as = re.compilea|b)*)|a)) wynik = as.match(aabaa) wynik.end() 5 -- Comment By: Tim Peters (tim_one) Date: 2006-09-09 18:23 Message: Logged In: YES user_id=31435 That's right -- the first (leftmost) alternative that matches wins; same as Perl, etc etc. Closing as Not-A-Bug. -- Comment By: Georg Brandl (gbrandl) Date: 2006-09-09 16:06 Message: Logged In: YES user_id=849994 IMHO that's not a bug, since we have a leftmost alternative strategy, not a longest match. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1555496group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-780714 ] infinite __str__ recursion in thread causes seg fault
Bugs item #780714, was opened at 2003-07-31 10:37 Message generated for change (Comment added) made by loewis You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=780714group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: Python 2.3 Status: Open Resolution: Fixed Priority: 5 Submitted By: Stefan Gregory (stefan_gregory) Assigned to: Nobody/Anonymous (nobody) Summary: infinite __str__ recursion in thread causes seg fault Initial Comment: The following code reliably produces a segmentation fault under Solaris8 in Python2.3, Python2.2, Python2.1.3 and Python1.5. It produces a Bus Error when run on Python2.2 under OSX. Clearly it should produce a Python RuntimeError. import thread, time class Frog: def __str__(self): return str(self) f = Frog() thread.start_new_thread(str,(f,)) time.sleep(1000) This problem manifests in scenarios such as when you have 2 publishing objects (such as HTMLgen objects) A and B and you put A inside B and B inside A and each objects __str__ method calls its childrens __str__ methods and voila! (I hope this might be the reason my Zope server has been intermitently crashing for the past year or so though I have not found any recursive structures yet.) With Python2.3 gdb reports: vgetargskeywords (args=0x1bdaf0, keywords=0x0, format=0xd2579 quot;0:strquot;, kwlist=0xf7b4c, p_va=0xfed0C02c) at Python/getargs.c:1167 Though with Python2.1 it dies at line 330 in getargs.c. -- Comment By: Martin v. Löwis (loewis) Date: 2006-09-10 02:03 Message: Logged In: YES user_id=21627 I fail to see the problem. You have to change the recursion limit; if you do, you risk a crash, as the documentation says: http://docs.python.org/lib/module-sys.html This should be done with care, because a too-high limit can lead to a crash. With an unmodified recursionlimit in 2.4.3 on Windows, I get the expected RuntimeError. If it causes a crash on some system, it just means that the default recursion limit is too high for that platform (however, we don't seem to have a confirmation that the default recursion limit is too large for this application on any platform for Python 2.4 or 2.5). It is quite common that the system provides the main thread with a larger stack space than any additional thread, so it is not surprising that the stack overflow is detected on some system when the code is run in the main thread, yet crashes in an additional thread. The default recursion limit should be the conservative minimum of what the system minimally guarantees for any thread. It seems that the original problem has been fixed (although nobody apparently has tested Python 2.4 or 2.5 on Solaris8); I suggest to close this as fixed again. -- Comment By: Josiah Carlson (josiahcarlson) Date: 2006-08-16 09:42 Message: Logged In: YES user_id=341410 import sys sys.setrecursionlimit(1) class foo: ... def __str__(self): ... return str(self) ... import threading threading.Thread(target=foo().__str__).start() Kills 2.3, 2.4, and 2.5 on Windows, and 2.3 and 2.4 on linux (I can't test 2.5 on linux). Running in the main thread on Windows doesn't seem to be a big deal: import sys sys.setrecursionlimit(1) class foo: ... def __str__(self): ... return str(self) ... try: ... str(foo()) ... except Exception, why: ... print why ... Stack overflow Note that the above crashes 2.3 and 2.4 on Linux. This is still a bug, at least in maintenance on 2.4. Suggested reopen. -- Comment By: SourceForge Robot (sf-robot) Date: 2006-08-14 04:20 Message: Logged In: YES user_id=1312539 This Tracker item was closed automatically by the system. It was previously set to a Pending status, and the original submitter did not respond within 14 days (the time period specified by the administrator of this Tracker). -- Comment By: Georg Brandl (gbrandl) Date: 2006-07-30 13:16 Message: Logged In: YES user_id=849994 Under 2.5, I get a runtime error now, so this might be fixed. -- Comment By: Brett Cannon (bcannon) Date: 2003-08-05 21:22 Message: Logged In: YES user_id=357491 Forgot to mention that Modules/threadmodule.c has thread_PyThread_start_new_thread which uses Python/ thread_*.h's PyThread_start_new_thread for executing threads; the '*' is replaced with the threading library used on your platform. OS X should use thread_pthread.h (I think). -- Comment
[ python-Bugs-1548332 ] whichdb too dumb
Bugs item #1548332, was opened at 2006-08-29 07:51 Message generated for change (Comment added) made by loewis You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1548332group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Extension Modules Group: Python 2.5 Status: Closed Resolution: Invalid Priority: 5 Submitted By: Curtis Doty (dotysan) Assigned to: Nobody/Anonymous (nobody) Summary: whichdb too dumb Initial Comment: On my system with db4, I noticed that whichdb doesn't know anything about more recent database types created by the bsddb module. Python 2.4.3 (#1, Jun 13 2006, 11:46:08) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type help, copyright, credits or license for more information. from whichdb import * import bsddb dbfile= hash bsddb.hashopen( dbfile) {} whichdb( dbfile) 'dbhash' # yay ... dbfile= btree bsddb.btopen( dbfile) {} whichdb( dbfile) '' # bah ... dbfile= recno bsddb.rnopen( dbfile) {} whichdb( dbfile) '' # humbug! It looks like both these database types share: #define DB_BTREEMAGIC 0x053162 So this might be a start: --- Python-2.5c1/Lib/whichdb.py.orig 2005-02-05 22:57:08.0 -0800 +++ Python-2.5c1/Lib/whichdb.py 2006-08-28 13:46:57.0 -0700 @@ -109,6 +109,10 @@ if magic in (0x00061561, 0x61150600): return dbhash +# Check for binary tree +if magic == 0x00053162: +return btree + # Unknown return But alas, I'm not clear on the best way to differentiate between btree and recno. The above example is on 2.4 but persists in 2.5. -- Comment By: Martin v. Löwis (loewis) Date: 2006-09-10 02:08 Message: Logged In: YES user_id=21627 It is not the job of whichdb to recognize certain database types created by the bsddb module. Instead, as the doc string says Guess which db package to use to open a db file. The return value of whichdb is a *module name*. Since btree is not a module name, the proposed change is incorrect. Closing as invalid. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1548332group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com