Re: Arrays? (Or lists if you prefer)
[EMAIL PROTECTED] wrote: > Interesting. Could I do . . . let's say > > b = [range(range(3)] > > for a three-dimensional array? >>> [range(range(3))] Traceback (most recent call last): File "", line 1, in TypeError: range() integer end argument expected, got list. if your mail program is easier to reach than your Python interpreter window, something's wrong with your setup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays? (Or lists if you prefer)
From: <[EMAIL PROTECTED]> wrote: 8<--- > So: > Way to do SIMPLE array, either internally or externally, with Python, > please. to help you see it - here is a simple 3 row by 3 column list: myarray = [[1,2,3],[4,5,6],[7,8,9]] the first "row" is myarray[0] - ie the list [1,2,3] the middle element is myarray[1][1] - ie 5 - row 1, col 1. the last element in the first row is myarray[0][2] - ie 3 play with it at the interactive prompt... HTH - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: implementation of "in" that returns the object.
Jorge Vargas wrote: > Hi > > I need to check if an object is in a list AND keep a reference to the > object I have done it this way but is there a better one? > > >>> def inplusplus(value,listObj): > ... for i in listObj: > ... if i is value: > ... return value > ... return False > ... > >>> l = [1,2,3,4] > >>> print inplusplus(2,l) > 2 > >>> print inplusplus(9,l) > False > >>> print inplusplus(1,l) > 1 > >>> l.append(0) > >>> print inplusplus(0,l) > 0 You mentioned a ist of objects. The following example will return the actual object matched in the ist allowing you to later change any mutable object returned and see the change reflected in the list: >>> x = [[0], [1], [2]] >>> y = [1] >>> def inref(val, lst): ... try: ... return lst[ lst.index(val) ] ... except ValueError: ... return False ... >>> z = inref(y, x) >>> z [1] >>> z[0] = 33 >>> z [33] >>> x [[0], [33], [2]] Hope this helps - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: multythreading app memory consumption
Dennis Lee Bieber wrote: > On Mon, 23 Oct 2006 03:31:28 +0400, Roman Petrichev <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > >> Hi folks. >> I've just faced with very nasty memory consumption problem. >> I have a multythreaded app with 150 threads which use the only and the >> same function - through urllib2 it just gets the web page's html code >> and assigns it to local variable. On the next turn the variable is >> overritten with another page's code. At every moment the summary of >> values of the variables containig code is not more than 15Mb (I've just >> invented a tricky way to measure this). But during the first 30 minutes >> all the system memory (512Mb) is consumed and 'MemoryError's is arising. >> Why is it so and how can I limit the memory consumption in borders, say, >> 400Mb? Maybe there is a memory leak there? >> Thnx >> > How much stack space gets allocated for 150 threads? Actually I don't know. How can I get to know this? >> Q = Queue.Queue() >> for i in rez: #rez length - 5000 > > Can't be the "test code" as you don't show the imports or where > "rez" is defined. Isn't it clear that "rez" is just a list of 5000 urls? I cannot place it here, but believe me all of them are not big - "At every moment the summary of values of the variables containig code is not more than 15Mb" Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter--does anyone use it for sophisticated GUI development?
From: James Stroud <[EMAIL PROTECTED]> To: [email protected] Date: Thu, 19 Oct 2006 20:34:26 GMT Subject: Re: Tkinter--does anyone use it for sophisticated GUI development? Kevin Walzer wrote: > I'm a Tcl/Tk developer who has been working, slowly, at learning Python, > in part because Python has better support for certain kinds of > applications that I want to develop than Tcl/Tk does. Naturally, I > thought that I would use Tkinter as the GUI for these programs. However, > in doing research into GUI development techniques, sample code, and > showcase applications, what has struck me is how little sophisticated > GUI development seems to be done in Tkinter as compared to, say, > wxPython. I've found plenty of tutorials on how to do basic GUI stuff > with Tkinter, but that stuff pretty much ends with the core Tk widgets > (buttons, entry fields, scrollbars, and menu items). > > Coming from Tcl/Tk, where there are a huge number of extension packages > to enhance the Tk widgets and which allow you to make really polished > GUI's, I'm struck mainly by how little of this stuff has made it over > into Tkinter/Python. For instance, I've developed several Tcl > applications that use the core Tk widgets, the Tile theming package, the > Bwidget set (great tree widget and listbox, which allows you to embed > images), and tablelist (an extremely flexible muti-column listbox > display). I've found Python wrappers for some of this stuff, but almost > no documentation on how to use them, and very little in the way of > actual applications making use of them--which is itself a red flag. And > most of the pure-Python extension stuff that I've found, such as Python > megawidgets, is pretty dated/ugly and lags far behind the comparable > stuff on the Tcl side. > > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? I've used Tkinter + bwidgets for Crescendo which you can find in this page http://godson.auroinfo.com/downloads you can look at the screen shots of Crescendo there. We have a wrapper for Tile written by Franklin a long time ago but his site is down currently. here is the google cached version of that page http://72.14.209.104/search?hl=en&q=cache%3Ahttp%3A%2F%2Fmfranklin.is-a-geek.org%2Fdocs%2FTile%2Findex.html&btnG=Search&meta= Bwidgets wrapper of python has not all widgets that Bwidgets offers, i've tried changing the file __init__.py its pretty easy. Regards, Godson. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems trying to override __str__ on path class
Mike Krell wrote: > Peter Otten <[EMAIL PROTECTED]> wrote in > news:[EMAIL PROTECTED]: > >> I get >> >> np: "overridden __str__: c:/mbk/test" >> str(np): "overridden __str__: c:/mbk/test" >> overridden __str__: overridden __str__: c:/mbk/test/appendtest > > Hmmm. I guess you're not running under windows, since normpath() > converts / to \ on windows. I wonder if that's part of the problem. > > >> Are you using the latest version of the path module? > > My path.py says it's 2.1, which is the latest according to the site. > > Older versions >> implied a Path() call in the __div__() operator which would explain at >> least the output you get for >> >> print np / 'appendtest' > > You've lost me here. What do you mean about "implied a Path() call"? > Here is the definition of __div__ from path.py: > > ''' > # The / operator joins paths. > def __div__(self, rel): > """ fp.__div__(rel) == fp / rel == fp.joinpath(rel) > > Join two path components, adding a separator character if > needed. > """ > return self.__class__(os.path.join(self, rel)) > ''' >From http://www.jorendorff.com/articles/python/path/changes.html: """ This page describes recent changes to the Python path module. 2.1 [...] Better support for subclassing path. All methods that returned path objects now respect subclassing. Before: type(PathSubclass(s).parent) is path Now: type(PathSubclass(s).parent) is PathSubclass """ So my assumption was that you are using a pre-2.1 version of path. I suggest that you double-check that by inserting a print path.__version__ into the code showing the odd behaviour before you start looking for more exotic causes. > I still don't understand the TypeError in the delegation case. For newstyle classes a = A() a / 42 # or any other operation implemented via __xxx__() (unlike a.__div__) will only look into the class for a __div__() special method and ignore methods defined in the instance or via the __getattr__() mechanism. For delegation to work you need (untested) class NormPath(object): def __div__(self, other): return self.__class__(self._path / other) # ... Peter -- http://mail.python.org/mailman/listinfo/python-list
is it a bug ?
hello can you explain to me what happened: class toto(object): eq = float.__eq__ t = toto() getattr(t,'eq') TypeError: descriptor '__eq__' for 'float' objects doesn't apply to 'toto' object -- http://mail.python.org/mailman/listinfo/python-list
Re: is it a bug ?
Sylvain Ferriol wrote: > can you explain to me what happened: > > class toto(object): >eq = float.__eq__ > > t = toto() > > getattr(t,'eq') > TypeError: descriptor '__eq__' for 'float' objects doesn't apply to > 'toto' object float.__eq__ is probably implemented in C and its operation will make sense only for instances of float or subclasses of float. Try >>> class Toto(float): ... eq = float.__eq__ ... >>> Toto().eq(42) False Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: is it a bug ?
Sylvain Ferriol wrote: > can you explain to me what happened: > > class toto(object): >eq = float.__eq__ > > t = toto() > > getattr(t,'eq') > TypeError: descriptor '__eq__' for 'float' objects doesn't apply to > 'toto' object I'd say the error message explains it pretty well. what did you expect this to do? -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing Unicode and string
I didn't mean that the *assignment* should raise exception. I mean that any string constant that cannot be decoded using sys.getdefaultencoding() should be considered a kind of syntax error. I agree of course with the argument of backward compatibility, which means that my suggestion is for Python 3.0, not earlier. And I admit that my suggestion lacks a solution for Neil Cerutti's use of non-decodable simple strings. And I admit that there are certainly more competent people than me to think about this question. I just wanted to throw my penny into the pond :-) Luc Fredrik Lundh wrote: > [EMAIL PROTECTED] wrote: > > > Suggestion: shouldn't an error raise already when I try to assign s2? > > variables are not typed in Python. plain assignment will never raise an > exception. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: is it a bug ?
Fredrik Lundh a écrit : > Sylvain Ferriol wrote: > >> can you explain to me what happened: >> >> class toto(object): >>eq = float.__eq__ >> >> t = toto() >> >> getattr(t,'eq') >> TypeError: descriptor '__eq__' for 'float' objects doesn't apply to >> 'toto' object > > > I'd say the error message explains it pretty well. what did you expect > this to do? > i just want a class variable named 'eq', i could understand if its name was '__eq__'. class toto(object): __eq__ = float.__eq__ why i can not create some class variables like this ? class toto(object): a= float.__eq__ b= str.__eq__ .. > > -- http://mail.python.org/mailman/listinfo/python-list
Handling emails
*** Your mail has been scanned by InterScan MSS. *** Hello, I'd like to ask some clue to move further on my project :-) The purpose would be to gather all emails (local and remote ones) to do some backup. I've tried to get ideas by reading all about the modules enclose with python, but neither email framework nor mailbox give me the idea how to handle *one* email complete of payload and attachment (if any). This purpose will give me chance to avoid duplicates and I suppose to achieve the grade of making a maildir o mbox file. It's welcome to point me to useful information. Surely I'm not asking ready-made solution :-). BTW sorry to whom feel hurt by the "virus scan banner". That's not generated by me, but rather by my ISP. I'll try to contact my ISP and ask to move it off from the email body. F -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging
*** Your mail has been scanned by InterScan MSS. *** On Saturday 21 October 2006 23:43, R. Bernstein wrote: > (I think all of this is the case also with pdb, but someone might > check on this; it's possible breakpoints in pdb start from 0 instead > of 1 as is the case in gdb/pydb.) Thank you for your details. The pdb that I'm talking about, can be found in /usr/lib/python2.4/pdb.py (an C:\python2.4\lib\pdb.py for the win32 version). I'll give a look to pydb site... The previous post I might have missed some explaination on my proceeding. I'd say that I'm testing a small program under pdb control (python /usr/lib/python2.4/pdb.py ./myprog.py). So pdb will load myprog and stop the first line code. Once I'm at the pdb command line I can issue the commands available inside the pdb itself. Concerning the mentioned BP function I meant to set a counter/function which let the BP run until reach the true condition. Then "condition" is one of the pdb commands which let add a conditon to a BP. The reference Manual gives information for all the pdb functions, but aren't detailed, specially on how to set up BP conditions, like countdown, timed and camparison conditions. Hope I've been clear this time :-) F -- http://mail.python.org/mailman/listinfo/python-list
Re: is it a bug ?
Peter Otten a écrit : > Sylvain Ferriol wrote: > > >>can you explain to me what happened: >> >>class toto(object): >> eq = float.__eq__ >> >>t = toto() >> >>getattr(t,'eq') >>TypeError: descriptor '__eq__' for 'float' objects doesn't apply to >>'toto' object > > > float.__eq__ is probably implemented in C and its operation will make sense > only for instances of float or subclasses of float. Try > > class Toto(float): > > eq = float.__eq__ > > Toto().eq(42) > > False > i can not use it because: class toto(float): def __init__(self,a=None):pass t=toto(a=3) TypeError: 'a' is an invalid keyword argument for this function > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: is it a bug ?
Sylvain Ferriol wrote: > i just want a class variable named 'eq' so why are you assigning another class' descriptor to it? descriptors are bound to types, and only works properly if used with the type they were created for. > why i can not create some class variables like this ? > > class toto(object): >a= float.__eq__ >b= str.__eq__ but given that "toto" is neither a float nor a str, what do you expect that code to *do*? is this some "programming by random mutation" exercise? -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing Unicode and string
In <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote: > I didn't mean that the *assignment* should raise exception. I mean that > any string constant that cannot be decoded using > sys.getdefaultencoding() should be considered a kind of syntax error. Why? Python strings are *byte strings* and bytes have values in the range 0..255. Why would you restrict them to ASCII only? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: sending vim text through Python filter
BartlebyScrivener wrote: > Hello, > > I'm sure this is my fault or some Windows snafu. But using gvim 7.0 on It's a bug in Windows. Try doing "sort.py < test.txt" from the command line, and you'll get the same error. Try "python sort.py < test.txt" and it should work fine. Apparently cmd.exe can't pick up the registered file extensions. > I'm sending standard text with the vim command :%!sort.py You'll have to use :%!python sort.py to get the filter to work. -- http://mail.python.org/mailman/listinfo/python-list
Re: is it a bug ?
Sylvain Ferriol wrote: >class Toto(float): >> >> eq = float.__eq__ >> >> >Toto().eq(42) >> >> False >> > i can not use it because: > class toto(float): > def __init__(self,a=None):pass > > t=toto(a=3) > TypeError: 'a' is an invalid keyword argument for this function Override __new__() then: >>> class Toto(float): ... def __new__(cls, a=None): ... if a is None: ... a = 42 ... return float.__new__(cls, a) ... def __init__(cls, a=None): ... print "random message containing", a ... >>> Toto() random message containing None 42.0 >>> Toto(42) random message containing 42 42.0 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python scripts in Windows Explorer
MC wrote: > I use this little batch: > > @echo off > cd \dev\python > viewarg.py %* I try that (with viewarg.py renamed, obviously), and get this error: "'defines.py' is not recognized as an internal or external command, operable program or batch file." defines.py is in the same directory as the batch file, but cannot be executed like this. Double-clicking on it works, as expected. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python scripts in Windows Explorer
Gabriel Genellina wrote: > At Friday 20/10/2006 12:20, Ben Sizer wrote: > > >I'd like to be able to drag a file onto a Python script in Windows > >Explorer, or send that file to the script via the Send To context-menu > >option, so I can then process that file via sys.argc. > > > >Unfortunately, I can't drag items onto the Python script, because > >Windows doesn't recognise that the script is executable (unless I > >double-click it, upon which it runs as usual, without the command line > >parameter of course) > > Create a shortcut and drop the file over it. Doesn't work; the mouse cursor changes to the "not permitted" sign and when you release the mouse, nothing happens. > >and won't set it as a drop target. And it won't > >even appear in the Send To menu after the usual steps are taken to get > >it there. > > Same here: put a shortcut to the script on your SendTo folder > (wherever it resides) That is what I meant by 'the usual steps'. :) It doesn't work. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
The Mythical Man-month's pdf file
Hi, Does anyone have the .pdf file of the book THE MYTHICAL MAN-MONTH? Then could you please send it to me( [EMAIL PROTECTED] )? Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging
Fulvio wrote:
> ***
> Your mail has been scanned by InterScan MSS.
> ***
>
>
> On Saturday 21 October 2006 23:43, R. Bernstein wrote:
>> (I think all of this is the case also with pdb, but someone might
>> check on this; it's possible breakpoints in pdb start from 0 instead
>> of 1 as is the case in gdb/pydb.)
>
> Thank you for your details. The pdb that I'm talking about, can be found
> in /usr/lib/python2.4/pdb.py (an C:\python2.4\lib\pdb.py for the win32
> version).
> I'll give a look to pydb site...
>
> The previous post I might have missed some explaination on my proceeding. I'd
> say that I'm testing a small program under pdb control
> (python /usr/lib/python2.4/pdb.py ./myprog.py). So pdb will load myprog and
> stop the first line code.
> Once I'm at the pdb command line I can issue the commands available inside
> the
> pdb itself. Concerning the mentioned BP function I meant to set a
> counter/function which let the BP run until reach the true condition.
> Then "condition" is one of the pdb commands which let add a conditon to a BP.
> The reference Manual gives information for all the pdb functions, but aren't
> detailed, specially on how to set up BP conditions, like countdown,
"""
ignore bpnumber [count]
Sets the ignore count for the given breakpoint number. If count is
omitted, the ignore count is set to 0. A breakpoint becomes active when
the ignore count is zero. When non-zero, the count is decremented each
time the breakpoint is reached and the breakpoint is not disabled and
any associated condition evaluates to true.
"""
> timed
saw nothing about this one... but perhaps with
> and
> camparison conditions.
"""
condition bpnumber [condition]
Condition is an expression which must evaluate to true before the
breakpoint is honored. If condition is absent, any existing condition is
removed; i.e., the breakpoint is made unconditional.
"""
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list
Re: The Mythical Man-month's pdf file
<[EMAIL PROTECTED]> wrote: > Does anyone have the .pdf file of the book THE MYTHICAL MAN-MONTH? start here: http://www.amazon.com/dp/0201835959 -- http://mail.python.org/mailman/listinfo/python-list
ANN: $500 prize for best Leo slideshows
A prize of $500 prize is hereby offered to the person or persons who can create the best slide shows (using Leo's slideshow plugin) that introduces Leo to newbies. What is Leo, you ask? Home: http://webpages.charter.net/edreamleo/front.html Tutorial: http://webpages.charter.net/edreamleo/leo_TOC.html FAQ: http://webpages.charter.net/edreamleo/FAQ.html Wiki: http://leo.zwiki.org/FrontPage 1. Prize fund The total prize fund is $500. Prizes will be awarded solely at the discretion of Edward K. Ream. The prize fund may be split among contestants, and the total prize fund will be distributed only if the number and quality of submissions warrant it. 2. Format of entries Entries should be a *single* Leo outline. This outline may contain multiple slideshows. Multiple entries are allowed. Entries must be accompanied by your name, address and email address. 3. Ownership of entries All entries become the property of Edward K. Ream and will be distributed under the terms of Leo's Open Source license. 4. Criteria for awards Prizes will be awarded on how useful the slideshow is in helping newbies understand Leo. To be considered for an award, an entry must show substantial work. I'll also consider creativity, originality, etc. I'll also look favorably on extensions to the slideshow plugin if such extensions materially improve the presentation. 5. Duration of contest The contest shall end December 11, 2006. The contest may be extended at the sole discretion of Edward K. Ream, but in no event shall the contest continue past February 2, 2007. Prizes will be awarded within one week of the close of the contest. Winners will be announced on Leo's Open Discussion Forum: http://sourceforge.net/forum/forum.php?forum_id=10226 Edward Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python scripts in Windows Explorer
Ben Sizer wrote: > > Create a shortcut and drop the file over it. ... > That is what I meant by 'the usual steps'. :) It doesn't work. Alter the target of the shortcut to something like: C:\Python25\python.exe C:\0\sort_test.py and drag and drop should work, with the filename of the dragged file being sent as a script argument. -- http://mail.python.org/mailman/listinfo/python-list
Re: Customize the effect of enumerate()?
Simon Forman wrote: > Dustan wrote: > > Can I make enumerate(myObject) act differently? > > > > class A(object): > > def __getitem__(self, item): > > if item > 0: > > return self.sequence[item-1] > > elif item < 0: > > return self.sequence[item] > > elif item == 0: > > raise IndexError, "Index 0 is not valid." > > else: > > raise IndexError, "Invalid Index." > > def __iter__(self): return iter(self.sequence) > > That final else clause is a little funny...What kind of indices are > you expecting that will be neither less than zero, greater than zero, > or equal to zero? I'm not 'expecting' anything to reach that clause, but it is a good catch-all if I forget something or have a bug somewhere. > > Why the funny behavior, you ask? For my class A, it doesn't make sense > > to number everything the standard programming way. Of course, if > > someone uses enumerate, it's going to number the items the same way as > > ever. Is there any way to modify that behavior, any special function to > > set? There doesn't appear to be, according to the docs, but it never > > hurts to make sure. > > You can write your own enumerate function and then bind that to the > name 'enumerate'. Except that my program is supposed to be treated as a module with tools to do certain things. I certainly can't control whether a 3rd party programmer uses "import myModule" or "from myModule import *". I haven't gotten around to doing it yet, but I'm pretty sure I'm planning on taking Paul Rubin's course of action - make a method (iteritems or similar) that will enumerate correctly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Customize the effect of enumerate()?
"Dustan" wrote: > Except that my program is supposed to be treated as a module with tools > to do certain things. I certainly can't control whether a 3rd party > programmer uses "import myModule" or "from myModule import *". anything can happen if people use "from import *" in the wrong way, so that's not much of an argument, really. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is x.f() <==>MyClass.f(x) a kind of algebraic structure?
steve wrote: > I thought that when read Guido van Rossum' Python tutorial.What can we > think that? That x.f() is equivalent to MyClass.f(x)? (Consider restating questions in the body of messages to maintain context, by the way.) Why not try it out? >>> class MyClass: ... def f(self): ... print "I am", self ... >>> x = MyClass() >>> x.f() I am <__main__.MyClass instance at 0x2a955d5b00> >>> MyClass.f(x) I am <__main__.MyClass instance at 0x2a955d5b00> Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: sending vim text through Python filter
> You'll have to use :%!python sort.py to get the filter to work. Damn. I should've thought of that. Then again, why would I when sort.py works fine from the windows commandline. Thanks a lot! That does the trick. rd -- http://mail.python.org/mailman/listinfo/python-list
Collate Module
I've made a few more changes to my little collate module.
There might be better ways to handle the options, or better choices for the
options themselves. I tried to keep it as general as possible.
I think it should work with Unicode now too.
Any suggestions in making it faster will be appreciated.
Any minor improvements to wording, spelling, etc.. are also welcome.
Many thanks for all the terrific feed back and suggestions!
Cheers,
Ron
---start---
"""
Collate.py - Sorts lists of strings in various ways depending
options and locale.
Class: Collate(option_string)
Functions:
collate(text, option_string) -> collate in place
result = collated(text, option_string) -> get a collated copy
To use collate with your user locale you need to call setlocale()
before collating:
locale.setlocale(locale.LC_ALL, '')
This will set several global variables such as string
constants, time and monitary formats, as well as numerical
formatting to your user Locale. Instead of '', you can also
specify a specific locale.
The setttings can be restored back to the default 'C' locale with
the following:
locale.setlocale(locale.LC_ALL, 'C')
Example:
locale.setlocale(locale.LC_ALL, '')
tlist = [ 'Fruit', 'fruit-apple', 'fruit-bannana',
'nut-pecan', 'Nut' ]
collate(tlist, 'caps_first hyphen_as_space')
* For more examples see doctests in function test().
Author: Ron Adam, [EMAIL PROTECTED]
"""
import re
import locale
import string
__version__ = '0.03 (pre-alpha) 10/23/2006'
class Collate(object):
""" A general purpose collator class.
Use: collate(text, option_string)
result = collated(text, option_string)
text = a list of strings
opton_string = a string of space separated options.
Collation can be modified with the following options:
CAPS_FIRST -> Aaa, aaa, Bbb, bbb
LOWERCASE_FIRST -> aaa, Aaa, bbb, Bbb
HYPHEN_AS_SPACE -> hyphens separate words
PERIOD_AS_SPACE -> Periods separate numerals
NUMERICAL -> Digit sequences as numerals
IGNORE_COMMAS -> Allows commas in numerals
UNDERSCORE_AS_SPACE -> Underscore as white space
IGNORE_LEADING_WS -> Disregard leading white space
"""
options = ( 'CAPS_FIRST', 'LOWERCASE_FIRST', 'NUMERICAL',
'HYPHEN_AS_SPACE', 'UNDERSCORE_AS_SPACE',
'IGNORE_LEADING_WS', 'IGNORE_COMMAS', 'PERIOD_AS_SPACE' )
def __init__(self, flags=""):
locale_conv = locale.localeconv()
self.encoding = locale.getpreferredencoding()
self.dpoint = locale_conv['decimal_point']
self.thsep = locale_conv['thousands_sep']
pattern = ''.join([r'([\d\\', self.dpoint, r']*|\D*)'])
self.numrex = re.compile(pattern, re.LOCALE)
if flags:
flags = flags.upper().split()
for value in flags:
if value not in self.options:
raise ValueError, 'Invalid option: %s' % value
txtable = []
if 'HYPHEN_AS_SPACE' in flags:
txtable.append(('-', ' '))
if 'UNDERSCORE_AS_SPACE' in flags:
txtable.append(('_', ' '))
if 'PERIOD_AS_SPACE' in flags:
txtable.append(('.', ' '))
if 'IGNORE_COMMAS' in flags:
txtable.append((',', ''))
self.txtable = txtable
self.capsfirst = (
sorted(['A','a'], key=locale.strxfrm) == ['A', 'a']
)
self.flags = flags
def transform(self, s):
""" Transform a string for collating.
"""
if type(s) is unicode:
s = s.encode(self.encoding, 'replace')
if not self.flags:
return locale.strxfrm(s)
for a, b in self.txtable:
s = s.replace(a, b)
if 'IGNORE_LEADING_WS' in self.flags:
s = s.lstrip()
if 'CAPS_FIRST' in self.flags and not self.capsfirst:
s = s.swapcase()
if 'LOWERCASE_FIRST' in self.flags and self.capsfirst:
s = s.swapcase()
if 'NUMERICAL' in self.flags:
slist = self.numrex.split(s)
for i, x in enumerate(slist):
if x: # slist may contain null strings
# inlined local.atof()
if self.thsep:
xx = x.replace(self.thsep, '')
if self.dpoint:
xx = xx.replace(self.dpoint, '.')
try:
slist[i] = float(xx)
except:
slist[i] = locale.strxfrm(x)
return slist
ret
Re: Customize the effect of enumerate()?
On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote:
> Dustan wrote:
>> Can I make enumerate(myObject) act differently?
>>
>> class A(object):
>> def __getitem__(self, item):
>> if item > 0:
>> return self.sequence[item-1]
>> elif item < 0:
>> return self.sequence[item]
>> elif item == 0:
>> raise IndexError, "Index 0 is not valid."
>> else:
>> raise IndexError, "Invalid Index."
>> def __iter__(self): return iter(self.sequence)
>
> That final else clause is a little funny...What kind of indices are
> you expecting that will be neither less than zero, greater than zero,
> or equal to zero?
Possible a NaN value? Maybe a class instance with strange comparison
methods?
Personally, I don't like the error message. "Invalid index" doesn't really
tell the caller what went wrong and why it is an invalid index. If I were
programming that defensively, I'd write:
if item > 0:
return self.sequence[item-1]
elif item < 0:
return self.sequence[item]
elif item == 0:
raise IndexError, "Index 0 is not valid."
else:
print repr(item)
raise ThisCanNeverHappenError("Congratulations! You've discovered "
"a bug that can't possibly occur. Contact the program author for "
"your reward.")
I know some programmers hate "Can't happen" tests and error messages, but
if you are going to test for events that can't possibly happen, at least
deal with the impossible explicitly!
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python and CMS
Kjell Magne Fauske enlightened us with: > I recommend taking a look at Django [1]. It is not a CMS right out > of the box, but writing one using the Django framework is not that > difficult. Django is my favourite as well. It's very easy to start building a dynamic website. Sybren -- Sybren Stüvel Stüvel IT - http://www.stuvel.eu/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Attempting to parse free-form ANSI text.
Paul McGuire wrote:
> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message
> news:[EMAIL PROTECTED]
>
>> Alright... I am attempting to find a way to parse ANSI text from a
>> telnet application. However, I am experiencing a bit of trouble.
>>
>> What I want to do is have all ANSI sequences _removed_ from the output,
>> save for those that manage color codes or text presentation (in short,
>> the ones that are ESC[#m (with additional #s separated by ; characters).
>> The ones that are left, the ones that are the color codes, I want to
>> act on, and remove from the text stream, and display the text.
>>
>>
> Here is a pyparsing-based scanner/converter, along with some test code at
> the end. It takes care of partial escape sequences, and strips any
> sequences of the form
> "[##;##;...", unless the trailing alpha is 'm'.
> The pyparsing project wiki is at http://pyparsing.wikispaces.com.
>
> -- Paul
>
> from pyparsing import *
>
>
snip
>
>
> test = """\
> This is a test string containing some ANSI sequences.
> Sequence 1: ~[10;12m
> Sequence 2: ~[3;4h
> Sequence 3: ~[4;5m
> Sequence 4; ~[m
> Sequence 5; ~[24HNo more escape sequences.
> ~[7""".replace('~',chr(27))
>
> leftOver = processInputString(test)
>
>
> Prints:
> This is a test string containing some ANSI sequences.
> Sequence 1:
>
>
I doubt we should concatenate numbers.
> Sequence 2:
>
> Sequence 3:
>
>
> Sequence 4;
>
>
> Sequence 5;
> No more escape sequences.
>
>
>
>
>
Another one of Paul's elegant pyparsing solutions. To satisfy my own
curiosity, I tried to see how SE stacked up and devoted more time than I
really should to finding out. In the end I don't know if it was worth
the effort, but having made it I might as well just throw it in.
The following code does everything Mike needs to do, except interact
with wx. It is written to run standing alone. To incorporate it in
Mike's class the functions would be methods and the globals would be
instance attributes. Running it does this:
>>> chunk_1 = """This is a test string containing some ANSI sequences.
Sequence 1 Valid code, invalid numbers: \x1b[10;12mEnd of sequence 1
Sequence 2 Not an 'm'-code: \x1b[30;4;77hEnd of sequence 2
Sequence 3 Color setting code: \x1b[30;45mEnd of sequence 3
Sequence 4 Parameter setting code: \x1b[7mEnd of sequence 4
Sequence 5 Color setting code spanning calls: \x1b[3"""
>>> chunk_2 = """7;42mEnd of sequence 5
Sequence 6 Invalid code: \x1b[End of sequence 6
Sequence 7 A valid code at the end: \x1b[9m
"""
>>> init ()
>>> process_text (chunk_1)
>>> process_text (chunk_2)
>>> print output
This is a test string containing some ANSI sequences.
Sequence 1 Valid code, invalid numbers: >>! Ignoring unknown number 10
!<< >>! Ignoring unknown number 12 !<< End of sequence 1
Sequence 2 Not an 'm'-code: End of sequence 2
Sequence 3 Color setting code: >>setting foreground BLACK<< >>setting
background MAGENTA<< End of sequence 3
Sequence 4 Parameter setting code: >>Calling parameter setting function
7<< End of sequence 4
Sequence 5 Color setting code spanning calls: >>setting foreground
GREY<< >>setting background GREEN<< End of sequence 5
Sequence 6 Invalid code: nd of sequence 6
Sequence 7 A valid code at the end: >>Calling parameter setting
function 9<<
###
And here it goes:
def init ():
# To add to AnsiTextCtrl.__init__ ()
import SE # SEL is less import overhead but doesn't have
interactive development features (not needed in production versions)
global output #-> For testing
global Pre_Processor, digits_re, Colors, truncated_escape_hold #
global -> instance attributes
# Screening out all ansi escape sequences except those controlling color
grit = '\n'.join (['(%d)=' % i for i in range (128,255)]) + ' (13)= '
# Regular expression r'[\x80-\xff\r]' would work fine but is four
times slower than 127 fixed definitions
all_escapes = r'\x1b\[\d*(;\d*)*[A-Za-z]'
color_escapes = r'\x1b\[\d*(;\d*)*m'
Pre_Processor = SE.SE ('%s ~%s~= ~%s~==' % (grit, all_escapes,
color_escapes)) # SEL.SEL for production
# 'all_escapes' also matches what 'color_escapes' matches. With
identical regular expression matches it is the last definitions that
applies. Other than that, the order of definitions is irrelevant to
precedence.
# Isolating digits.
digits_re = re.compile ('\d+')
# Color numbers to color names
Colors = SE.SE ('''
30=BLACK40=BLACK
31=RED 41=RED
32=GREEN42=GREEN
33=YELLOW 43=YELLOW
34=BLUE 44=BLUE
35=MAGENTA 45=MAGENTA
36=CYAN 46=CYAN
37=GREY 47=GREY
39=GREY 49=BLACK
''')
truncated_escape_hold = '' #-> self.truncated_escape_hold
output= '' #-> For testing only
# What follows replaces all others of Mike's methods
def process_text (text):
global output #-> For testing
global trunca
Script to count files in a folder
Dear all, We have a multi-platform application(Windows-Linux). Linux part of our application is writing some input and trigger files on the a shared drive. What I want to do is to be able to count the occurence of these trigger files. lets say my file is file.start A batch file creates this file and deletes that file in the same loop. This file is intended to start the reading of an input file. After it is read batch file deletes this file automatically and on the next loop it will be written and deleted again. With this script I have to count the occurences of the file on this specific folder. I did not have the time to think on it but maybe you can give me some ideas on that. And btw, I am not an expert in scirpting. I am trying to learn Python but this task is a little bit over my head. Any help or thoughts are appreciated. With best regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and CMS
Hi, check out Plone atop Zope. http://plone.org regards, KMOn 10/23/06, Sybren Stuvel <[EMAIL PROTECTED]> wrote: Kjell Magne Fauske enlightened us with:> I recommend taking a look at Django [1]. It is not a CMS right out > of the box, but writing one using the Django framework is not that> difficult.Django is my favourite as well. It's very easy to start building adynamic website.Sybren--Sybren Stüvel Stüvel IT - http://www.stuvel.eu/--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Book about database application development?
> and perhaps a fairly elementary datagrid widget is what is being sought. *snip* > I'm sure other people can provide links to resources for other toolkits > and frameworks. Err, slight misunderstanding. I am _not_ searching for a toolkit or framework for database applications. What I am searching for is a _book_ (or other learning material) about how to implement database applications. See subject. I want to learn this because I want to be able to - understand the existing frameworks and be able to choos ethe one that suits my needs best - be able to fix bugs - be able to implement missing things myself - be able to do things "from scratch" if nothing else helps. I mentioned Delphi just as an example for a language that I am able to read easily. TIA, Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove ".nospam" to reply. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to count files in a folder
[EMAIL PROTECTED] wrote: > A batch file creates this file and deletes that file in the same loop. > This file is intended to start the reading of an input file. After it > is read batch file deletes this file automatically and on the next loop > it will be written and deleted again. With this script I have to count > the occurences of the file on this specific folder. what does "count" mean here? do you want to check if the file is there, or how many times a file with that name has been created ? the former is easy (just use the os.path.isfile() function), the latter is not really possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to count files in a folder
On Oct 23, 3:11 pm, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > A batch file creates this file and deletes that file in the same loop. > > This file is intended to start the reading of an input file. After it > > is read batch file deletes this file automatically and on the next loop > > it will be written and deleted again. With this script I have to count > > the occurences of the file on this specific folder.what does "count" mean > > here? > > do you want to check if the file is there, or how many times a file with > that name has been created ? Yes I would like to check how many times that specific file is created. so count is the number of times of creation. > > the former is easy (just use the os.path.isfile() function), the latter is not > really possible. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems trying to override __str__ on path class
Peter Otten <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > > So my assumption was that you are using a pre-2.1 version of path. > I suggest that you double-check that by inserting a > > print path.__version__ > > into the code showing the odd behaviour before you start looking for > more exotic causes. Alas, the print statement says "2.1". So there's a definite platform / environment difference here, but that isn't it. > For delegation to work you need (untested) > > class NormPath(object): >def __div__(self, other): >return self.__class__(self._path / other) ># ... I see. The base class implementation is throwing up its hands at the unknown type NormPath. One needs to substitute the parameter in every case where the base class implementation is called. That kind of kills the attractiveness of the technique for new style classes, unless a way could be done to do it programatically instead of explicitly for each method. Of course, if I could get the simple override to work, the need to do this would disappear. Mike -- http://mail.python.org/mailman/listinfo/python-list
python thread state
hi, i'm trying to write a multithreaded embedded python application and i'm having some trouble. i found this article "embedding python in multi-threaded c/c++ applications" in the python journal (http://www.linuxjournal.com/article/3641) but there still seems to be a step missing for me. each time a function in my c module is called, it's called on a different c thread. i would then like to call a function in an embedded python script. from my understanding of the article, you can associate a python script with a c thread by calling PyThreadState_New as in this code: // save main thread state PyThreadState * mainThreadState = NULL; mainThreadState = PyThreadState_Get(); PyEval_ReleaseLock(); // setup for each thread PyEval_AcquireLock(); PyInterpreterState * mainInterpreterState = mainThreadState->interp PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState); PyEval_ReleaseLock(); //execute python code PyEval_AcquireLock(); PyThreadState_Swap(myThreadState); # execute python code PyThreadState_Swap(NULL); PyEval_ReleaseLock(); unfortunately, this doesn't work for me because each time i get called to execute python code, i'm in a new c thread and PyThreadState_Swap seems to want to be executed in the same c thread that PyThreadState_New was executed in. if this isn't the case, please let know. i then called PyThreadState_New each time i wanted to call a python function in the script, but PyThreadState_New wipes out, or rather gives you a new global dictionary, because i lost all my global variables. the article assumes you have one c thread per python thread state, but i want multiple c threads per python thread state. Is there a c api function that will associate a c thread without resetting the global dictionary? thank you, bryan -- http://mail.python.org/mailman/listinfo/python-list
Auto Completion for Python in VIM editor
Dear all, Perl and C/C++ have perl-support.vim and c.vim by Fritz Mehner that support a very convenient auto completion shortcut in visual mode (e.g \aw for While construct). Does anybody know if such a comprehensive scripts also exist for Python? python.vim doesn't seem to suppor this kind of autocompletion. Regards, Edward WIJAYA SINGAPORE Institute For Infocomm Research - Disclaimer - This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to count files in a folder
[EMAIL PROTECTED] wrote: > > > On Oct 23, 3:11 pm, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: >> [EMAIL PROTECTED] wrote: >> > A batch file creates this file and deletes that file in the same loop. >> > This file is intended to start the reading of an input file. After it >> > is read batch file deletes this file automatically and on the next loop >> > it will be written and deleted again. With this script I have to count >> > the occurences of the file on this specific folder.what does "count" >> > mean here? >> >> do you want to check if the file is there, or how many times a file with >> that name has been created ? > > Yes I would like to check how many times that specific file is created. > so count is the number of times of creation. As Fredrik said - not really possible, at least not with standard python. For Linux, you might be lucky using the python LUFS module: http://www.freenet.org.nz/python/lufs-python/ But you being a beginner, I guess that is a bit over your head. Trying to change the behaviour of the batch skript, writing out the information you need is the more reasonable approach. Diez -- http://mail.python.org/mailman/listinfo/python-list
Parsing XML using SAX
Hi, Currently I m writing an XML parser that processes an xml file using sax, and I have it working, however I want to make the code of my parser less cluttered and more readable by other people (including myself). However it is quite messy at the moment. The main reason is that Python doesnt have a switch statement. def startElement(self,name,attributes): if name == "sbml": s = Sbml(attributes['xmlns'], attributes['version'], attributes['level']) self.sbmlDict['sbml'] = s elif name == "model": m = Model(attributes['id'], attributes['name']) self.sbmlDict['model'] = m elif name == "listOfCompartments": self.inListOfCompartments = bool(1) elif name == "compartment" and self.inListOfCompartments: c = Compartment(attributes['id'], attributes['name']) self.tempList.append(c)...snipI would use a dictionary for this, but this would require the use of many extra methods for each tag name, and this would lead to clutter aswell. Does anyone have any suggestions for reducing the number of lines and making my code look neater than a large amount of methods or elif statements. Many ThanksNathan -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems trying to override __str__ on path class
Mike Krell wrote:
> Alas, the print statement says "2.1". So there's a definite platform /
> environment difference here, but that isn't it.
It turns out the observed difference is only indirectly triggered by the
differing platforms. On my machine the path baseclass is str. If I change
it to unicode (by patching path.py), I get the same output that you had.
The problem can be reduced to
>>> class A(str):
... def __str__(self): return "yadda"
...
>>> "%s" % A(), str(A())
('yadda', 'yadda')
>>> class B(unicode):
... def __str__(self): return "yadda"
...
>>> "%s" % B(), str(B())
(u'', 'yadda')
So Python itself doesn't honor an overridden __str__() method for the "%s"
format. Implementing __unicode__() doesn't help, either:
>>> class C(unicode):
... def __unicode__(self): return u"YADDA"
... def __str__(self): return "yadda"
...
>>> "%s" % C(), unicode(C())
(u'', u'')
Somewhere there is an isinstance() test where there should be a test for the
exact class. Seems like a bug to me.
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: Rate my reply
Paddy wrote: > What I am interested in is if John and others might just take time out > to critique the replies. I'm interested in what the group think makes a > good comp.lang.python reply: too short, too long; too cryptic, too > simplistic, too polite (is their such a thing), too nasty; too > self-effacing, too self-promoting; too long a sig ;-) , too anonymous Thanks for the reply. It's kind of hard for me to critique your reply at this point, because I'm starting to understand my problem now. But what I liked about your help was that you took it in steps and show each process. What's always a little confusing is when people immediately resort to examples for help instead of explaining it in words first, because often times this just duplicates the confusion for the OP. But examples definitely help! -- http://mail.python.org/mailman/listinfo/python-list
Using cElementTree and elementtree.ElementInclude
> cElementTree cannot hold ElementTree instances.
>
> can you post a small but self-contained example showing how you got this
> error?
>
#from elementtree.ElementTree import ElementTree, dump # This works
from cElementTree import ElementTree, dump # This does not
from elementtree import ElementInclude
etree = ElementTree(file='xml_in.xml').getroot()
dump(etree)
ElementInclude.include(etree)
dump(etree)
for child in etree.find('./included_root').findall('./*'):
# Copy the child down to the root
etree.append(child)
# Remove the root/included_root
etree.remove(etree.find('./included_root'))
dump(etree)
http://www.w3.org/2001/XInclude";>
Thanks for the help.
Mark
--
http://mail.python.org/mailman/listinfo/python-list
Re: Parsing XML using SAX
Nathan Harmston wrote: > However it is quite messy at the moment. The main reason is that Python > doesnt have a switch statement. a switch statement wouldn't save you a single line, so I find it a bit hard to believe that it's the main reason... > def startElement(self,name,attributes): >if name == "sbml": >s = Sbml(attributes['xmlns'], attributes['version'], > attributes['level']) >self.sbmlDict['sbml'] = s >elif name == "model": >m = Model(attributes['id'], attributes['name']) >self.sbmlDict['model'] = m >elif name == "listOfCompartments": >self.inListOfCompartments = bool(1) >elif name == "compartment" and self.inListOfCompartments: >c = Compartment(attributes['id'], > attributes['name']) >self.tempList.append(c) > ...snip > > I would use a dictionary for this, but this would require the use of many > extra methods for each tag name, and this would lead to clutter aswell. Does > anyone have any suggestions for reducing the number of lines and making my > code look neater than a large amount of methods or elif statements. forget about SAX and silly state machines, and use a modern XML library; here's some ElementTree inspiration: http://effbot.org/zone/element-iterparse.htm#incremental-decoding there are several other newer libraries that provide built-in data binding support, including lxml.objectify and Amara. -- http://mail.python.org/mailman/listinfo/python-list
File and directory permissions in windows
Hi all
I have some problems to get the the permissions on windows. I use a simple
code that run perfectly in UNIX but give me wrong information on Windows. I
found this code searching by google:
import os
import stat
print os.stat('fichero.txt')
st = os.stat('fichero.txt')
mode = st[stat.ST_MODE]
print mode
if mode & stat.S_IREAD: # same as stat.S_IRUSR
print "readable"
if mode & stat.S_IWRITE: # same as stat.S_IWUSR
print "writable"
if mode & stat.S_IEXEC: # same as stat.S_IXUSR
print "executable"
This code allways say that file is readable and writable except if is a read
only file.
Looking for a solution I found this code that use other library but the
result is the same:
import nt
import os
import sys
if (sys.platform == "win32"):
print nt.access ('c:/prueba/fichero.txt', nt.W_OK)
is there a solution for this?, another library or code? Anything that i do
wrong?
Thanks everybody.
Best regards.
--
http://mail.python.org/mailman/listinfo/python-list
Re: implementation of "in" that returns the object.
Jorge Vargas <[EMAIL PROTECTED]> wrote: >I need to check if an object is in a list AND keep a reference to the >object I have done it this way but is there a better one? > def inplusplus(value,listObj): >... for i in listObj: >... if i is value: >... return value >... return False >... try: obj = listObj[listObj.index(value)] # do something with obj except ValueError: # do whatever you're going to do if inplusplus returns False Assuming you meant "if i == value" (as others have pointed out). -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
RE: File and directory permissions in windows
[ismael] | I have some problems to get the the permissions on windows. I | use a simple code that run perfectly in UNIX but give me wrong | information on Windows. I found this code searching by google: [... snip ...] | is there a solution for this?, another library or code? | Anything that i do wrong? Well, I'm certainly feeling guilty, because I've had a note on my TODO list since the last time this came up a month or so ago. In short, Windows doesn't really map the read/write/exec Posix model especially logically. AFAICT, the MS CRT code doesn't take account of NT permissions or things like PATHEXT at all -- which would give you non-readable or executable. The traditional DOS model only supports read-only (and hidden/system/archived which don't apply here) so there's no way, eg, for any combination of flags to indicate can't-read-at-all. In short, *I* need to provide that doc patch I got halfway through, and *you* need to find a way around whatever you're trying to do on Windows. Depending on what you're after, you might end up with some sort of try-except framework, or using the win32security module from the pywin32 extensions. Feel free to post again indicating what you're trying to do with the stat information. TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Screen capture on Linux
Thnx everybody for the help, actually I need somethin slightly different. I found about some external process that can capture the screen, but since I need to captyre the screen up to 4-5 times a second, I don't want to fork a new process every time, so I was looking for some library...[This method works good on Windows] If needed, I was thinking to write a C module too. I never did it before, but I am a not so bad C programmer... any suggestion? What code can I read and eventually reuse? Would the xwd be useful? Anyway doesn't it exist a Python binding for let's say X APIs ? [I know about nothing about X programing] 2006/10/22, Theerasak Photha <[EMAIL PROTECTED]>: > On 22 Oct 2006 09:06:53 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > Paolo Pantaleo wrote: > > > Hi, > > > > > > I need to capture a screen snapshot in Linux. PIL has a module > > > IageGrab, but in the free version it only works under Windows. Is > > > there any package to capture the screen on Linux? > > > > xwd comes with the X server. man xwd > > > > Most useful is "xwd -root" or similar. You may want "sleep 5; xwd > > -root" to give you some time to set things up as needed, or map it to a > > window manager keybinding. > > The problem with that is that xwd format is a non-standard format, and > *uncompressed* on top of that. If he wants to distribute the image to > friends, or whatever, he'll have to convert it to something like png > anyway. If he's using Linux, he probably doesn't need to use xwd > anyway and might as well save himself the effort (and HD space) now. > > -- Theerasak > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: implementation of "in" that returns the object.
"Jorge Vargas" <[EMAIL PROTECTED]> writes: > I need to check if an object is in a list AND keep a reference to the > object I have done it this way but is there a better one? > > >>> def inplusplus(value,listObj): > ... for i in listObj: > ... if i is value: > ... return value > ... return False That's bug-prone. Suppose the object's value is false (i.e. it's the empty string, or None, or the boolean False, or whatever)? You're best off raising an exception if the value is not found. You could also do something like that using the list.index method. -- http://mail.python.org/mailman/listinfo/python-list
Set operations in Numeric
Is there a way to handle numeric (or numarray or numpy) arrays as sets and compute efficiently their intersection, union, etc. ? I hope there is a faster way than s = array(set(A) & set(B)). Can this be done with masked arrays maybe ? I've never used them though and browsing through the docs didn't make clear if it is possible. Thanks, George -- http://mail.python.org/mailman/listinfo/python-list
Python 2.5 ; Effbot console ; thank ; pb release.
Hi! (***sorry for my approximative english***) A few months ago, I needed a console, under Windows. After several research, I selected the console of EffBot. Thank you very much, Fredrik Lundh, for this small tool, quite practical and which repaired me well. Then, Python 2.5 arrived. Many modules/libraries was adapted to Python 2.5 But, it missed the console of EffBot. Patiently, I visited the site of EffBot regularly. Then, I started to corrode me the nails. Then, I questioned myself: "with each new version of Python, certain libraries are never adapted/compiled." For the professional developments, it is a major risk. For (the evolution of) Python, it is an obstacle. The rebuilding of libraries (not-standard) is not (under Windows) very easy, and not very standard. To facilitate this possibility (of rebuilding) could be an objective, intended to improve perenniality of Python. What do you think of that? ( While waiting, for the console, I ended up writing my (perso) small module. Therefore, THANK YOU, Fredrik, FOR NOR TO HAVE COMPILED a version for P-2.5, because: - that made me become aware of brittleness, in time, of the external bookshops; - that forced me to write a trick of which I will be used again myself. ) @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
HTML Templates (Sitemesh/Tiles concept) in Python
Hello, I am a newbie to python and web development. I am part of a fairly simple project and we are trying to identify an efficient way to design our html pages. The technologies at our disposal are javascript, html and python for now. Our pages bear a very standard look. Here is what it looks like. -- BANNER -- | -l1 | <- -> Logout | -l2 |--- | -l3 | | -l4 | CONTENT | -l5 |--- | | COPYRIGHT - l1 through l5 are links that basically target the content page and fill in. Each page via that link has a python reference to go gather appropriate data for the content page. We are using frames to do the banner.html, menu.html (the links page) and the content page. For the content page, how can we decorate it on top with the back/front buttons and logout buttons and botton with a copyright in every page. It seems error prone as well as bad design to scatter this logic in each content page. Is there a template logic like Sitemesh or Tiles concept that can decorate a desired page just before show time? Any other tips to help life easier are appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 ; Effbot console ; thank ; pb release.
Méta-MCI wrote: > For the professional developments, it is a major risk. some days, I ask myself why I shouldn't just use GPL for everything I do, and ship it as source code only. -- http://mail.python.org/mailman/listinfo/python-list
RE: File and directory permissions in windows
No feel guilty because all of us have a lot of things to do and usualy we dont have time to do it. My objective is check if some directories exist and if the user that execute the perl script has access to some files and directories. If one of this checkpoints failed the execution will be aborted. If all of then finish ok the execution will continue. It's simply this. Those scripts will be executed on windows and linux. I start to look python because the MS-DOS utilities were so basic and when i try to do the same with python i found the same problem with the permissions :P Then i try Perl and what happens? the same problem... Thanks for all. Best regards. Tim Golden wrote: > [ismael] > > | I have some problems to get the the permissions on windows. I > | use a simple code that run perfectly in UNIX but give me wrong > | information on Windows. I found this code searching by google: > > [... snip ...] > > | is there a solution for this?, another library or code? > | Anything that i do wrong? > > Well, I'm certainly feeling guilty, because I've had a > note on my TODO list since the last time this came up > a month or so ago. > > In short, Windows doesn't really map the read/write/exec > Posix model especially logically. AFAICT, the MS CRT code > doesn't take account of NT permissions or things like PATHEXT > at all -- which would give you non-readable or executable. > The traditional DOS model only supports read-only > (and hidden/system/archived which don't apply here) so > there's no way, eg, for any combination of flags to indicate > can't-read-at-all. > > In short, *I* need to provide that doc patch I got halfway > through, and *you* need to find a way around whatever you're > trying to do on Windows. Depending on what you're after, you > might end up with some sort of try-except framework, or using > the win32security module from the pywin32 extensions. > > Feel free to post again indicating what you're trying to do > with the stat information. > > TJG > > > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > -- http://mail.python.org/mailman/listinfo/python-list
FreeImagePy creating thumbnails from TIFF
I a trying to create a series of thumbnail images from a multpage TIFF
file. The sample code is below. When it executes, we get the
following error;
FreeImagePy.constants.FreeImagePy_ColorWrong: 'Wrong color 1 in
function: FreeImage_MakeThumbnail. I can use: (8, 24, 32)'
Any suggestions?
fname = "01-PJ2306.tif"
img = FIPY.Image()
img.load(fname)
#NOTE: the follow method results"
#getFormat: ((18, 0), ('TIFF', 'MINISWHITE'), (200, 200))
#getColorUsed: 2
#getNumPages: 8
for pg in range(img.getNumPages()):
print 'page;',pg
bmp = FIPY.Image()
bmp.new((300,300),fileType=FIF_TIFF)
bmp.setBitmap(img)
bmp.thumbnail(300,convert=True)
bmp.save("first_thumb_"+str(pg), FIF_PNG)
img.setCurrentPage(pg+1)
del bmp
Using the above "img" we were able to successfully create the seperate
pages as PNG files in a working directory, however, our goal is to use
to display a series of thumbnails in a wxpython application. The app
will stored references back to the orginal document with the
correspondng page number. Essentially we want to avoid having to
"cleanup" a working directory of the PNG pages.
... but if someone has suggestions on this, we are interested too !
Thanks in avance.
--
http://mail.python.org/mailman/listinfo/python-list
Re: multythreading app memory consumption
Roman Petrichev wrote: > try: > url = Q.get() > except Queue.Empty: > break This code will never raise the Queue.Empty exception. Only a non-blocking get does: url = Q.get(block=False) As mentioned before you should post working code if you expect people to help. i. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 ; Effbot console ; thank ; pb release.
Fredrik Lundh wrote: > Méta-MCI wrote: > > >>For the professional developments, it is a major risk. > > > some days, I ask myself why I shouldn't just use GPL for everything I > do, and ship it as source code only. > To which I presume the answer is that you are considerate of Windows users who'd rather not compile their own Windows applications due to the cost of using the commercial compilers and the complexity of using the open source ones. Whatever the reasons, a vote of thanks to all extension authors who *do* bother to compile for Windows (despite complaints from others who don't feel this happens quickly enough). 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: Set operations in Numeric
George Sakkis wrote: > Is there a way to handle numeric (or numarray or numpy) arrays as sets > and compute efficiently their intersection, union, etc. ? I hope there > is a faster way than s = array(set(A) & set(B)). Can this be done with > masked arrays maybe ? I've never used them though and browsing through > the docs didn't make clear if it is possible. You'll probably want to ask such questions on the numpy list: http://www.scipy.org/Mailing_Lists Robert Cimrman has implemented a number of set operations based on sorting. http://svn.scipy.org/svn/scipy/trunk/Lib/sandbox/arraysetops/arraysetops.py -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
RE: File and directory permissions in windows
[ismael] | My objective is check if some directories exist and if the | user that execute the perl script has access to some files | and directories. If one of this checkpoints failed the | execution will be aborted. If all of then finish ok | the execution will continue. It's simply this. I think you've got two options: 1) Invest some time in understanding the Win32 security model -- which is quite a bit more complex than the (default) Posix model. You'll need to use the win32security module or some ctypes code and see if the logged-on user has the necessary permissions on the file of your choice. or 2) Do it anyway, wrap it in a try-except block and catch the OSError exception (or whatever exception it is). That could be for several reasons, but I suspect that you don't really care *why* this user can't execute, merely that he can't. NB This appraoch is generally well-regarded under Python. In theory between the time you check the permissions and the execution of the script something could happen which changes the situation. If you simply trap any exceptions, you'll always be timely. import os path_i_cant_access = r"\\vogbs022\it\canadasp" try: result = os.listdir (path_i_cant_access) except OSError: print "Couldn't read, or something else happened" else: print "The result was", result Hope that helps TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
sharing persisten cache between modules
Hi, I´ve got a problem creating persistent cache, that would be shared between modules. There a supermodule, which calls submodules. I´d like submodules to use cache created in the supermodule. The only way I see right now, is to pass it as function argument, but that would require a change in API, which I´d prefer to avoid. Is this the only way? -- http://mail.python.org/mailman/listinfo/python-list
Re: sharing persisten cache between modules
Bart Ogryczak wrote: > I´ve got a problem creating persistent cache, that would be shared > between modules. There a supermodule, which calls submodules. I´d like > submodules to use cache created in the supermodule. The only way I see > right now, is to pass it as function argument, but that would require a > change in API, which I´d prefer to avoid. Is this the only way? does "module" mean Python module? why not just put the cache management code in a module that's imported by any submodule that wants to use it ? -- http://mail.python.org/mailman/listinfo/python-list
Re: sharing persisten cache between modules
Fredrik Lundh wrote: > Bart Ogryczak wrote: > > > I´ve got a problem creating persistent cache, that would be shared > > between modules. There a supermodule, which calls submodules. I´d like > > submodules to use cache created in the supermodule. The only way I see > > right now, is to pass it as function argument, but that would require a > > change in API, which I´d prefer to avoid. Is this the only way? > > does "module" mean Python module? Yes it does. > why not just put the cache management > code in a module that's imported by any submodule that wants to use it ? The problem is, that then it is not shared. If I do it like that, each module has it´s own copy of the cache. Maybe I´m doing something wrong. I´ve made a cache module, imported it in each of the submodules. I don´t know how to make the data "static". -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging
Fulvio <[EMAIL PROTECTED]> writes: > The previous post I might have missed some explaination on my proceeding. I'd > say that I'm testing a small program under pdb control > (python /usr/lib/python2.4/pdb.py ./myprog.py). So pdb will load myprog and > stop the first line code. > Once I'm at the pdb command line I can issue the commands available inside > the > pdb itself. Okay. There's one other pydb command might be of interest. I mentioned the ability to issue debugger commands by giving the commands as a string in a command-line option, or putting the debugger commands in a file and giving the name of a file in a command-line option. However *inside* pydb, one can also run a canned set of debugger commands read in from a file. This is "source" command. Again, this is exactly analogous the command of the same name in gdb. Should you want to somehow build such a debugger script from an interactive debugging session, "set history" and "set logging" might be helpful. -- http://mail.python.org/mailman/listinfo/python-list
Re: sharing persisten cache between modules
Bart Ogryczak wrote: > Fredrik Lundh wrote: > >>Bart Ogryczak wrote: >> >> >>>I´ve got a problem creating persistent cache, that would be shared >>>between modules. There a supermodule, which calls submodules. I´d like >>>submodules to use cache created in the supermodule. The only way I see >>>right now, is to pass it as function argument, but that would require a >>>change in API, which I´d prefer to avoid. Is this the only way? >> >>does "module" mean Python module? > > > Yes it does. > > >>why not just put the cache management >>code in a module that's imported by any submodule that wants to use it ? > > > The problem is, that then it is not shared. If I do it like that, each > module has it´s own copy of the cache. Maybe I´m doing something > wrong. I´ve made a cache module, imported it in each of the > submodules. I don´t know how to make the data "static". > No, it doesn't. At least, not if the cache is global to the module that's imported by all the other ones. 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: sharing persisten cache between modules
Bart Ogryczak wrote: >> why not just put the cache management >> code in a module that's imported by any submodule that wants to use it ? > > The problem is, that then it is not shared. If I do it like that, each > module has it´s own copy of the cache. nope. modules are shared, and all module-level objects are shared as well. the code in a module is only executed when you import it the first time; all further imports will get a reference to the same module instance. > Maybe I´m doing something wrong. I´ve made a cache module, imported it in > each of the submodules. that should work. how do you create the cache in the module, and how do the individual modules access the cache? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and CMS
Duncan Booth wrote: > Just because something like Plone can run as a web server doesn't mean that > you expose that web server to the outside world, nor do you have to run it > as a webserver at all. Normally you run Plone behind another web server > such as Apache. > > You can get Plone on shared hosting from various places. I use webfaction > (www.webfaction.com). To be able to run Plone on webfaction, I checked them out a few days ago, you have to get the plan 'shared 4', which is a lot more expensive than places that offer regular web hosting with pythong suport (like dreamhost.com). Bruno Desthuilliers wrote: > Pylons (www.pylonshq.com). It's a rail-like framework based on Paste. What I've seen so far, I like. I think I will use Pylons. Thanks. > > ps. I know that this is a big and complicated project. > > Really ? Why so ? > > Writing a configurable, extensible, general purpose can be a "big and > complicated project". But writing a "taylor-made", specific one is not > that difficult. Good point. -- "Now that I am a Christian I do not have moods in which the whole thing looks very improbable: but when I was an atheist I had moods in which Christianity looked terribly probable." -C. S. Lewis -Echo -- http://mail.python.org/mailman/listinfo/python-list
Re: Set operations in Numeric
Robert Kern wrote: > George Sakkis wrote: > > Is there a way to handle numeric (or numarray or numpy) arrays as sets > > and compute efficiently their intersection, union, etc. ? I hope there > > is a faster way than s = array(set(A) & set(B)). Can this be done with > > masked arrays maybe ? I've never used them though and browsing through > > the docs didn't make clear if it is possible. > > You'll probably want to ask such questions on the numpy list: > >http://www.scipy.org/Mailing_Lists > > Robert Cimrman has implemented a number of set operations based on sorting. > >http://svn.scipy.org/svn/scipy/trunk/Lib/sandbox/arraysetops/arraysetops.py Thank you so much, these fit the bill perfectly ! George -- http://mail.python.org/mailman/listinfo/python-list
encoding of sys.argv ?
Hi all, I am desperately searching for the encoding of sys.argv. I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is "utf-8". However, sys.argv is neither in ASCII (since I can pass French accentuated character), nor in UTF-8. It seems to be encoded in "latin-1", but why ? Jiba -- http://mail.python.org/mailman/listinfo/python-list
ZODB for inverted index?
Hello,
While playing to write an inverted index (see:
http://en.wikipedia.org/wiki/Inverted_index), i run out of memory with
a classic dict, (i have thousand of documents and millions of terms,
stemming or other filtering are not considered, i wanted to understand
how to handle GB of text first). I found ZODB and try to use it a bit,
but i think i must be misunderstanding how to use it even after reading
http://www.zope.org/Wikis/ZODB/guide/node3.html...
i would like to use it once to build my inverted index, save it to disk
via a FileStorage,
and then reuse this previously created inverted index from the
previously created FileStorage, but it looks like i am unable to
reread/reload it in memory, or i am missing how to do it...
firstly each time i use the code below, it looks everything is added
another time, is there a way to rather rewrite/replace it? and how am i
suppose to use it after an initial creation? i thought that using the
same FileStorage would reload my object inside dbroot, but it doesn't.
i was also interested by the cache mecanisms, are they transparent?
or maybe do you know a good tutorial to understand ZODB?
thx for any help, regards.
here is a sample code :
import sys
from BTrees.OOBTree import OOBTree
from BTrees.OIBTree import OIBTree
from persistent import Persistent
class IDF2:
def __init__(self):
self.docs = OIBTree()
self.idfs = OOBTree()
def add(self, term, fromDoc):
self.docs[fromDoc] = self.docs.get(fromDoc, 0) + 1
if not self.idfs.has_key(term):
self.idfs[term] = OIBTree()
self.idfs[term][fromDoc] = self.idfs[term].get(fromDoc, 0) + 1
def N(self, term):
"total number of occurrences of 'term'"
return sum(self.idfs[term].values())
def n(self, term):
"number of documents containing 'term'"
return len(self.idfs[term])
def ndocs(self):
"number of documents"
return len(self.docs)
def __getitem__(self, key):
return self.idfs[key]
def iterdocs(self):
for doc in self.docs.iterkeys():
yield doc
def iterterms(self):
for term in self.idfs.iterkeys():
yield term
storage = FileStorage.FileStorage("%s.fs" % sys.argv[1])
db = DB(storage)
conn = db.open()
dbroot = conn.root()
if not dbroot.has_key('idfs'):
dbroot['idfs'] = IDF2()
idfs = dbroot['idfs']
import transaction
for i, line in enumerate(open(sys.argv[1])):
# considering doc is linenumber...
for word in line.split():
idfs.add(word, i)
# Commit the change
transaction.commit()
---
i was expecting :
storage = FileStorage.FileStorage("%s.fs" % sys.argv[1])
db = DB(storage)
conn = db.open()
dbroot = conn.root()
print dbroot.has_key('idfs')
=> to return True
--
http://mail.python.org/mailman/listinfo/python-list
Re: encoding of sys.argv ?
On 2006-10-23, Jiba <[EMAIL PROTECTED]> wrote: > Hi all, > > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 > filesystem. sys.getdefaultencoding() is "ascii" and > sys.getfilesystemencoding() is "utf-8". However, sys.argv is > neither in ASCII (since I can pass French accentuated > character), nor in UTF-8. It seems to be encoded in "latin-1", > but why ? It will most likely be in the encoding of the terminal from which you call Python, in other words, sys.stdin.encoding. Your only hope of accepting non-US-ASCII command line arguments in this manner is that sys.stdin.encoding is divined correctly by Python. -- Neil Cerutti Facts are stupid things. --Ronald Reagan -- http://mail.python.org/mailman/listinfo/python-list
Looking for a Python-on-Windows person to help with SpamBayes
I'm looking for some help with SpamBayes. It can be short-term or long-term. I've implemented some OCR capability based on the open source ocrad program that works reasonably well to extract text tokens from image-based spam. Alas, I don't use Windows at all, so I can't make sure this stuff works on Windows. None of the usual suspects in the SpamBayes development community have any free time at the moment. Others are helping out, but they are user types, not programmer types, so the round trip between "this doesn't work", to "okay, try this" and back again is agonizingly slow. The bare requirements are: * Able to program in Python on Windows (that is, remove my Unix-think from the OCR bits of code) * Use Outlook to read mail (so you can test the changes with the SpamBayes Outlook plugin) If you can compile software under cygwin (the ocrad program builds fine under cygwin) and/or can create installers for Python-based Windows apps that would be a plus. If you can help out, please drop an email to [EMAIL PROTECTED] Thanks, -- Skip Montanaro - [EMAIL PROTECTED] - http://www.mojam.com/ "The hippies and the hipsters did some great stuff in the sixties, but the geeks pulled their weight too." -- Billy Bragg -- http://mail.python.org/mailman/listinfo/python-list
Introduction article on Ruby on Rail published
The Methods & Tools newsletter has just released in its html archive section the article "An Introduction to Web Development Using the Ruby on Rails Framework". This article presents the basic concepts used by the popular Ruby on Rails web development framework. http://www.methodsandtools.com/archive/archive.php?id=47 -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Python-on-Windows person to help with SpamBayes
[EMAIL PROTECTED] wrote: > I'm looking for some help with SpamBayes. It can be short-term or > long-term. I've implemented some OCR capability based on the open source > ocrad program that works reasonably well to extract text tokens from > image-based spam. Alas, I don't use Windows at all, so I can't make sure > this stuff works on Windows. None of the usual suspects in the SpamBayes > development community have any free time at the moment. Others are helping > out, but they are user types, not programmer types, so the round trip > between "this doesn't work", to "okay, try this" and back again is > agonizingly slow. > > The bare requirements are: > > * Able to program in Python on Windows (that is, remove my Unix-think > from the OCR bits of code) > > * Use Outlook to read mail (so you can test the changes with the > SpamBayes Outlook plugin) > > If you can compile software under cygwin (the ocrad program builds fine > under cygwin) and/or can create installers for Python-based Windows apps > that would be a plus. > > If you can help out, please drop an email to [EMAIL PROTECTED] > > Thanks, > > -- Does ocrad require the cygwin environment to run? -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Templates (Sitemesh/Tiles concept) in Python
Suren wrote:
> Hello,
>
> I am a newbie to python and web development. I am part of a fairly
> simple project and we are trying to identify an efficient way to design
> our html pages. The technologies at our disposal are javascript, html
> and python for now.
Python with ? CGI ? FastCGI ? mod_python ? Other ?
> Our pages bear a very standard look. Here is what it looks like.
>
(snip)
> l1 through l5 are links that basically target the content page and fill
> in. Each page via that link has a python reference to go gather
> appropriate data for the content page. We are using frames to do the
> banner.html, menu.html (the links page) and the content page.
You shouldn't - unless this is an internal web-based application, not a
public site. Since your dynamically generating the pages, there's no
gain using frames - but there are huge drawbacks, for the programmers as
well as for the visitors.
> For the content page, how can we decorate it on top with the back/front
> buttons and logout buttons and botton with a copyright in every page.
> It seems error prone as well as bad design to scatter this logic in
> each content page. Is there a template logic like Sitemesh or Tiles
> concept that can decorate a desired page just before show time?
There are lot of web templating engines in Python, and most of them
provide some way to either "extend" an existing template (to fill-in
page-specific stuffs) or to do server-side-includes-like inclusion of
common parts. Google for Genshi, Jinja, SimpleTAL, Mighty, Cheetah...
> Any other tips to help life easier are appreciated.
Have you considered using one of the existing python web development
libraries/frameworks? Like Pylons, Turbogears, Django, Spyce, Karigell,
etc, etc, etc, etc...
My 2 cents...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list
numpy error
Hello, this is my first try to get wxmpl-1.2.8 running. Therefor I installed: python 2.5 matplotlib-0.87.6.win32-py2.5.exe numpy-1.0rc3.win32-py2.5.exe on WinXP SP2 The result is a version mismatch (see below). Numpy version 102 seems to be numpy-1.0b5 which is not downloadable anymore. Any hints ? Thanks in advance. Jürgen traceback: from pylab import * RuntimeError: module compiled against version 102 of C-API but this version of numpy is 109 The import of the numpy version of the nxutils module, _nsnxutils, failed. This is is either because numpy was unavailable when matplotlib was compiled, because a dependency of _nsnxutils could not be satisfied, or because the build flag for this module was turned off in setup.py. If it appears that _nsnxutils was not built, make sure you have a working copy of numpy and then re-install matplotlib. Otherwise, the following traceback gives more details: Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\pylab.py", line 1, in from matplotlib.pylab import * File "C:\Python25\Lib\site-packages\matplotlib\pylab.py", line 199, in import mlab #so I can override hist, psd, etc... File "C:\Python25\Lib\site-packages\matplotlib\mlab.py", line 64, in import nxutils File "C:\Python25\Lib\site-packages\matplotlib\nxutils.py", line 17, in from matplotlib._ns_nxutils import * ImportError: numpy.core.multiarray failed to import -- http://mail.python.org/mailman/listinfo/python-list
Tkinter question
Hi All,Is it possible to have a widget id while it is created?Something like this:Button(root, text='...', command= lambda v=: fn(v)).grid()and then the function:def fn(v): v['bg']='BLUE' # or maybe nametowidget(v)['bg']='BLUE'Thanks,Sorin-- http://mail.python.org/mailman/listinfo/python-list
Re: ZODB for inverted index?
You may want to take a quick look at ZCatalogs. They are for indexing ZODB objects. I may not be understanding what you are trying to do. I suspect that you really need to store everything in a database (MySQL/Postgres/etc) for maximal flexibility. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding of sys.argv ?
In <[EMAIL PROTECTED]>, Jiba wrote: > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. > sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is > "utf-8". However, sys.argv is neither in ASCII (since I can pass French > accentuated character), nor in UTF-8. It seems to be encoded in > "latin-1", but why ? There is no way to determine the encoding. The application that starts another and sets the arguments can use any encoding it likes and there's no standard way to find out which it was. The `sys.stdin.encoding` approach isn't very robust because this will only be set if the interpreter can find out what encoding is used on `stdin`. That's impossible if the `stdin` is the input from another file. Make it explicit: Add a command line option to choose the encoding. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding of sys.argv ?
Jiba wrote: > Hi all, > > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. > sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is > "utf-8". However, sys.argv is neither in ASCII (since I can pass French > accentuated character), nor in UTF-8. It seems to be encoded in "latin-1", > but why ? > > Jiba Here's what I see in a Windows command prompt interactive session: Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Started with C:/Steve/.pythonrc >>> import sys >>> sys.stdin.encoding 'cp437' >>> sys.getdefaultencoding() 'ascii' >>> But in a Cygwin command window on the same machine I see import syPython 2.5b2 (trunk:50713, Jul 19 2006, 16:04:09) [GCC 3.4.4 (cygming special) (gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. sStarted with C:/Steve/.pythonrc >>> import sys >>> sys.stdin.encoding 'US-ASCII' >>> sys.getdefaultencoding() 'ascii' >>> The strings in sys.argv are encoded the same as the standard input, I bleieve. 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: HTML Templates (Sitemesh/Tiles concept) in Python
> Python with ? CGI ? FastCGI ? mod_python ? Other ? We are using mod_python and SSI. We are inheriting some legacy code that we do not want to mess with at all. > You shouldn't - unless this is an internal web-based application, not a > public site. Since your dynamically generating the pages, there's no > gain using frames - but there are huge drawbacks, for the programmers as > well as for the visitors. Although not an internal site, this site is going to be in a controlled environment. Only a handful of people may access the website. > There are lot of web templating engines in Python, and most of them > provide some way to either "extend" an existing template (to fill-in > page-specific stuffs) or to do server-side-includes-like inclusion of > common parts. Google for Genshi, Jinja, SimpleTAL, Mighty, Cheetah... I will look at these and see it works. > > > Any other tips to help life easier are appreciated. > > Have you considered using one of the existing python web development > libraries/frameworks? Like Pylons, Turbogears, Django, Spyce, Karigell, > etc, etc, etc, etc... > > My 2 cents... We have not considered a framework coz the legacy code base has not included one. We are living in the same source structure and did not want to introduce a newer dependency. I hope we can find a non-intrusive library/framework that does its job. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 ; Effbot console ; thank ; pb release.
Steve Holden wrote: > Fredrik Lundh wrote: > > Méta-MCI wrote: > > > >>For the professional developments, it is a major risk. I'll cut in here and mention that it's a risk that can be managed through various well understood methods of deployment. For me, Python 2.4 is going to be good enough until (and even beyond) the time I can be bothered to either upgrade my distribution's packages or to upgrade my distribution and get the packages for Python 2.5. At which point, I'll just need to select the pinnacles of my package tower; then I can hopefully just press the button and have everything working on Python 2.5. Generally, package developers shouldn't be "aggressively" using the absolute latest and greatest version's features, and if you're pursuing "professional developments" you might want to keep using the mature releases of Python whilst letting other developers know that adoption of their stuff will be limited if they make it part of a rapidly moving target. Sure, I can imagine that people are desperate to use the "with" statement all over the place, but maintainers of widely used (or "professional") stuff have to exercise some conservatism - otherwise someone has to start forking and backporting their changes. > > some days, I ask myself why I shouldn't just use GPL for everything I > > do, and ship it as source code only. > > > To which I presume the answer is that you are considerate of Windows > users who'd rather not compile their own Windows applications due to the > cost of using the commercial compilers and the complexity of using the > open source ones. Well, there's a commercial service you could offer, Steve. ;-) > Whatever the reasons, a vote of thanks to all extension authors who *do* > bother to compile for Windows (despite complaints from others who don't > feel this happens quickly enough). This happens every time a new release of Python comes out: people want to play with the new features, but they experience a period of frustration because their favourite packages aren't available. I'd advise people to download the installer, get their fill of the new features for a few minutes, then schedule another look in a few weeks. Or they can start paying people to make it all happen "yesterday", of course. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees
Georg Brandl wrote: > Michael Spencer wrote: >> Announcing: compiler2 >> - >> >> For all you bytecode enthusiasts: 'compiler2' is an alternative to the >> standard >> library 'compiler' package, with several advantages. > > Is this a rewrite from scratch, or an improved stdlib compiler package? > > In the latter case, maybe you can contribute some patches to the core. > > Georg Georg It started as the latter (i.e., the stdlib compiler package improved) and proceeded via incremental change with the twin goals of generating correct object code and creating a clean compiler architecture (the latter somewhat subjective of course). I'd be happy in principle to contribute the work, but the sum of the changes amounts to a substantial re-write, so I don't think it can be meaningfully submitted as a patch. Regards Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Python-on-Windows person to help with SpamBayes
olsongt> Does ocrad require the cygwin environment to run? No. It was compiled so it didn't require the cygwin runtime environment. I presume it was statically linked. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: Python2.3 & Python2.4 on RHEL4 x86_64
PYTHONPATH was the problem. I had /usr/lib64/python2.3 included and that's why it was breaking. I took it out and it works fine now. Unfortunately, it still puts the lib files in /usr/lib instead of /usr/lib64. I'm assuming all I need to do is set libdir accordingly and the files will get put in /usr/lib64. How do I then build the library files for 32bits? Respectfully, Christopher Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 ; Effbot console ; thank ; pb release.
Paul Boddie wrote: > Steve Holden wrote: > >>Fredrik Lundh wrote: >> >>>Méta-MCI wrote: >>> >>> For the professional developments, it is a major risk. > > > I'll cut in here and mention that it's a risk that can be managed > through various well understood methods of deployment. For me, Python > 2.4 is going to be good enough until (and even beyond) the time I can > be bothered to either upgrade my distribution's packages or to upgrade > my distribution and get the packages for Python 2.5. At which point, > I'll just need to select the pinnacles of my package tower; then I can > hopefully just press the button and have everything working on Python > 2.5. > > Generally, package developers shouldn't be "aggressively" using the > absolute latest and greatest version's features, and if you're pursuing > "professional developments" you might want to keep using the mature > releases of Python whilst letting other developers know that adoption > of their stuff will be limited if they make it part of a rapidly moving > target. Sure, I can imagine that people are desperate to use the "with" > statement all over the place, but maintainers of widely used (or > "professional") stuff have to exercise some conservatism - otherwise > someone has to start forking and backporting their changes. > > >>>some days, I ask myself why I shouldn't just use GPL for everything I >>>do, and ship it as source code only. >>> >> >>To which I presume the answer is that you are considerate of Windows >>users who'd rather not compile their own Windows applications due to the >>cost of using the commercial compilers and the complexity of using the >>open source ones. > > > Well, there's a commercial service you could offer, Steve. ;-) > You think people would pay? > >>Whatever the reasons, a vote of thanks to all extension authors who *do* >>bother to compile for Windows (despite complaints from others who don't >>feel this happens quickly enough). > > > This happens every time a new release of Python comes out: people want > to play with the new features, but they experience a period of > frustration because their favourite packages aren't available. I'd > advise people to download the installer, get their fill of the new > features for a few minutes, then schedule another look in a few weeks. > Or they can start paying people to make it all happen "yesterday", of > course. > If there's evidence of demand this *is* something I'd consider doing. 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
python2.5 importerror on md5
i compiled and installed the release version of python 2.5 for linux to
a directory accessible to 2 computers, configured with
--prefix=/usr/arch (which is accessible to both machines). the
installation went fine and when i run python on one machine i can do
from hashlib import * without a problem. on the other machine i get the
following error:
Traceback (most recent call last):
File "", line 1, in
File "/usr/arch/lib/python2.5/hashlib.py", line 104, in
md5 = __get_builtin_constructor('md5')
File "/usr/arch/lib/python2.5/hashlib.py", line 31, in
__get_builtin_constructor
import _md5
ImportError: No module named _md5
I have the file md5.py , md5.pyo , and md5.pyc in
/usr/arch/lib/python2.5/ so I don't know why python is having a problem
finding the md5 module...
The sys.path is equal on both machines :
['', '/usr/arch/lib/python25.zip', '/usr/arch/lib/python2.5',
'/usr/arch/lib/python2.5/plat-linux2',
'/usr/arch/lib/python2.5/lib-tk',
'/usr/arch/lib/python2.5/lib-dynload',
'/usr/arch/lib/python2.5/site-packages',
'/usr/arch/lib/python2.5/site-packages/gtk-2.0']
Here is the version info :
Python 2.5 (r25:51908, Oct 23 2006, 13:38:11)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2
If anyone has encountered similar problems or knows of a way to
fix/suggestions please let me know.
Thanks in advance.
Sam
--
http://mail.python.org/mailman/listinfo/python-list
Re: Handling emails
Fulvio wrote: > > Hello, > > I'd like to ask some clue to move further on my project :-) > The purpose would be to gather all emails (local and remote ones) to do some > backup. > I've tried to get ideas by reading all about the modules enclose with python, > but neither email framework nor mailbox give me the idea how to handle *one* > email complete of payload and attachment (if any). The 'PopClient' class here might help you: http://gflanagan.net/site/python/pagliacci/pagliacci.py.html A script I use is here: http://gflanagan.net/site/python/pagliacci/getpopmail.py.html There's a woeful lack of comments but hopefully you can figure it out! It saves emails to the filesystem along with attachments. (Note that the POP account passwords are stored as plain text.) It checks a mail's message-id and doesn't download if it already has been downloaded. hth Gerard -- http://mail.python.org/mailman/listinfo/python-list
_winreg.saveKey question
Reply with quote Edit/Delete this post Delete this post
Post _winreg.SaveKey question
Does anyone know where I might find some sample code of using the
saveKey function? I am getting an error 5 access denied and I think
that it is coming from the way I am specifying the filename as in
_winreg.SaveKey(key, filename). The docs mention that if the key is to
a remote host (which it is in my case) that the path is relative. I
read this as meaning that I should use a unc path back to where I want
to save the registry key file. Here is a section of the code I am
using:
def remoteSaveKey(host, key, file):
rhostreg = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)
remotekey = _winreg.OpenKey(rhostreg, key)
_winreg.SaveKey(remotekey, file)
... from main():
readfile = open('hostlist.txt', 'r')
hostfile = []
for host in readfile:
hostfile += [host.strip()]
for srvname in hostfile:
outputpath = destsrvr + srvname # destsrvr is server/share
outputfile = outputpath + "\\" + srvname
output = remoteSaveKey(hostname, regpath, outputfile)
I am able to connect to the registry and I believe that the key is
being specified correctly, but I am getting the following error:
Traceback (most recent call last):
File "main.py", line 40, in ?
output = remoteSaveKey(srvname, regpath, outputfile)
File "main.py", line 17, in remoteSaveKey
_winreg.SaveKey(remotekey, file)
WindowsError: [Errno 5] Access is denied
I have searched but have only been able to find documentation with
little to no examples on how to implement the SaveKey function with a
remote host. Any help will be appreciated.
thx
--
http://mail.python.org/mailman/listinfo/python-list
Getting a lot of SPAM from this list
I'm getting a lot of spam to the email address I use to post to this list. Since this email address doesn't appear elsewhere, I know that people are scanning this list to get the email address and spam me. Does anyone have a suggestion as to a way that I can get less of this spam? I could have another email address, but that won't help as I'd still get the spam and have to wade through it. I'm running spamassassin, but it isn't catching all that much of it. Any suggestions would be greatly appreciated. Regards, Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: _winreg.saveKey question
> remotekey = _winreg.OpenKey(rhostreg, key) Try adding the sam=_winreg.KEY_SET_VALUE parameter. Help on built-in function OpenKey in module _winreg: OpenKey(...) key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open res is a reserved integer, and must be zero. Default is zero. sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ The result is a new handle to the specified key If the function fails, an EnvironmentError exception is raised. The default is KEY_READ so you can't update. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Attempting to parse free-form ANSI text.
Frederic Rentsch wrote:
> Paul McGuire wrote:
>
>> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message
>>
Sorry about the line wrap mess in the previous message. I try again with
another setting:
Frederic
##
The following code does everything Mike needs to do, except interact
with wx. It is written to run standing alone. To incorporate it in
Mike's class the functions would be methods and the globals would be
instance attributes. Running it does this:
>>> chunk_1 = """This is a test string containing some ANSI sequences.
Sequence 1 Valid code, invalid numbers: \x1b[10;12mEnd of sequence 1
Sequence 2 Not an 'm'-code: \x1b[30;4;77hEnd of sequence 2
Sequence 3 Color setting code: \x1b[30;45mEnd of sequence 3
Sequence 4 Parameter setting code: \x1b[7mEnd of sequence 4
Sequence 5 Color setting code spanning calls: \x1b[3"""
>>> chunk_2 = """7;42mEnd of sequence 5
Sequence 6 Invalid code: \x1b[End of sequence 6
Sequence 7 A valid code at the end: \x1b[9m
"""
>>> init ()
>>> process_text (chunk_1)
>>> process_text (chunk_2)
>>> print output
This is a test string containing some ANSI sequences.
Sequence 1 Valid code, invalid numbers: >>!!!Ignoring unknown number 10!!!<<
>>!!!Ignoring unknown number 1!!!<< End of sequence 1
Sequence 2 Not an 'm'-code: End of sequence 2
Sequence 3 Color setting code: >>setting foreground BLACK<< >>setting
background MAGENTA<< End of sequence 3
Sequence 4 Parameter setting code: >>Calling parameter setting function 7<<
End of sequence 4
Sequence 5 Color setting code spanning calls: >>setting foreground GREY<<
>>setting background GREEN<< End of sequence 5
Sequence 6 Invalid code: nd of sequence 6
Sequence 7 A valid code at the end: >>Calling parameter setting function 9<<
#
def init (): # To add to AnsiTextCtrl.__init__ ()
import SE # SEL is less import overhead but doesn't have interactive
development features (not needed in production versions)
global output #-> For testing
global Pre_Processor, digits_re, Colors, truncated_escape_hold #
global -> instance attributes
# Screening out all ansi escape sequences except those controlling color
grit = '\n'.join (['(%d)=' % i for i in range (128,255)]) + ' (13)= '
# Makes 127 fixed expressions plus delete \r
# Regular expression r'[\x80-\xff\r]' would work fine but is four
times slower than 127 fixed expressions
all_escapes = r'\x1b\[\d*(;\d*)*[A-Za-z]'
color_escapes = r'\x1b\[\d*(;\d*)*m'
Pre_Processor = SE.SE ('%s ~%s~= ~%s~==' % (grit, all_escapes,
color_escapes)) # SEL.SEL for production
# 'all_escapes' also matches what 'color_escapes' matches. With
identical regular expression matches the last regex definitions applies.
# Isolating digits.
digits_re = re.compile ('\d+')
# Color numbers to color names
Colors = SE.SE ('''
30=BLACK40=BLACK
31=RED 41=RED
32=GREEN42=GREEN
33=YELLOW 43=YELLOW
34=BLUE 44=BLUE
35=MAGENTA 45=MAGENTA
36=CYAN 46=CYAN
37=GREY 47=GREY
39=GREY 49=BLACK
''')
truncated_escape_hold = '' #-> self.truncated_escape_hold
output= '' #-> For testing only
# What follows replaces all others of Mike's methods
def process_text (text):
global output #-> For testing
global truncated_escape_hold, digits_re, Pre_Processor, Colors
purged_text = truncated_escape_hold + Pre_Processor (text)
# Text is now clean except for color codes beginning with ESC
ansi_controlled_sections = purged_text.split ('\x1b')
# Each ansi_controlled_section starts with a color control, except the
first one (leftmost split-off)
if ansi_controlled_sections:
#-> self.AppendText(ansi_controlled_sections [0]) #->
For real
output += ansi_controlled_sections [0] #-> For testing #->
For testing
for section in ansi_controlled_sections [1:]:
if section == '': continue
try: escape_ansi_controlled_section, data = section.split ('m', 1)
except ValueError: # Truncated escape
truncated_escape_hold = '\x1b' + section # Restore ESC
removed by split ('\x1b')
else:
escapes = escape_ansi_controlled_section.split (';')
for escape in escapes:
try: number = digits_re.search (escape).group ()
except AttributeError:
output += ' >>!!!Invalid number %s!!!<<< ' % escape
#-> For testing
continue
_set_wx (number)
#-> self.AppendText(data) #-> For real
output += data#-> For testing
def _set_wx (n):
global output # For testing only
global Colors
int_n = int (n)
if 0 <= int_n <= 9:
#-> self._number_to_method (n)() #->
For real
output += ' >>Calling parameter setting function %s<
Re: python2.5 importerror on md5
samn wrote:
> i compiled and installed the release version of python 2.5 for linux to
> a directory accessible to 2 computers, configured with
> --prefix=/usr/arch (which is accessible to both machines). the
> installation went fine and when i run python on one machine i can do
> from hashlib import * without a problem. on the other machine i get the
> following error:
> Traceback (most recent call last):
> File "", line 1, in
> File "/usr/arch/lib/python2.5/hashlib.py", line 104, in
> md5 = __get_builtin_constructor('md5')
> File "/usr/arch/lib/python2.5/hashlib.py", line 31, in
> __get_builtin_constructor
> import _md5
> ImportError: No module named _md5
>
> I have the file md5.py , md5.pyo , and md5.pyc in
> /usr/arch/lib/python2.5/ so I don't know why python is having a problem
> finding the md5 module...
>
> The sys.path is equal on both machines :
> ['', '/usr/arch/lib/python25.zip', '/usr/arch/lib/python2.5',
> '/usr/arch/lib/python2.5/plat-linux2',
> '/usr/arch/lib/python2.5/lib-tk',
> '/usr/arch/lib/python2.5/lib-dynload',
> '/usr/arch/lib/python2.5/site-packages',
> '/usr/arch/lib/python2.5/site-packages/gtk-2.0']
>
> Here is the version info :
> Python 2.5 (r25:51908, Oct 23 2006, 13:38:11)
> [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2
>
> If anyone has encountered similar problems or knows of a way to
> fix/suggestions please let me know.
>
I believe the _md5 module (as opposed to the md5 module) is a compiled
extension. I'm guessing the import succeeds on the machine you used to
build python.
Try
import _md5
print _md5.__file__
and see if you can find out where it's being loaded from. You'll
probably find that you also need to tailor the sysprefix parameter, or
some such.
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: _winreg.saveKey question
> remotekey = _winreg.OpenKey(rhostreg, key) Try adding the sam=_winreg.KEY_SET_VALUE parameter. Help on built-in function OpenKey in module _winreg: OpenKey(...) key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open res is a reserved integer, and must be zero. Default is zero. sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ The result is a new handle to the specified key If the function fails, an EnvironmentError exception is raised. The default is KEY_READ so you can't update. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting a lot of SPAM from this list
On Oct 23, 2006, at 3:13 PM, [EMAIL PROTECTED], "Bates "@bag.python.org wrote: > I'm getting a lot of spam to the email address I use to post > to this list. Since this email address doesn't appear elsewhere, > I know that people are scanning this list to get the email > address and spam me. Does anyone have a suggestion as to a > way that I can get less of this spam? I could have another > email address, but that won't help as I'd still get the spam > and have to wade through it. I'm running spamassassin, but it > isn't catching all that much of it. Any suggestions would be > greatly appreciated. Spammers don't scan lists as much anymore; they now rely on machines infected with malware to extract addresses out of email programs. I know this doesn't help you, but it is good to recognize that it isn't always the fault of the list admins. I have an advantage in that I run my own mail server, and can create as many aliases to my account as I like. When a particular address "goes bad", I change that alias to point to /dev/null, and create a new one. If it's an alias for a list, I first unsub using the old alias, and then re-sub with the new one. -- Ed Leafe -- http://leafe.com -- http://dabodev.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Attempting to parse free-form ANSI text.
Frederic Rentsch wrote: > Frederic Rentsch wrote: > >> Paul McGuire wrote: >> >> >>> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message >>> >>> > > Sorry about the line wrap mess in the previous message. I try again with > another setting: > > Frederic > I give up! -- http://mail.python.org/mailman/listinfo/python-list
Re: Attempting to parse free-form ANSI text.
Frederic Rentsch wrote: > Frederic Rentsch wrote: > >>Frederic Rentsch wrote: >> >> >>>Paul McGuire wrote: >>> >>> >>> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message >> >>Sorry about the line wrap mess in the previous message. I try again with >>another setting: >> >>Frederic >> > > I give up! > > Don't give up, attach it as a file! 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: python2.5 importerror on md5
> I believe the _md5 module (as opposed to the md5 module) is a compiled > extension. I'm guessing the import succeeds on the machine you used to > build python. > > Try > >import _md5 >print _md5.__file__ > > and see if you can find out where it's being loaded from. You'll > probably find that you also need to tailor the sysprefix parameter, or > some such. > You are correct that import md5 works fine on the machine that I compiled on and only has problems on the other machine. I wasn't able to import _md5 , even on the machine I compiled on. Here's what I get on the machine I compiled on: Python 2.5 (r25:51908, Oct 23 2006, 13:38:11) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> import _md5 Traceback (most recent call last): File "", line 1, in ImportError: No module named _md5 >>> import md5 >>> print md5.__file__ /usr/arch/lib/python2.5/md5.py sys.prefix is equal on both machines: >>>import sys >>> sys.prefix '/usr/arch' thanks for any help sam -- http://mail.python.org/mailman/listinfo/python-list
