Re: Refactoring question
> On Behalf Of Kevin Walzer > What's the best way to do this? Can anyone point me in the > right direction? How could, for instance, the top snippet be > rewritten to separate the Tkinter parts from the generic stuff? I like to use the broadcaster/broker recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81983 I added a few features (such as decorators for listener functions -- see below sig). There are other recipes out there, such as PyDispatcher. Basically, I have GUI events translated into broadcaster events (by passing lambdas that call broadcaster.Broadcast() to the event binders), which are received by controller functions/classes. Feedback (status/progress) is also communicated via broadcaster events. Something I tried on my current project, which is going fairly well, is first writing a command-line version, then writing a GUI version, with the same controller back-end used in each case, and the controller communicating progress/results via the same interface. This approach has made me keep presentation and logic very loosely coupled. So for instance, the view class would send request for processing, which the controller gets. The controller performs the requested action, sending broadcasts of progress (note that the controller can start a worker thread for the processing, but the broadcasts should be made on the GUI thread...) broadcaster.Broadcast( "progress", "start", (100, "Doing your bidding now..." ) ) # number of items we will process # ... broadcaster.Broadcast( "progress", "progress", (i, "Working on item %i" % i ) ) # current item # ... broadcaster.Broadcast( "progress", "end", (100, "Done!") ) Depending on who is showing the progress, this might go onto a status bar, progress dialog, the console, a log file, and so on, or some combination thereof -- the controller doesn't know or care. When the controller is finished, it asks the broker for a view, and calls show results on the view view = broker.Request( "view" ) view.ShowResults( results ) That could have been done equally with the broadcaster, but for some reason I like the broker here (it makes the view "dumber"). Regards, Ryan -- Ryan Ginstrom == # listener decorators def BrokerRequestHandler( title ): """A decorator for broker listeners @param title: the title to provide The decorated function must take no arguments (it can retrieve them using CurrentData()) """ def decorator(func): broker.Register( title, func ) return func return decorator def BroadcasterEventHandler( source, title ): """A decorator for broadcaster event handlers @param source: the broadcast source @param title: the title of the broadcast The decorated function must take no arguments (it can retrieve them using CurrentData()) """ def decorator(func): broadcaster.Register( func, source, title ) return func return decorator # example ... @BrokerRequestHandler( "meaning of life" ) def getMeaningOfLife(): return 42 ## A little more complicated for class methods. I stole this technique from WCK # Lifted shamelessly from WCK (effbot)'s wckTkinter.bind def EventHandler( source, title ): """Dectorator for event-handling methods""" def decorator(func): func.BroadcasterEvent = (source, title) return func return decorator class FrameController: """Controller for the main frame window""" def __init__( self ): for key in dir(self): method = getattr(self, key) if hasattr(method, "BroadcasterEvent") and callable(method): source, title = method.BroadcasterEvent broadcaster.Register( method, source=source, title=title ) @EventHandler( "event", "onExport" ) def onExport( self ): """Handles the onExport broadcast by exporting the database to the requested format""" format = broadcaster.CurrentData() # Perform export... -- http://mail.python.org/mailman/listinfo/python-list
Re: zip list with different length
On Apr 4, 4:53 pm, [EMAIL PROTECTED] wrote: > elements, say len(a) = 5, len(b) = 3 > >>> a = range(5) > >>> b = range(3) ... > I want the results to be > [(0, 0), (1, 1), (2, 2) , (3) , (4) ] > can it be done? A bit cumbersome, but at least shows it's possible: >>> def superZip( a, b ): common = min( len(a), len(b) ) results = zip( a[:common], b[:common] ) if len( a ) < len( b ): a = b return results + [ (x,) for x in a[common:] ] >>> superZip( range( 5 ), range( 3 ) ) [(0, 0), (1, 1), (2, 2), (3,), (4,)] >>> superZip( range( 3 ), range( 5 ) ) [(0, 0), (1, 1), (2, 2), (3,), (4,)] >>> superZip( range( 0 ), range( 5 ) ) [(0,), (1,), (2,), (3,), (4,)] >>> superZip( range( 3 ), range( 3 ) ) [(0, 0), (1, 1), (2, 2)] Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Classes referencing each other
> Behalf Of Manuel Bleichner > In a module I have a huge number of classes of the form: > > class A(object): >connected_to = [B, C] > > > class B(object) >connected_to = [C] > > > class C(object) >connected_to = [A] > > > As you see, classes A and B reference classes that are not > yet defined when the class is being defined. > It will raise a NameError: 'B'. How about a connection broker? Simple example: # connections = {} def Register( obj ): try: connections[obj.name]['obj'] = obj except KeyError: connections[obj.name] = { 'obj' : obj, 'connected_to' : [] } def ConnectTo( objname, obj ): try: connections[objname]['connected_to'].append( obj ) except KeyError: connections[objname] = { 'obj' : None, 'connected_to' : [obj] } class ConnectionObject: def __str__(self): return self.name class A(ConnectionObject): def __init__(self): self.name = 'A' Register( self ) ConnectTo( 'B', self ) class B(ConnectionObject): def __init__(self): self.name = 'B' Register( self ) ConnectTo( 'A', self ) ConnectTo( 'C', self ) class C(ConnectionObject): def __init__(self): self.name = 'C' Register( self ) ConnectTo( 'A', self ) a = A() b = B() c = C() for (key, val) in connections.iteritems(): print 'object: %s (%s)' % ( key, val['obj'] ) str_vals = [] for obj in val['connected_to']: str_vals.append( str( obj ) ) print '\tconnections from:', str_vals # Output: object: A (A) connections from: ['B', 'C'] object: C (C) connections from: ['B'] object: B (B) connections from: ['A'] object: D (None) connections from: ['C'] Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Python, Dutch, English, Chinese, Japanese, etc.
> On Behalf Of Steve Howell > Asia: > >Python should be *completely* internationalized for > Mandarin, Japanese, and possibly Hindi and Korean. > Not just identifiers. I'm talking the entire language, > keywords and all. I am a Japanese-to-English translator in my day job, and live in Japan. I can say with confidence that most Japanese programmers do not want localized keywords. Note that Yukihiro "Matz" Matsumoto created Ruby with English(-styled) keywords. One reason for preferring ASCII keywords and variable names is that typing Japanese requires the use of a front-end processor (FEP), which considerably slows and complicates typing output. One English-to-Japanese translator I know finds it quicker to write his Japanese translations by hand, and have his assistant type them (he types reasonably well in English). Additionally, most Japanese programmers would probably prefer their programs to be accessible outside Japan, and poorly named variables are a much lower barrier to understanding than Japanese would be. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Obtaining hte currently running script under windows
> On Behalf Of Sean Farrow > Is there any way to obtain the full path to the currently > running script under win32? > I am using the pythonw.exe file is that helps. > Sean. Current working directory is not always reliable. There is a __file__ variable set if python.exe runs your script. import os import sys module_name = os.path.dirname(unicode(__file__, sys.getfilesystemencoding( ))) If your script is frozen via py2exe, you can use the sys.executable value to get the module directory. import os import sys module_name = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( ))) (You need the Unicode stuff if your path may include non-ASCII characters) function module_path() in the alternate solution at http://www.py2exe.org/index.cgi/WhereAmI will give you the module (script/executable) directory whether your script is running normally or frozen. Regards, Ryan -- Ryan Ginstrom [EMAIL PROTECTED] http://ginstrom.com/ -- http://mail.python.org/mailman/listinfo/python-list
RE: win32com ppt embedded object
> On Behalf Of Lance Hoffmeyer > for Z in WB.Slides(29).Shapes: > if (Z.Type== 7): > ZZ=Z.OLEFormat.Object > WSHEET = ZZ.Worksheets(1) > WSHEET.Range("A1").Value = .50 > WSHEET.Range("A1").NumberFormat="0%" I think you need to call Activate on your OLE object. Here is some code I use to extract the text from an Excel worksheet embedded in a PowerPoint slide. Maybe you can adapt it to your purposes. def extract_excel_text( shape ): """Process embedded excel worksheet in the powerpoint slide """ format = shape.OLEFormat format.Activate() excel = format.Object sheet = excel.ActiveSheet for row in sheet.UsedRange.Value: for cell in row: if cell: yield cell for shape in sheet.Shapes: try: # We need to give a range of characters, # # but we can take advantage of the fact that texboxes # # have a maximum length of 255 characters # yield shape.TextFrame.Characters(1,255).Text except com_error, details: log_error( "Exception getting shape text", details ) Regards, Ryan -- Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: testing with coverage.py problem
> On Behalf Of Piotr Hrebieniuk > I've spent few hours and found nothing, so here's my question: > How can i run tests wrote by myself on a module, using coverage.py ? > Let's assume i have a module mymod.py which i want to test > with tests from file mytest.py (i.e. class inherited from > unittest.TestCase). How to do that with coverage.py? Where i > should put the code that runs the tests? The easiest way is probably by using nose http://somethingaboutorange.com/mrl/projects/nose/ In particular, check out the "--with-coverage" flag. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: code packaging
> On Behalf Of Paul Rubin > I'm wondering how other projects go about this. I develop an automated build system from the very beginning. Running the build script: * Creates the API documentation (epydoc) * Creates the help files (extracting some information from the source) * Builds a windows executable (py2exe) * Builds an installer (Inno Setup) * Runs the installer (AutoIt) * Runs a smoke test on the installed application (AutoIt) The program must at least install and pass the smoke tests at any given point in development. Another script uploads the installer to my server, and sends an email to the testers stating that a new version is ready, with a list of additions/improvements. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: From D
> On Behalf Of Leo Petr > Digits are grouped in 2s in India and in 4s in China and Japan. This is not entirely true in Japan's case. When written without Japanese characters, Japan employs the same format as the US, for example: 1,000,000 (However, they would read this as 百万 (hyaku man), literally 100 ten thousands.) Raymond is correct in that Japan traditionally groups in fours (and stills reads it that way regardless, as shown above), but in an ordinary programming context, this almost never comes into play. On the original topic of the thread, I personally like the underscore idea from D, and I like it better than the "concatenation" idea, even though I agree that it is more consistent with Python's string-format rules. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Utilizing a raw IDispatch Pointer from Python
> On Behalf Of Brad Johnson > I would like to give the Python interpreter access to these > interfaces that were created in C++ land. > > Stated another way, how can I have Python consume a IDispatch > pointer from C++ and wrap it with one of those nice Python > classes automatically? If I understand you correctly, you can use client.Dispatch from win32com import client com_object = client.Dispatch(idispatch_pointer_from_cpp) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Using Regular Expresions to change .htm to .php in files
> On Behalf Of Mark > This line should be: > > sed "s/\.htm$/.php/g" < $each > /tmp/$$ I think a more robust way to go about this would be: (1) Use os.walk to walk through the directory http://docs.python.org/lib/os-file-dir.html (2) Use Beautiful Soup to extract the internal links from each file http://crummy.com/software/BeautifulSoup/documentation.html from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(doc) links = soup('a') internal_links = [link["href"] for link in links if link.has_key("href") and not link["href"].startswith("http")] (4) Do straight string replacements on those links (no regex needed) (5) Save each html file to *.html.bak before changing Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Parser Generator?
> On Behalf Of Jason Evans > Parsers typically deal with tokens rather than individual > characters, so the scanner that creates the tokens is the > main thing that Unicode matters to. I have written > Unicode-aware scanners for use with Parsing-based parsers, > with no problems. This is pretty easy to do, since Python > has built-in support for Unicode strings. The only caveat being that since Chinese and Japanese scripts don't typically delimit "words" with spaces, I think you'd have to pass the text through a tokenizer (like ChaSen for Japanese) before using PyParsing. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Parser Generator?
> On Behalf Of Paul McGuire > > On Aug 26, 8:05 pm, "Ryan Ginstrom" <[EMAIL PROTECTED]> wrote: > > The only caveat being that since Chinese and Japanese scripts don't > > typically delimit "words" with spaces, I think you'd have > to pass the > > text through a tokenizer (like ChaSen for Japanese) before > using PyParsing. > > Did you think pyparsing is so mundane as to require spaces > between tokens? Pyparsing has been doing this type of > token-recognition since Day 1. Cool! I stand happily corrected. I did write "I think" because although I couldn't find a way to do it, there might well actually be one . I'll keep looking to find some examples of parsing Japanese. BTW, I think PyParsing is great, and I use it for several tasks. I just could never figure out a way to use it with Japanese (at least on the applications I had in mind). Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: How to use os.putenv() ?
> On Behalf Of [EMAIL PROTECTED] > What am I doing wrong? How do I change the value of an > environment variable? You'll have to go through the Windows registry. Please have a look at the following recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/55993 I also have my own routines based on that for getting and setting the path: ## import _winreg as winreg import win32gui import win32con REG_KEY_PATH = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' def set_path(pathval): """Set the PATH environment variable""" try: reg = winreg.ConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE) key = winreg.OpenKey(reg, REG_KEY_PATH, 0, win32con.KEY_ALL_ACCESS) winreg.SetValueEx(key, 'path', 0, win32con.REG_EXPAND_SZ, pathval) win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') finally: winreg.CloseKey(key) winreg.CloseKey(reg) def get_path(): """Get the PATH environment variable""" try: reg = winreg.ConnectRegistry(None, win32con.HKEY_LOCAL_MACHINE) key = winreg.OpenKey(reg, REG_KEY_PATH, 0, win32con.KEY_ALL_ACCESS) return winreg.QueryValueEx(key, 'path')[0] finally: winreg.CloseKey(key) winreg.CloseKey(reg) ## Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: status of Programming by Contract (PEP 316)?
> On Behalf Of Russ > Once you have the conditions in place, all you need to do in > your unit tests is to send inputs to the unit and wait to see > if exceptions are thrown. That sounds a little ambitious to me... However, you may want to look at the typecheck module (you can get it via easy_install). I think you could probably extend it to do DBC. http://oakwinter.com/code/typecheck/ >>> from typecheck import accepts, returns, Any >>> @accepts(str, int, Any()) @returns(list) def makelist(a, b, c): return [a, b, c] >>> makelist("spam", 42, object()) ['spam', 42, ] >>> makelist(42, "spam", 3.4) Traceback (most recent call last): File "", line 1, in makelist(42, "spam", 3.4) File "C:\Python25\lib\site-packages\typecheck-0.3.5-py2.5.egg\typecheck\__init__. py", line 1340, in fake_function File "C:\Python25\lib\site-packages\typecheck-0.3.5-py2.5.egg\typecheck\__init__. py", line 1419, in __check_args TypeCheckError: Argument a: for 42, expected , got >>> I tried using DBC for a time in C++ (using a library with a clever assembly-language hack). I personally found it neater having such code in unit tests, but obviously, it's a matter of preference. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Printing lists in columns
> On Behalf Of [EMAIL PROTECTED] > bo, daf, da > pres, ppar, xppc > magnjklep, *, dsa > *, *, nbi > > But I want it justified, i.e: > > bo , daf, da > pres , ppar, xppc > magnjklep,*, dsa > *,*, nbi Once you have a nice rectangular list of lists, you might want to take a look at my padnums module. # Usage: import padnums import sys table = [row for row in izip_longest(*d, fillvalue='*')] padnums.pprint_table(sys.stdout, table) Code described here, with link to module: http://ginstrom.com/scribbles/2007/09/04/pretty-printing-a-table-in-python/ Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: newbie: self.member syntax seems /really/ annoying
> On Behalf Of Charles Fox > described mathematically in papers, by equations like > a_dot = -k(a-u) > In other languages, this translates nicely into code, but as > far as I can tell, Python needs the ugly: > self.a_dot = -self.k(self.a-self.u) In addition to the other advice you've received, if you don't need to preserve state, you could avoid the "self" business by putting your functions in a module instead of an object. def k(a): return a**3 def dot(a, u) return -k(a-u) Python modules are also objects, so they can serve in place of class instances much of the time. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: newbie: self.member syntax seems /really/ annoying
> On Behalf Of madzientist > As a newbie to Python (and OOP), I would love to hear what > people think of Steven's suggestion below. Is there a reason > why classes would be useful for the OP's question ? If you > can point me to a brief online tutorial addressing this, I > would happily go there to read it too :) In general, you should use classes when you need to maintain state. The classic example is a BankAccount class, each instance of which maintains a "balance" state. When you don't need to maintain state, module-level functions are fine. In fact, for testability/reliability, they're preferred, because when a method twiddles some internal state, it's much harder to test. It's valuable to have a function that always gives output x for input y, with no side effects. That (to me) is the appeal of the functional programming style. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Coming from Perl
> On Behalf Of Amer Neely > I saw that and I guess that is the closest thing. In Perl I can do .. > > print < > > Hello > > > EndHTML >>> data = dict(title="Python Rocks!", content="I heart Python") >>> template = """ %(title)s %(content)s """ >>> print template % data Python Rocks! I heart Python >>> You might also want to check out string.Template (http://docs.python.org/lib/node40.html), or even move on to one of the many, many templating languages (Mako, Cheetah, Kid, etc.) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Setting stdout encoding
> On Behalf Of Fabio Zadrozny > Makes sense... Do you think that creating a new object, > setting it as sys.stdout and overriding its write() method to > check for a unicode string to do > original_stdout.write(unicode_str.encode(my_encoding)) would > do it? Here's an output stream encoder I have used. It might be kind of screwball, so I'd welcome any feedback on it, but it does work for encoding output streams. import sys class OutStreamEncoder(object): """Wraps an out stream with an encoder""" def __init__(self, outstream, encoding=None): self.stdout = outstream if not encoding: self.encoding = sys.getfilesystemencoding() else: self.encoding = encoding def write(self, obj): """Wraps the output stream's write method, encoding it with the specified encoding""" self.stdout.write(obj.encode(self.encoding)) def __getattr__(self, attr): """Delegate everything but write to the stream""" if attr != "write": return getattr(self.stdout, attr) return self.write >>> from cStringIO import StringIO as si >>> out = si() >>> nihongo = unicode("日本語", "sjis") >>> print >> out, nihongo Traceback (most recent call last): File "", line 1, in print >> out, nihongo UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) >>> out = OutStreamEncoder(out, "utf-8") >>> print >> out, nihongo >>> val = out.getvalue() >>> print val.decode("utf-8") 日本語 >>> Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Setting stdout encoding
> On Behalf Of Gabriel Genellina > You should check that obj is an unicode object before calling > encode. > Strings should not be encoded. ... > __getattr__ is only called when the attribute has NOT been > found in the usual way, so checking for "write" is > unnecesary. Just return getattr(self.stdout, attr) always. Thanks a lot. Here is my modified class: import sys class OutStreamEncoder(object): """Wraps a stream with an encoder """ def __init__(self, outstream, encoding=None): self.out = outstream if not encoding: self.encoding = sys.getfilesystemencoding() else: self.encoding = encoding def write(self, obj): """Wraps the stream's output stream, encoding unicode strings with the specified encoding""" if isinstance(obj, unicode): self.out.write(obj.encode(self.encoding)) else: self.out.write(obj) def __getattr__(self, attr): """Delegate everything but write to the stream""" return getattr(self.out, attr) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Python statements not forcing whitespace is messy?
> On Behalf Of J. Cliff Dyer > On the other hand, this is just as bad: > > [ ( y ) for ( x , y ) in [ ( "foo" , 2 ) , ( "bar" , 4 ) ] if > "foo" in ( x ) ] I think that's allowed in order to recruit C/C++ programmers. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: lambda-funcs problem
> On Behalf Of [EMAIL PROTECTED] > F = [] > for i in xrange(N): > F.append(lambda x: x + i) > > however, the example don't work - since i in end is N-1 it yields x+ > (N-1) for any func. How about: >>> def make_adder(i): def adder(x): return x+i return adder >>> funcs = [make_adder(i) for i in xrange(10)] >>> print [func(10) for func in funcs] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Test-driven development and code size
> On Behalf Of Joel Hedlund > My presumption has been that in order to do proper > test-driven development I would have to make enormous test > suites covering all bases for my small hacks before I could > getting down and dirty with coding (as for example in > http://www.diveintopython.org/unit_testing). This of course > isn't very appealing when you need something done "now". But > if I understand you correctly, if I would formalize what > little testing I do, so that I can add to a growing test > suite for each program as bugs are discovered and needs > arise, would you consider that proper test-driven > development? (or rather, is that how you do it?) Have you looked at nose? http://somethingaboutorange.com/mrl/projects/nose/ It automatically discovers your unit tests and runs them. I have a command in my Komodo toolbox that runs the nosetests script on the current directory. So the overhead of writing (and running) unit tests is very small. Usually, even when developing one-off scripts, you'll try some test cases, maybe do some testing at the interactive prompt. That can serve as the basis of your unit tests. Then maybe the first time you want to import that module from another script, you can beef up your unit tests then. If unit testing seems like too much work, people won't do it. So I think it's good to start out by doing just enough unit testing that it's not onerous. As you see the benefits, you'll probably seem them as less onerous, of course. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Wrapper functions and arguments
> On Behalf Of Jeremy Sanders > def a(x, y, z): > print x, y, z > def b(x, y, z='fruitbat') > print x, y, z > > for func in a, b: > def wrapper(func=func, *args, **argsk): > # do something > func(*args, **argsk) > x.append(wrapper) > > x[0](1, 2, 3) > x[1](1, 2) > ... > > Is there any way to do this? Can you capture arguments in a > tuple and dict, but still receive other keyword arguments? I think you're missing one level of wrapping. >>> def a(x, y, z): print x, y, z >>> def b(x, y, z='fruitbat'): print x, y, z >>> x = [] >>> for func in a, b: def wrapper(func): def wrapped(*args, **kwds): print "wrapped!" func(*args, **kwds) return wrapped x.append(wrapper(func)) >>> x[0](1, 2, 3) wrapped! 1 2 3 >>> x[1](1, 2) wrapped! 1 2 fruitbat >>> --- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: interfacing Python interpreter with a VB6 frontend
> On Behalf Of Anonymous > This requires several steps, but the one I am having most > problem finding info on is the ff: > > 1. using/interacting the Python interpreter from VB6 One way to do this might be by creating a COM server with Python, and having VB feed it lines of text and then collect results of execution for display. win32com has demos of COM servers. -- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: unit testing
> On Behalf Of Bruno Desthuilliers > Or py.test or nose, which are both more complete than doctest > and more pythonics than the unittest module. I second the recommendation of nose. It makes it fantastically easy to write and run unit tests. Also, in my experience unit tests help reduce bugs in the development process, but their main benefits are making code more modular (writing for testing tends to reduce dependencies) and easier to modify (less fear in refactoring). Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Entering username & password automatically using urllib.urlopen
> On Behalf Of rodrigo > I am trying to retrieve a password protected page using: > > get = urllib.urlopen('http://password.protected.url";').read() I would suggest looking at mechanize. http://wwwsearch.sourceforge.net/mechanize/ from mechanize import Browser USERNAME = "user" PASSWORD = "secret" LOGIN_PAGE = "http://password.protected.url/"; browser = Browser() browser.open( LOGIN_PAGE ) # log in browser.select_form( nr=0 ) # Assuming log in form is first form on the page # Check the form for the actual field names... browser['user'] = USERNAME browser['pass'] = PASSWORD browser.submit() # Content goodness follows... ## Of course, this assumes that the site doesn't use some kind of JavaScript trickery to prevent automation like the above. In that case, you'd have to use something like PAMIE http://sourceforge.net/projects/pamie/ HTH, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Wrapping stdout in a codec
> On Behalf Of JKPeck > otherwise anonymous. How can we accomplish this wrapping? > Our application may be loaded into a Python program that has > already set up stdout. Do you mean something like this? import sys class OutStreamEncoder(object): """Wraps a stream with an encoder""" def __init__(self, outstream, encoding=None): self.out = outstream if not encoding: self.encoding = sys.getfilesystemencoding() else: self.encoding = encoding def write(self, obj): """Wraps the output stream, encoding Unicode strings with the specified encoding""" if isinstance(obj, unicode): self.out.write(obj.encode(self.encoding)) else: self.out.write(obj) def __getattr__(self, attr): """Delegate everything but write to the stream""" return getattr(self.out, attr) You can wrap sys.stdout easily: sys.stdout = OutStreamEncoder(sys.stdout) The code, with unit tests: http://www.ginstrom.com/code/streamencode.zip Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: ignoring chinese characters parsing xml file
> On Behalf Of Fabian Lopez > like ^�u�u啖啖才是�w.���扉L锍才是�� or ヘアアイロン... The problem is that I get Just thought I'd point out here that the second string is Japanese, not Chinese. >From your second post, it appears that you've parsed the text without problems -- it's when you go to print them out that you get the error. This is no doubt because your default encoding can't handle Chinese/Japanese characters. I can imagine several ways to fix this, including encoding the text in utf-8 for printout. If you really want to strip out Asian characters, here's a way: def strip_asian(text): """"Returns the Unicode string text, minus any Asian characters""" return u''.join([x for x in text if ord(x) < 0x3000]) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: japanese encoding iso-2022-jp in python vs. perl
> On Behalf Of kettle > I am rather new to python, and am currently struggling with some > encoding issues. I have some utf-8-encoded text which I need to > encode as iso-2022-jp before sending it out to the world. I am using > python's encode functions: > -- > var = var.encode("iso-2022-jp", "replace") > print var > -- Possibly silly question: Is that a utf-8 string, or Unicode? print unicode(var, "utf8").encode("iso-2022-jp") On my computer (Japanese XP), your string round-trips between utf-8 and iso-2022-jp without problems. Another possible thing to look at is whether your Python output terminal can print Japanese OK. Does it choke when printing the string as Unicode? Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: list (range) syntax
> On Behalf Of Steven D'Aprano > Because in common English, counting starts at 1 and ranges > normally include both end points (that is, it is a "closed" > interval). If you say "I'll be away from the 4th to the 7th" > and then turn up on the 7th, nearly everyone will wonder why > you're back a day early. Actually, I think this illustrates the point about confusion, because in the United States at least, "the 4th to the 7th" will not necessarily include the 7th. That's why it's common to use circumlocutions like "the 4th through the 7th" and "the 4th to the 7th, inclusive" when one wants to be sure. At any rate, I also think that having range(1, 10) or a similar construct mean one to ten (inclusive ) is a bad idea. Ruby's philosophy is obviously different, which is probably fine as long as you know your tradeoffs. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Finding decorators in a file
> On Behalf Of Andrew West > Basically what I'm looking for is a way to, given a python file, look > through that file and find all the decorators and the associated > functions, that includes any arguments that the decorator has. The inspect module has a function called "findsource" import inspect import my_module lines, line_num = inspect.findsource(my_module) decorated_lines = [num for num, line in enumerate(lines) if line.strip().startswith("@")] Probably a little more complicated than that -- like what if a function has two decorators? -- but I think the basic idea will work. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: simple question on dictionary usage
> On Behalf Of Edward Kozlowski > I think this should do the trick. There's probably something > more concise than this, but I can't think of it at the moment. > > egt = {} > for key in record: > if key.startswith('E'): > egt[key] = record[key] Not much more concise, but another way: egt = dict((key, record[key]) for key in record if key.startswith('E')) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: posting to a form with no form name
> On Behalf Of [EMAIL PROTECTED] > posting to a form with no form name or it's just that i cant > find the form name. > can anyone explain how to either post to a form with no name > or, find the name of the form..here my current output, but i > dont see a form name, also, there is only 1 form on the page I believe you want Browser.select_form(nr=0) # Using mechanize # http://wwwsearch.sourceforge.net/mechanize/ from mechanize import Browser browser = Browser() browser.open("http://example.com";) browser.select_form(nr=0) browser['username'] = "me" browser['password'] = "secret" browser.submit() Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: How to Create pyd by C#
> On Behalf Of jane janet > I'm wondering how to create extension fill (.pyd) or anything > that seem like DLL file by C# language. If you are going to be using C#, I would suggest that you create an ordinary assembly, and call it via IronPython. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Catching and automating a win32 MessageBox
> On Behalf Of Xavier Homs > Is there any way to hook such a MessageBox a send a default > action (yes) from a Python Script? A pure Python solution is pywinauto: http://www.openqa.org/pywinauto/ Another solution is AutoIt http://www.autoitscript.com/autoit3/ It has a COM server, which you can automate from Python. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: VB6 frontend GUI with Python
> On Behalf Of Claire Blair > I am trying to write a VB6 (not VB.Net) application that has > a console window that allows Python command to be typed at the prompt. I'm not sure what pieces of the puzzle you're missing. Were you able to create a simple COM server with Python? At a conceptual level, how about this: * Your VB form creates an instance of the Python COM server * You pass a reference to the form to the COM server (server.SetForm Me 'etc...) * You have a textbox in your VB form. You listen for Return key events * When you get a return key, you call a method on the COM server that says "submit text line" * The COM server examines the last line of text in the form's text box, and takes any necessary action, including: + Eval a line of interactive Python code + Write a result to the VB form's text box Do the above steps sound feasible? Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Equivalent of perl's Pod::Usage?
> On Behalf Of Nick Craig-Wood > As for Pod::Usage - write the instructions for your script as > a docstring at the top of your file, then use this little function... > > def usage(error): > """ > Print the usage, an error message, then exit with an error > """ > print >>sys.stderr, globals()['__doc__'] > print >>sys.stderr, error > sys.exit(1) argparse[1] also prints out very pretty usage for you. [1] http://argparse.python-hosting.com/ Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: tail a file (win)
> Behalf Of david brochu jr > I wrote a script to monitor ping activity and output it to a > log file. I am using windows and want to have another script > constantly check the latest entry to see if Request timed out > is seen. Is there a way to "tail" a file much like I would in > Unix so I can just see the latest entry and move from there? The method I would use that is not RAM/CPU intensive would be to create a memory-mapped file, take the size of the file, and increment your pointer to file_length - tail_size. The Windows API functions to look at are: CreateFile CreateFileMapping MapViewOfFile I'm sorry, but I'm not a ctypes guru so can't tell you how you would accomplish this in python. (The C(++) code is fairly straightforward, however). --- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
Hooking things up in GUI application
Apropos recent threads about GUI editors, coming from a Win32/WTL C++ background, I actually like the idea of being able to (easily) create GUIs programmatically. But I still see a lot of the same tedium: hooking up events to handlers, and getting data into and out of dialogs. In C++, this is generally handled through code generation and/or macros, but IMO these are brittle and ugly. So my question: Is there a Pythonic way to make these tedious hookups easier? --- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Counting elements in a list wildcard
> Behalf Of hawkesed > If I have a list, say of names. And I want to count all the people > named, say, Susie, but I don't care exactly how they spell it (ie, > Susy, Susi, Susie all work.) how would I do this? Set up a regular > expression inside the count? Is there a wildcard variable I can use? > Here is the code for the non-fuzzy way: > lstNames.count("Susie") > Any ideas? Is this something you wouldn't expect count to do? > Thanks y'all from a newbie. If there are specific spellings you want to allow, you could just create a list of them and see if your Suzy is in there: >>> possible_suzys = [ 'Susy', 'Susi', 'Susie' ] >>> my_strings = ['Bob', 'Sally', 'Susi', 'Dick', 'Jane' ] >>> for line in my_strings: ... if line in possible_suzys: print line ... Susi I think a general solution to this problem is to use edit (also called Levenshtein) distance. There is an implementation in Python at this Wiki: http://en.wikisource.org/wiki/Levenshtein_distance You could use this distance function, and normalize for string length using the following score function: def score( a, b ): "Calculates the similarity score of the two strings based on edit distance." high_len = max( len(a), len(b) ) return float( high_len - distance( a, b ) ) / float( high_len ) >>> for line in my_strings: ... if score( line, 'Susie' ) > .75: print line ... Susi -- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Hooking things up in GUI application
> Behalf Of sturlamolden > If you use PyGTK (it also runs on Windows), you can design > the GUI with > GLADE and then use libglade to import the gui as an xml-resource. Yes, I've tried something similar with wxGlade. Nice, but it doesn't seem to remove the most tedious work -- hooking up handlers (although it does help here, at the cost of some behind-the-scenes magic), and getting data into and out of GUI widgets. That's the kind of boilerplate code that makes GUI development a pain in my opinion -- the actual GUI design/layout isn't so bad, especially with the spacer layout concept. -- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Hooking things up in GUI application
> Behalf Of sturlamolden > Ryan Ginstrom wrote: > > > Yes, I've tried something similar with wxGlade. > > But GLADE is not wxGlade :-) Yes, I'm just saying that I've done something similar to your example. In fact, wxCard also does this auto-generation of handlers. That's a start, but it's still auto-generated code -- XML doesn't save you from that -- and it doesn't do the meaty stuff. (I chose wxWidgets over GTK because, despite GTK-Wimp, I think wxWidgets' support on Windows is better.) There are many philosophies to GUI design, and mine problably isn't the best, but I actually like having my design in the code. I think it saves a layer of abstraction, it's easier to test/modularize, and still doesn't prevent you from separating the GUI layer from the business logic, especially in a language like Python. But I don't want to argue this point, just state that this isn't the problem I want to solve. I really liked the idea of KVO/KVC in Cocoa that James Stroud mentioned. That is what I am after, or something like that. If there isn't anything like that, I think that it might be worthwhile to port it to Python in some form. It seems at first glance that it would be fairly easy to do. -- Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Look for a string on a file and get its line number
> On Behalf Of Horacius ReX > I have to search for a string on a big file. Once this string > is found, I would need to get the number of the line in which > the string is located on the file. Do you know how if this is > possible to do in python ? This should be reasonable: >>> for num, line in enumerate(open("/python25/readme.txt")): if "Guido" in line: print "Found Guido on line", num break Found Guido on line 1296 >>> Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: docstrings style question
> On Behalf Of Steve Brown > What do you think? I think that comments are for maintainers, and docstrings are for users. Some of the things I use comments for: * Visually separate classes (using a syntax-highlighting editor) * Explain algorithm choices * Explain bug fixes so I don't later "fix" code back to the buggy version Some of the things I use docstrings for: * Describe interface (inputs/outputs) * Sample usage I personally don't use doctests, but that's one more use of docstrings. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Win32com and Excel
> On Behalf Of Mike P > Does anyone have any code that does something similar? My > guess is i have to do something like thefollowing to enable > python to read xl? I think that what you want is UsedRange for row in sheet.UsedRange.Value: ... Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: for loop without variable
> On Behalf Of Marty > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" > statement (and also why has it not come up in this thread)? > I realize the topic has probably been beaten to death in > earlier thread(s), but does anyone have the short answer? data_out = [[] for item in data_in] Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: [OT] "Code Friendly" Blog?
> On Behalf Of Miki > Posting code examples to blogger.com hosted blog is not fun > (need to remember alway escape < and >). > Is there any free blog hosting that is more "code friendly" > (easy to post code snippets and such)? I use WordPress with the Dean's Code Highlighter plugin[1] (which uses the Geshi code highlighter). You write your code like this: print "hello, world!" You do need to escape angle brackets, though. You also have to turn off WYSIWYG editing in WordPress, or it'll mess things up. Here's an example of how it turns out: http://ginstrom.com/scribbles/2007/11/17/fixing-jis-mojibake-with-python/ [1] http://www.deanlee.cn/wordpress/code_highlighter_plugin_for_wordpress/ Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Has Anyone Worked with Gene Expression Programming???????????????????????????
> On Behalf Of Daniel Fetchinson > Actually, it turns out I might say I'm a world known expert > of Gene Expression Programming. > The only thing is that some higher powers are preventing me > from telling you about it. > I'm really sorry, I hope you understand. Please don't ask > questions. It's not safe to know too much about this stuff. > One day, my son, you'll understand. You'll understand. The first rule of Gene Expression Programming is - you do not talk about Gene Expression Programming. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: dict comprehension
> On Behalf Of Daniel Fetchinson > What does the author mean here? What's the Preferably One Way > (TM) to do something analogous to a dict comprehension? I imagine something like this: >>> keys = "a b c".split() >>> values = [1, 2, 3] >>> D = dict([(a, b) for a, b in zip(keys, values)]) >>> D {'a': 1, 'c': 3, 'b': 2} Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Automating GUI interaction with Python
> On Behalf Of jorma kala > Is there a python library or bindings to a library in some > other language for automating GUI interaction (the kind of > functionality provided by Autoit for instance). > What I need to do is very simple GUI automation : moving the > mouse cursor to and from specified screen coordinates, clicking, etc. > Thanks a lot. For Windows, try pyWinAuto http://pywinauto.openqa.org/ Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Article of interest: Python pros/cons for the enterprise
> On Behalf Of Nicola Musatti > Newbies learn, and the fundamental C++ lessons are usually > learnt quite easily. Unless we're talking about idiots, that > is, but in this case at least C++ is likely to make their > deficiencies evident sooner than most other programming > languages. So, yes, your big company is likely to be safer > with newbie C++ programmers than with Python newbie programmers. The danger of memory leaks alone makes C++ a decidedly newbie-unfriendly language. Java I might go along with, but C++? Regards, Ryan Ginstrom (who learned C++ before Python and has grappled with his share of memory bugs) -- http://mail.python.org/mailman/listinfo/python-list
RE: Article of interest: Python pros/cons for the enterprise
> On Behalf Of Jeff Schwab > When I see this silliness again and again, it really breaks > my heart If you allow your heart to be broken by others' opinions, you're setting yourself up for a lot of disappointment IMHO. I personally used C++ for about 90% of my code for 10 years. During that time, I was chugging the C++ Kool-Aid so hard I almost peed myself. I still think that C++ is a beautiful language, but I have also come to think that starting a program with C++ is a premature optimization. I think that very few Python programmers today started with Python. Most of them came to Python for a reason. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Hyphenation module PyHyphen-0.3 released
> On Behalf Of Max Erickson > the easy way to do this might be to find(in your mingw /lib > directory) and copy or rename libmsvcr71.a and libmsvcr71d.a > into libmsvcrt.a and libmsvcrtd.a (backing up the originals > if desired). If the MingW you have installed doesn't provide > the appropriate runtime, you would have to track that down. Here's another way. Go to /MinGW/lib/gcc/mingw32/3.4.2/spec, and modify the libgcc directive as follows: *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Unit testing Web applications
> On Behalf Of Monica Leko > Does Python has some testing frameworks for testing Web > applications (like Cactus and HttpUnit for Java), generating > requests and checking if the response is correct? I have got a lot of traction using mechanize [1] with nose [2]. Of course that still leaves out testing JavaScript. For that, something like PAMIE [3] is one way to go. [1] http://wwwsearch.sourceforge.net/mechanize/ [2] http://somethingaboutorange.com/mrl/projects/nose/ [3] http://pamie.sourceforge.net/ Here's an example of how I use mechanize + nose: # test_index.py from mechanize import Browser class TestPageLoads: def setup(self): self.mech = Browser() self.mech.set_handle_robots(False) # use thought and consideration... def test_nonexistent(self): try: response = self.mech.open("http://honyaku-archive.org/nonexistent/";) assert False, "Should have thrown here" except Exception, e: assert "404" in str(e), e def test_index(self): response = self.mech.open("http://honyaku-archive.org/";) assert response.code == 200, response.code def test_index_title(self): response = self.mech.open("http://honyaku-archive.org/";) assert self.mech.title().strip() == "Honyaku Archive :: Home", self.mech.title() Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: SV: Regarding coding style
> On Behalf Of Grant Edwards > I think docstrings are a great idea. What's needed is a way > to document the signature that can't get out-of-sync with > what the fucntion really expects. Like doctests? (I know, smart-ass response) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: any chance regular expressions are cached?
> On Behalf Of Tim Chase > Sounds like what you want is to use the compile() call to > compile once, and then use the resulting objects: > >re1 = re.compile(r'\n') >re2 = re.compile(r'^') >... >s = re1.sub('\n' + spaces, s) >s = re2.sub(spaces, s) Yes. And I would go a step further and suggest that regular expressions are best avoided in favor of simpler things when possible. That will make the code easier to debug, and probably faster. A couple of examples: >>> text = """spam spam spam spam spam spam spam""" >>> # normalize newlines >>> print "\n".join([line for line in text.splitlines() if line]) spam spam spam spam spam spam spam >>> # normalize whitespace >>> print " ".join(text.split()) spam spam spam spam spam spam spam >>> # strip leading/trailing space >>> text = " spam " >>> print text.lstrip() spam >>> print text.rstrip() spam >>> print text.strip() spam Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Edit and continue?
> On Behalf Of Bronner, Gregory > I'm working on a GUI application that has lots of callbacks. > Testing it is very slow and quite boring, as every time I > find an error, I have to exit it, restart it, and repeat the > series of clicks. It would be really amazing if python > supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my > code and have it apply to a running instance of a class. What framework are you using? Also, automating those pesky clicks and such should make your GUI testing a lot easier. There are two angles of approach: "driving" the GUI automatically, and stubbing out/mocking the windowing methods so that you can test GUI components in a unit-testing framework. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Dispatch("Excel.Application") failed
> On Behalf Of John Machin > > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > > None, None) > > Googling for 2147221005 gives some clues. > > That string of hex stuff appears where an error message is > expected -- it's not utf8, and makes no sense when I attempt > to decode it with cp1250 to cp1258 inclusive. If you start > IDLE and type: The hex stuff is Chinese. It appears to be a standard Windows error message. 无效的类别字符串 (Which I believe meaans "invalid class string") I wrote in another post (that doesn't appear to have made it to the list) that the call to Dispatch on Excel will fail if the formula bar edit box is active. Just another idea. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Decode email subjects into unicode
> On Behalf Of Laszlo Nagy > > =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?= > > [Fwd: re:Flags Of The World, Us States, And Military] > > =?ISO-8859-2?Q?=E9rdekes?= =?UTF-8?B?aGliw6Fr?= Try this code: from email.header import decode_header def getheader(header_text, default="ascii"): """Decode the specified header""" headers = decode_header(header_text) header_sections = [unicode(text, charset or default) for text, charset in headers] return u"".join(header_sections) I get the following output for your strings: Быстровыполнимо и малозатратно érdekeshibák Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Duplicating list of lists [newbie]
> On Behalf Of [EMAIL PROTECTED] > So - it looks that in list "b" there copy of all objects from list "a" > including not copy of list [5,6,7] but reference to it. > > Is there simple way to copy a into b (like a[:]) with all > copies of all objects going as deep as possible? Or it can be > done only manually? I'd suggest checking out copy.deepcopy. >>> a = [1, [1, 2, 3], 2] >>> b = a[:] >>> a[1][2] = 'spam' >>> b [1, [1, 2, 'spam'], 2] >>> from copy import deepcopy >>> b = deepcopy(a) >>> a[1][2] = 'deepcopy is your friend' >>> b [1, [1, 2, 'spam'], 2] Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Testing for an empty dictionary in Python
> On Behalf Of John Nagle >What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). I believe that the following is fairly efficient: >>> def dict_is_empty(D): for k in D: return False return True >>> dict_is_empty(dict(a=1)) False >>> dict_is_empty({}) True Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Breaking the barrier of a broken paradigm... part 1
> On Behalf Of john s. > import os, sys, string, copy, getopt, linecache > from traceback import format_exception > > #The file we read in... > fileHandle = "/etc/passwd" > srcFile = open(fileHandle,'r') > srcList = srcFile.readlines() > > #yah, a for loop that "iterates" through the file of "lines" > for i in srcList: > strUsr = string.split(i,":") > theUsr = strUsr[0] > usrHome = "/expirt/home/",theUsr,"/" > usrHome = ''.join(usrHome) How about for starters: import os for line in open("/etc/passwd"): user, _pwd = line.split(":") user_home = os.path.join("/expirt/home", user) > try: > os.makedirs('usrHome' ) > except Exception, e: > print e if os.path.exists(user_home): print "User Home dir exists, checking and fixing permissions." else: print "Do other stuff" Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Breaking the barrier of a broken paradigm... part 1
> On Behalf Of Bruno Desthuilliers > >> for line in open("/etc/passwd"): > > NB : this idiom relies on the VM automatically closing files, > which is not garanteed on each and every implementation > (IIRC, jython won't do it). This is ok for Q&D throwaway > scripts targeting CPython, but should not go into production code. You're right. For production, I'd probably do this. def create_user_dirs(lines): for line in lines: pass # process lines here with open("/etc/passwd") as fp: create_user_dirs(fp) This has the benefit of allowing me to test create_user_dirs without touching the file system (by passing in a list of lines). Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: unittest: Calling tests in liner number order
> On Behalf Of Roy Smith > You could have a bunch of tests of increasing complexity. > The first bunch of tests all run in a few seconds and test > some basic functionality. From experience, you also know > that these are the tests that are most likely to fail as you > port to a new environment. > > There's also some tests which take a long time to run. If > the basic stuff that's being tested by the earlier tests > doesn't work, there's no way these tests could pass, but they > still take a long time to fail. How about something like this: def run_quickies(): # run the quick, i.e. actual unit tests # located in folder ./unit_tests/ def run_long_ones(): # Run function tests, integration tests, what have you # located in folder ./integration_tests/ def whole_shebang(): run_quickies() run_long_ones() Now you do something like run the unit tests every time a file is saved, and run the whole shebang nightly and every time a build is performed. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: [Business apps for Windows] Good grid + calendar, etc.?
> On Behalf Of Gilles Ganault > Is it hopeless, or did I overlook things? Are there other > solutions I should look at (FLTK, etc.)? For those of you > writing business apps in Python for Windows, how do things go > as far as GUI widgets are concerned? To do a bit of shameless plugging, I wrote an overview of Python GUI platforms for Windows a month or two ago: http://ginstrom.com/scribbles/2008/02/26/python-gui-programming-platforms-fo r-windows/ For your stated needs, I'd advise checking out IronPython or Python.NET (which allow use of .NET GUI libraries). Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: [Business apps for Windows] Good grid + calendar, etc.?
> On Behalf Of Gilles Ganault > Thanks but I forgot to say that I'd rather not use .Net > because deployment/updates are too problematic for our audience. > > .. that's assuming that a GUI Python can install/update > itself as easily as eg. Delphi, which is where I could be wrong :-/ wxPython can be made to look pretty nice. Check out Chandler for an example. http://chandlerproject.org/ Delphi has a truly impressive ecosystem of controls and widgets. If there were a commercial market for wxPython/wxWidgets widgets, I'm sure we'd get a bunch of very nice ones as well. There is kind of an analog with the "bounty" program for developing widgets, but it doesn't appear very active. If you don't mind being Windows-only, there's another approach that I've been working on. I use a WTL application to host the web browser, then pass the browser instance to a COM server written in Python, along with a COM wrapper of the application window. This gives me the flexibility of HTML + JavaScript + Python, but eliminates two of the big issues with web apps: latency and lack of Windows conventions like keyboard shortcuts and Drag & Drop. I've yet to deploy this approach in an application, but from my prototypes I'm liking it. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: [Business apps for Windows] Good grid + calendar, etc.?
> From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > Instead of the COM approach, have you considered using a > local, client based Python server as a container for your > business logic and GUI (DHTML, AJAX)? This would give you a > cross platform solution, without the typical browser/server > latency, and via techniques like AJAX, perhaps more of a > desktop look and feel? I haven't done this yet, but I'm > grappling with the same question ("how to create sexy looking > business applications using Python"). I have used a cherrypy server wrapped with py2exe for a "desktop server app", but the local server in the browser solution has some weaknesses. Drag and drop is one. Another is native dialog boxes. A third is problems with firewalls. And although you can do keyboard shortcuts with Ajax, the mechanism isn't quite the same. Also, using COM you can manipulate the DOM from Python, removing the need for AJAX. In that case, your only need for JavaScript would be for prebuilt library functionality (assuming you like Python better than JavaScript). Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Build complete, now I just need to "install" it...
> On Behalf Of axl > Since I don't have access to MSVS 2003 I need to rebuild > Python using MSVS 2008 in order for the binaries to go along. Another option is to compile your extensions with gcc, and specify that it link to MSVCR71.dll as the C runtime. For MinGW, it's sufficient to edit the specs (e.g. in C:\MinGW\lib\gcc\mingw32\3.4.2) like so: *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 And tell distutils to use mingw, by putting this in lib/distutils/distutils.cfg: [build] compiler=mingw32 [build_ext] compiler=mingw32 Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Automatically fill in forms on line
> On Behalf Of Jackie Wang > I want to automatically complete the following task: > > 1. Go to http://www.ffiec.gov/Geocode/default.aspx; ... > > Can Python realize these steps? Can these steps be done > witout openning and IE windows? Especially, I dont know how > to write code for step 2, 4 and 5. I suggest looking at mechanize: http://wwwsearch.sourceforge.net/mechanize/ If you're going to do this frequently, you also might want to check out the site's policy on robots. Mechanize does have a function to automatically handle a site's robots.txt. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Copy Stdout to string
> On Behalf Of sophie_newbie > Hi, I'm wondering if its possible to copy all of stdout's > output to a string, while still being able to print on > screen. I know you can capture stdout, but I still need the > output to appear on the screen also... If I understand you correctly, the following class should work. from StringIO import StringIO class OutBuffer(object): """Wraps a stream, and keeps output as a buffer Usage: >>> import sys >>> sys.stdout = OutBuffer(sys.stdout) >>> print "spam" spam >>> print "egg" egg >>> sys.stdout.getvalue().splitlines() ['spam', 'egg'] """ def __init__(self, outstream): self.out = outstream self.buffer = StringIO() def write(self, obj): """Writes obj to the output stream, storing it to a buffer as well""" self.out.write(obj) self.buffer.write(obj) def getvalue(self): """Retrieves the buffer value""" return self.buffer.getvalue() def __getattr__(self, attr): """Delegate everything but write and getvalue to the stream""" return getattr(self.out, attr) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: ANN: pry unit testing framework
> On Behalf Of Ben Finney > Aldo Cortesi <[EMAIL PROTECTED]> writes: > > Some day I might experiment with extending Pry to gather and run > > doctests and unittests. At this stage, however, I don't believe the > > (significant) effort would be worth it. > > That's very unfortunate. Until it plays better with others, I > don't believe the effort of using this package will be worth it. I also don't want to be negative, since Aldo obviously has put a lot of work into this framework. But since it's not compatible with other frameworks, it will mainly be attractive to people not writing unit tests now, which means they: 1) Think writing unit tests is too much of a hassle, or 2) Ae new (Python) programmers In either case, the key requirement of the framework would be ease of use, but Pry's selling point is actually its sophisticated options. Thus it appears that the potential user base is rather small... Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Splitting MainWindow Class over several modules.
> On Behalf Of Mike Driscoll > I don't think there's anything wrong with it. The main thing > to remember is to try to keep the interface and the logic > separate. I have a fairly complex program with lots of tabs > and sub tabs. So I stuck each of the tab's display code in a > separate file and imported them into my main program. There are also several signaling techniques that make it easy to separate the GUI logic from the message-processing logic. Or you could simply have a controller class that instantiates the GUI class and registers itself as the message listener. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: firefox add-on to grab python code handily?
> On Behalf Of Larry Bates > Since most of us keep Idle or some other Python IDE open > nearly 100% of the time we just copy from webpage, paste into > new Python document, and run in the IDE. > While you could clearly write a plug-in for FF to achieve > this, IMHO I doubt many people would actually use it. Not that I'm going to implement it, but it would be really neat to tie something together with codepad[1] [1] http://codepad.org/ (With the site owner's permission, of course!) Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Registration Code
> On Behalf Of Dave Mandelin: > Second, I hear that in general it is very difficult to make a > time-limited demo, because the code has to be all there, so all a > cracker has to do is bypass the "if". It seems that even this method > won't work for that. Do you know of any way to make time limiting > secure? If the application is to be Windows only (and I assume this from statement about using py2exe), one fairly secure and easy method is to put some critical functionality into a plain DLL or (compiled) COM module, and use a commercial software-protection program like Armadillo on that. Armadillo is much more secure than just about anybody could make on their own, and instead of wasting time (and probably introducing bugs) implementing it yourself, you can use that time improving your application. Armadillo handles all sorts of protection schemes, from time limitations to machine locking and "crippling," and combinations thereof. (I have no commercial or other interest in Armadillo.) Another tack to take is to maintain content updates on a Website for download. The Website would check the registration code. This foils most cracking methods, and even shared codes can be blacklisted when found. Of course, this only works for certain types of applications, but when it is possible it has the benefits of not requiring significant changes to your application, remaining transparent to the user, and most importantly, not antagonizing legitimate users. And of course, it would enable cross-platform (commercial) use of your application. A variation of this strategy is the subscription model. Regards, Ryan --- Ryan Ginstrom http://ginstrom.com -- http://mail.python.org/mailman/listinfo/python-list
Framework/module for generating HTML documentation
I have been maintaining a body of documentation in plain HTML files. I would now like to automate the generation of the HTML files. Maintaining the HTML files now is tedious and error prone, because every time I move/remove/add a section, I have to renumber the following sections and update my internal links. I have looked at some of the HTML-generation frameworks, but the selection is somewhat bewildering, and most also seem geared to generating dynamic or static content for Websites. I guess what I am looking for is a Wiki-like documentation generation engine, but generating a bunch of statically linked files. E.g., I want to go from something like this: Introduction Some text Getting Started Some text Installation Some text. See Getting Started for details. To this: [index.html] Contents 1. Introduction 2. Getting Started 2.1. Installation [1.html] 1. Introduction Some text Contents Next [2.html] 2. Getting Started Some text Prev Contents Next [2_1.html] 2.1. Installation Some text. See Getting Started for details. Prev Contents Next If someone can recommend a framework/module that will help me achieve this, I would greatly appreciate it. I could do it from scratch, but if this has been tackled before (as I suspect it has), I'd like to stand on those developers' shoulders . Regards, Ryan --- Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Using PythonWin32 to copy text to Windoze Clipboard for Unix-stylerandom .sig rotator?
> On > Behalf Of [EMAIL PROTECTED] > I want to write a Python script that, when launched, will choose a > random .sig (from a list of about 30 cool ones I've devised), > and store > the .sig text in the Windows Clipboard, so I can then paste > it into any > Windows application. You might try looking into wxPython.wx.wxTheClipboard However, unless this is soley for your own use, I would suggest you try a different method. In my experience, users get annoyed when their clipboard contents are stepped on. One general, if messy, solution is to use pywinauto to type the text in directly. Another (much more ambitious) project would be to create a private clipboard, save the current clipboard contents there, and then swap them back in when you are done. Regards, Ryan --- Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list