Re: Is there a list comprehension for this?
liam_herron wrote: > > Given: > dw = [ 1, -1.1, +1.2 ] > > Suppose I want to create a list 'w' that is defined as > > w[0] = dw[0], > w[1] = w[0] + dw[1], > w[2] = w[1] + dw[2] > > Is there a list comprehension or map expression to do it in one or 2 > lines. >>> from itertools import * >>> data = [1, -1.1, 1.2] >>> N = 2 >>> [sum(item) for item in izip(*[chain(repeat(0, i), di) for i, di in enumerate(tee(data, N))])] [1, -0.10009, 0.099867] Should work for other values of N, too. No, I'm not serious about it... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python for me?
One resource you should always keep at hand is this extremely useful Quick Reference: http://rgruet.free.fr/PQR24/PQR2.4.html Study it carefully, there is a lot in there that can teach you about how Python works. Fire up IPython as well and start hacking! 2B -- http://mail.python.org/mailman/listinfo/python-list
Re: Quadratic Optimization Problem
[EMAIL PROTECTED] wrote: > I need to do a quadratic optimization problem in python where the > constraints are quadratic and objective function is linear. > > What are the possible choices to do this. Too bad these homework assignments get trickier every time, isn't it? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: re.match -- not greedy?
EXI-Andrews, Jack wrote: > the '*' and '+' don't seem to be greedy.. they will consume less in > order to match a string: > > >>> import re;re.match('(a+)(ab)','aaab').groups() > ('aa', 'ab') > > this is the sort of behaviour i'd expect from >'(a+?)(ab)' > > a+ should greedily consume a's at the expense of the string not matching They are greedy - they consume as much as possible *without* sacrificing the match. You are thinking I think of possessive quantifiers, such as found in Java, which *will* match as much as possible even if doing so causes the match to fail. This would be written: re.match('(a++)(ab)','aaab') Python doesn't support these possessive quantifiers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand Python objects
walterbyrd wrote: > 1) Can attributes can added just anywhere? I create an object called > point, then I can add attributes any time, and at any place in the > program? in general, yes, but that should be done sparingly. > 2) Are classes typically created like this: > > class Point: > pass > > Then attributes are added at some other time? no, classes with attributes are typically created like this: class Point: def __init__(self, x, y): self.x = x self.y = y p = Point(1, 2) i.e. attributes are created in the initialization function. > 3) What is with the __underscores__ ?? they're reserved for use by the interpreter, usually for calling special methods in you class: http://effbot.org/pyref/reserved-identifier-classes http://effbot.org/pyref/special-method-names > 4) Are parameters passed to an class definition? > > class Whatever(params): >pass no, that's the syntax used for inheritance. arguments passed to the class constructor are passed on to the initialization function (see the example above). for more on this, see the tutorial. Jay Parlar's gentle introduction from the community tutorial might be helpful: http://effbot.org/pytut/node11-baseline.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing/Splitting Line
Noah Rawlins wrote: > I'm a nut for regular expressions and obfuscation... > > import re > def splitline(line, size=4): > return re.findall(r'.{%d}' % size, line) > > >>> splitline("helloiamsuperman") > ['hell', 'oiam', 'supe', 'rman'] there are laws against such use of regular expressions in certain jurisdictions. -- http://mail.python.org/mailman/listinfo/python-list
file backup in windows
Hi ALL, I am a newbee programmer and started of with python recently. I am trying write a script which backups outlook (.pst ) files everytime I shutdown my system. I have writtern following code after some findings on net. My .pst file path is as follows " c:\documents and settings\060577\Local Settings\Application Data\Microsoft\Outlook " where 060577 represents username. I want my script to identigy the user logged in and go to the resp outlook folder or should be able to read outlook store directory path from registry and the copy the files to the desired path. --- how can i make the following code work, I have probelm with filepath declaration. --- import os, shutil filepath = ' C:\\Documents and Settings\\060577\\Local Settings\\Application Data\\Microsoft\\Outlook\\* ' backup = ' D:\\temp\\outlook ' os.system ("xcopy /s %s %s" % (filepath, backup)) - Thank you, Kk -- http://mail.python.org/mailman/listinfo/python-list
Re: How to sort list
Klaus Alexander Seistrup wrote: > Decorate-sort-undecorate? > > #v+ > > array = [] > > for addr in Emails: > (user, domain) = addr.split('@') > array.append((domain, user, addr)) > # end for > > array.sort() > > SortedEmails = [addr for (user, domain, addr) in array] > > #v- note that DSU is built into Python these days: L.sort(key=transform) so you could use e.g. Emails.sort(key=lambda s: s.partition("@")[::-1]) also see: http://preview.tinyurl.com/yc3qak http://effbot.org/zone/python-list.htm#sorting -- http://mail.python.org/mailman/listinfo/python-list
Python visual IDE
Hi to all, i am not sure if this question really belongs here but anyway, here it goes: I have seen a lot of IDEs for Python, a lot of good stuff but actually none of them has what, for example, Visual Studio has: a Visual Editor (with the ability to place controls on forms etc etc), or RAD I know that there is Glade but does anybody knows of some product, or an ongoing effort to this direction so i can have a look at ? Coming from Windows and vs.net world, i think the only missing point here is the integration of the Pyrthon with a RAD IDE... Thanks a lot and i apologize if this isn't the correct place for this question... Kikapu -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing/Splitting Line
Fredrik Lundh schrieb: > Noah Rawlins wrote: > > >> I'm a nut for regular expressions and obfuscation... >> >> import re >> def splitline(line, size=4): >> return re.findall(r'.{%d}' % size, line) >> >> >>> splitline("helloiamsuperman") >> ['hell', 'oiam', 'supe', 'rman'] > > there are laws against such use of regular expressions in certain > jurisdictions. ... and in particularly bad cases, you will be punished by Perl not less than 5 years ... Georg -- http://mail.python.org/mailman/listinfo/python-list
Pyparsing Question.
I have a home-grown Wiki that I created as an excercise, with it's own wiki markup (actually just a clone of the Trac wiki markup). The wiki text parser I wrote works nicely, but makes heavy use of regexes, tags and stacks to parse the text. As such it is a bit of a mantainability nightmare - adding new wiki constructs can be a bit painful. So I thought I'd look into the pyparsing module, but can't find a simple example of processing random text. For example, I want to parse the following: "Some random text and '''some bold text''' and some more random text" into: "Some random text and some bold text and some more random text" I have the following as a starting point: from pyparsing import * def parse(text): italics = QuotedString(quoteChar="''") parser = Optional(italics) parsed_text = parser.parseString(text) print parse("Test this is '''bold''' but this is not.") So if you could provide a bit of a starting point, I'd be grateful! Cheers, -- http://mail.python.org/mailman/listinfo/python-list
Re: file backup in windows
k.i.n.g. wrote: > how can i make the following code work, I have probelm with filepath > declaration. http://effbot.org/pyfaq/tutor-i-need-help-im-getting-an-error-in-my-program-what-should-i-do -- http://mail.python.org/mailman/listinfo/python-list
gopherlib deprecated in 2.5
I've just seen that gopherlib is deprecated in python 2.5 http://docs.python.org/lib/module-gopherlib.html we still use this protocol (though there are only few working gopher servers are left on the net) My friend just wrote a standard compliant gopher server (pygopherd had some problems oslt) and it's much better for hierarchycal content sharing than the http (which is overrated and misused in this respect). So i don't really understand why would one remove it from python. It's a friendly, tiny, simple, standard protocol. what is the opinion of the comp.lang.python crowd? -- http://mail.python.org/mailman/listinfo/python-list
RE: file backup in windows
| " c:\documents and settings\060577\Local Settings\Application | Data\Microsoft\Outlook " | where 060577 represents username. I want my script to | identigy the user | logged in and go to the resp outlook folder or should be able to read | outlook store directory path from registry and the copy the files to | the desired path. | | --- | how can i make the following code work, I have probelm with filepath | declaration. | --- | import os, shutil | filepath = ' C:\\Documents and Settings\\060577\\Local | Settings\\Application Data\\Microsoft\\Outlook\\* ' | backup = ' D:\\temp\\outlook ' | os.system ("xcopy /s %s %s" % (filepath, backup)) | - I suggest you let the system work out most of the filepath for you. Things like Application Data are determined by the Windows Shell as they can change according to Windows version / roaming profile settings and so on. The following code snippet shows how to get the Local Application Data folder. It assumes you have installed the pywin32 extensions from http://pywin32.sf.net import os, sys from win32com.shell import shell, shellcon local_app_data = shell.SHGetSpecialFolderPath (0, shellcon.CSIDL_LOCAL_APPDATA) outlook_path = os.path.join (local_app_data, "Microsoft", "Outlook") print outlook_path http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: file backup in windows
k.i.n.g. wrote: > Hi ALL, > > I am a newbee programmer and started of with python recently. I am > trying write a script which backups outlook (.pst ) files everytime I > shutdown my system. I have writtern following code after some findings > on net. My .pst file path is as follows > > " c:\documents and settings\060577\Local Settings\Application > Data\Microsoft\Outlook " > where 060577 represents username. I want my script to identigy the user > logged in and go to the resp outlook folder or should be able to read > outlook store directory path from registry and the copy the files to > the desired path. > > --- > how can i make the following code work, I have probelm with filepath > declaration. > --- > import os, shutil > filepath = ' C:\\Documents and Settings\\060577\\Local > Settings\\Application Data\\Microsoft\\Outlook\\* ' > backup = ' D:\\temp\\outlook ' Aside: having a space at the beginning and/or end of the filename has no good effect and may cause problems, so don't do it. > os.system ("xcopy /s %s %s" % (filepath, backup)) > - It's always a good idea *before* you write an os.system call on *any* operating system to try a few sample commands at the command line. You would find in this case that the problem exists there too -- it has nothing to do with Python. The problem is that the first argument *contains* spaces, but the Windows command processor splits the command line on spaces, so it thinks the first argument is 'C:\\Documents'. On both the command line and in your script, you will need to wrap quotes around each argument that does/could contain spaces. [untested] os.system ('xcopy /s "%s" "%s"' % (filepath, backup)) Hint: you should find it easier using raw strings for Windows filenames: backup = r'D:\temp\outlook' HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a list comprehension for this?
On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote: > Steven D'Aprano wrote: > > [snip] > >> def running_sum(dw): >> """Return a list of the running sums of sequence dw""" >> rs = [0]*len(dw) >> for i in range(len(dw)): >> rs[i] = dw[i] + rs[i-1] > > Please explain to the newbies why there is no exception raised when > rs[i-1] is executed for i == 0, and state whether you consider this is > a Good Idea or a Filthy Trick or a Fortunate Accident. Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I cunningly initialised the list to all zeroes, so adding zero to the first term doesn't change the result value. It is a variation of the sentinel technique, where you add an extra value to the beginning or end of a list so that you don't need to treat the first or last item differently. In this specific case, I think it is a combination of Good Idea and Fortunate Accident, but since the meaning of list[-1] is both deliberate and well-documented, it is certainly not a Filthy Trick. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a list comprehension for this?
Steven D'Aprano wrote: > On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote: > > > Steven D'Aprano wrote: > > > > [snip] > > > >> def running_sum(dw): > >> """Return a list of the running sums of sequence dw""" > >> rs = [0]*len(dw) > >> for i in range(len(dw)): > >> rs[i] = dw[i] + rs[i-1] > > > > Please explain to the newbies why there is no exception raised when > > rs[i-1] is executed for i == 0, and state whether you consider this is > > a Good Idea or a Filthy Trick or a Fortunate Accident. > > Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I > cunningly initialised the list to all zeroes, so adding zero to the first > term doesn't change the result value. > > It is a variation of the sentinel technique, where you add an extra value > to the beginning or end of a list so that you don't need to treat the > first or last item differently. In this specific case, I think it is a > combination of Good Idea and Fortunate Accident, but since the > meaning of list[-1] is both deliberate and well-documented, it is > certainly not a Filthy Trick. > Fair enough. But it does make the concerned reader go back a couple of lines to see why it doesn't run amok. Here's my attempt at a no-reader-backtracking solution: def running_sum_2(dw): rs = dw[:1] for i in xrange(1, len(dw)): rs.append(dw[i] + rs[-1]) return rs Comments invited. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a list comprehension for this?
On Wed, 22 Nov 2006 02:28:04 -0800, John Machin wrote: > > Steven D'Aprano wrote: >> On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote: >> >> > Steven D'Aprano wrote: >> > >> > [snip] >> > >> >> def running_sum(dw): >> >> """Return a list of the running sums of sequence dw""" >> >> rs = [0]*len(dw) >> >> for i in range(len(dw)): >> >> rs[i] = dw[i] + rs[i-1] >> > >> > Please explain to the newbies why there is no exception raised when >> > rs[i-1] is executed for i == 0, and state whether you consider this is >> > a Good Idea or a Filthy Trick or a Fortunate Accident. >> >> Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I >> cunningly initialised the list to all zeroes, so adding zero to the first >> term doesn't change the result value. >> >> It is a variation of the sentinel technique, where you add an extra value >> to the beginning or end of a list so that you don't need to treat the >> first or last item differently. In this specific case, I think it is a >> combination of Good Idea and Fortunate Accident, but since the >> meaning of list[-1] is both deliberate and well-documented, it is >> certainly not a Filthy Trick. >> > > Fair enough. But it does make the concerned reader go back a couple of > lines to see why it doesn't run amok. Nobody said that every piece of code should be instantly comprehensible just at a glance. Sometimes you do actually have to think about code to understand it, even in Python :) > Here's my attempt at a > no-reader-backtracking solution: > > def running_sum_2(dw): > rs = dw[:1] > for i in xrange(1, len(dw)): > rs.append(dw[i] + rs[-1]) > return rs > > Comments invited. Even with xrange() instead of range, it is a little slower than my version for largish input lists because you are repeatedly appending to a list. >>> timeit.Timer("running_sum(L)", ... "from __main__ import running_sum; L = range(500)").timeit(1000) 0.56354999542236328 >>> timeit.Timer("running_sum_2(L)", ... "from __main__ import running_sum_2; L = range(500)").timeit(1000) 0.68534302711486816 Although the speed difference disappears (or even reverses) for small enough lists. Either way, it isn't really a major speed difference -- Python's resizing of lists is very smart. But why build a list of all the running sums when you probably only need them one at a time? Here's a generator version that can take any iterable, not just a sequence: def running_sum_3(iterable): sum_ = 0 for x in iterable: sum_ += x yield sum_ And it is considerably faster than either of the list-only versions: >>> timeit.Timer("list(running_sum_3(L))", ... "from __main__ import running_sum_3; L = range(500)").timeit(1000) 0.33915305137634277 -- Steve. -- http://mail.python.org/mailman/listinfo/python-list
text file parsing (awk -> python)
Hi list, I have an awk program that parses a text file which I would like to rewrite in python. The text file has multi-line records separated by empty lines and each single-line field has two subfields: node 10 x -1 y 1 node 11 x -2 y 1 node 12 x -3 y 1 and this I would like to parse into a list of dictionaries like so: mydict[0] = { 'node':10, 'x':-1, 'y':1 } mydict[1] = { 'node':11, 'x':-2, 'y':1 } mydict[2] = { 'node':12, 'x':-3', 'y':1 } But the names of the fields (node, x, y) keeps changing from file to file, even their number is not fixed, sometimes it is (node, x, y, z). What would be the simples way to do this? -- http://mail.python.org/mailman/listinfo/python-list
RE: file backup in windows
[... snip ...] | --- | how can i make the following code work, I have probelm with filepath | declaration. | --- | import os, shutil | filepath = ' C:\\Documents and Settings\\060577\\Local | Settings\\Application Data\\Microsoft\\Outlook\\* ' | backup = ' D:\\temp\\outlook ' | os.system ("xcopy /s %s %s" % (filepath, backup)) | - ... also, for various ways of copying files around under Windows in Python, see: http://tgolden.sc.sabren.com/python/win32_how_do_i/copy-a-file.html 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: Trying to understand Python objects
walterbyrd wrote: > Reading "Think Like a Computer Scientist" I am not sure I understand > the way it describes the way objects work with Python. > > 1) Can attributes can added just anywhere? I create an object called > point, then I can add attributes any time, and at any place in the > program? Apart from a few special cases (mainly builtin types or new-style classes using slots IIRC), yes. Now wether this is a good idea is another question. As far as I'm concerned, I do use this feature, but only for special cases, and almost only in metaclasses or other special 2-stages init. > 2) Are classes typically created like this: > > class Point: > pass > > Then attributes are added at some other time? Nope. The canonical idiom is to use the initializer: class Point(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 self.attr3 = 42 > 3) What is with the __underscores__ ?? "magic" methods or attributes. The initializer ('__init__') is one of them, which is called at instance creation time. Most of the magic __methods__ are used to implement or override operators. You'll find the relevant documentation around here: http://docs.python.org/ref/specialnames.html > 4) Are parameters passed to an class definition? > > class Whatever(params): >pass A class statement is not a function definition statement. Here, you ask for a class Whatever inheriting from class params. Cf the above point about the __init__ method for passing args at instanciation. > I sort-of understand the way objects work with PHP. With PHP, the > classes are defined in one place - sort of like a function. FWIW, Python's classes actually are callable objects (just like functions are callable objects). To instanciate a class, you just call the class, no 'new' keyword needed. > To me, that > makes more sense. name = "toto"; echo $obj->name; ?> Just like Python (and Javascript FWIW), PHP objects are mostly hashtable in disguise. But - having some experience with both PHP and Python (and some other OOPLs), I can tell you that Python's object model is far superior to PHP's one. The only "gotcha" here wrt/ most other object models is that attributes defined in the class statement body (ie, outside methods) are attached to the class object itself (and then shared by all instances of the class), not to instances themselves. Instance attributes initialisation is usually done in the __init__(self, ...) method. 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: file backup in windows
Thank You all for reply's so far > > import os, sys > from win32com.shell import shell, shellcon > > local_app_data = shell.SHGetSpecialFolderPath (0, > shellcon.CSIDL_LOCAL_APPDATA) > outlook_path = os.path.join (local_app_data, "Microsoft", "Outlook") > > print outlook_path > > The above code was fine while printing, when I am trying to use this (outlook_path) to use as source path it is giving file permission error can you please clarify this -- http://mail.python.org/mailman/listinfo/python-list
File upload from client application (non-form based upload)
Hi I'm trying to write a Python script to receive and save a file on a web server that has been POST'ed from a client application. In essence, this is similar to handling a file upload from an HTML form. However, I can't use: form = cgi.FieldStorage() fileitem = form['file'] since the file is not coming from a form, and hence I don't have a form field called 'file'. I have working server-side code in PHP to do this (error handling removed): $file = "./test.jpg"; $file_handle = fopen($file,"w"); $mydata = file_get_contents("php://input"); fwrite($file_handle, $mydata); fclose($file_handle); What I need is a Python equivalent of the the above PHP script. The content-type in the POST header is currently set to "application/octet-stream" which works fine with the php code above. Any help, advise, pointers, sample code would be hugely welcome, Many thanks in advance, Stuart -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
king kikapu wrote: > Hi to all, > > i am not sure if this question really belongs here but anyway, here it > goes: I have seen a lot of IDEs for Python, a lot of good stuff but > actually none of them has what, for example, Visual Studio has: a > Visual Editor (with the ability to place controls on forms etc etc), > or RAD > > I know that there is Glade but does anybody knows of some product, or > an ongoing effort to this direction so i can have a look at ? > > Coming from Windows and vs.net world, i think the only missing point > here is the integration of the Pyrthon with a RAD IDE... > > Thanks a lot and i apologize if this isn't the correct place for this > question... If you use wxWidgets, you may want to have a look at projects like Boa-constructor or PythonCard. If you use QT/KDE, Eric3 offers good integration with QT Designer IIRC. Now as you can see, the problem with RAD tools is that they are specific to a given GUI toolkit. Python runs on a lot of platforms, and some of these platforms (ie Linux) are not tied to a specific GUI toolkit. So integrating the RAD tool in the IDE means you can't use this IDE with other GUI toolkits. Also, there's a tradition in the *n*x world about preferring small, highly specialized tools over huge monolithic do-it-all applications. As an example, I daily use half a dozen languages, and I wouldn't like to have to learn half a dozen IDEs. I'm much more productive with a good code editor, the command line, and a few external tools when needed. 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
Re: file backup in windows
k.i.n.g. wrote: > [snip code] > The above code was fine while printing, when I am trying to use this > (outlook_path) to use as source path it is giving file permission error > can you please clarify this Did you follow the link that Fredrik Lundh gave you? /MiO -- http://mail.python.org/mailman/listinfo/python-list
Data not flushed at the moment
I've to modifying a file, then I use a method imported that access to that file and has to read the new data, but they are not read ( as if the data were not flushed at the moment even using .close() explicitly). --- ... ... # If it is not installed, it looking for the line and insert it. if not is_application: print "Activating I18n application ..." writefile_line = 0 a = fileinput.input(settings, inplace=1) #for line in fileinput.input(settings, inplace=1): for line in a: writefile_line += 1 if writefile_line == readfile_line: print "'%s'," % application_name print line[:-1] else: print line[:-1] a.close() update() def update(): # Update the data base. try: from django.core.management import syncdb except ImportError, err: print "Can't import from Django: %s" % err sys.exit(1) syncdb() --- Note that it only fails if the update() method is run inner of 'if not is_application', and I don't understand because it is happening so. But the problem is that I need run it when that condition is performed. Any idea? -- http://mail.python.org/mailman/listinfo/python-list
Re: file backup in windows
Hi , I am sorry I am providing the code i used as it is. Being newbee to programming I have tinkerd with various options i found on the net. start of the code import os, sys ,shutil, win32file import time from win32com.shell import shell, shellcon local_app_data = shell.SHGetSpecialFolderPath (0,shellcon.CSIDL_LOCAL_APPDATA) outlook_path = os.path.join (local_app_data, "Microsoft", "Outlook") # print outlook_path #c:\documents and settings\060577\Local Settings\Application Data\Microsoft\Outlook source = outlook_path #source = outlook_path +'\\*' print source backup = 'D:\MailBackup' backup1=r'D:\temp\outlook1' backup2 = 'D:\MailBackup' today = backup1 + '_' + time.strftime ( '%Y-%m-%d') now = time.strftime('%H.%M.%S') target = today +'_'+ now if not os.path.exists(target): os.mkdir(target) # make directory print 'Successfully created directory', target #shutil.copy(source, backup) #os.system( "copy "(source,backup)) #os.system ("xcopy %s %s" % (source, backup1)) #os.system ("xcopy /s %s %s" % (outlook_path, backup1)) #os.system ("xcopy /s %s %s" % (backup2, backup1)) #os.system( 'xcopy /i D:\\MailBackup\\* d:\\temp\\outlook') #win32file.CopyFile (outlook_path, backup, 0) #os.system ("xcopy /s %s %s" % (backup,target)) os.system ("xcopy /s %s %s" % (source,target)) # this doesnt give me any errors but the #work is not done win32file.CopyFile (source, target, 1) --- end -- - output -- C:\Documents and Settings\060577\Local Settings\Application Data\Microsoft\Outlook\* Successfully created directory D:\temp\outlook1_2006-11-22_17.41.54 Traceback (most recent call last): File "C:\Documents and Settings\060577\kk\source_code\py\Mypy\pywin32test.py", line 34, in win32file.CopyFile (source, target, 1) error: (123, 'CopyFile', 'The filename, directory name, or volume label syntax is incorrect.') -- http://mail.python.org/mailman/listinfo/python-list
RE: file backup in windows
| > | > import os, sys | > from win32com.shell import shell, shellcon | > | > local_app_data = shell.SHGetSpecialFolderPath (0, | > shellcon.CSIDL_LOCAL_APPDATA) | > outlook_path = os.path.join (local_app_data, "Microsoft", "Outlook") | > | > print outlook_path | > | > | | The above code was fine while printing, when I am trying to use this | (outlook_path) to use as source path it is giving file | permission error As others have suggested, please cut-and-paste code and traceback from an interpreter session. Don't make people guess what you've done. My code above doesn't do anything with the path bar printing it, so you've obviously attempted some kind of file operation with it. What have you done? The outlook_path itself is a *folder*, not a file. I didn't write out all of your code; you need to add something to copy the file or files you need. Have you done that? Please provide code and traceback if you still have difficulties. 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
PyQt app in seperate thread
I am writing a plugin for a piece of software in python, and I want to start up a PyQt GUI in the plugin, without stalling the main thread while the gui is running (later i will want to pass messages between the main thread and the gui thread). I'm new to pyqt, so I'm probably doing something very silly, but for the moment I'm just trying to get the first pyqt tutorial example running in a seperate thread: 8< import sys from PyQt4 import QtGui from PyQt4 import QtCore class MyThread( QtCore.QThread ): def __init__( self ): QtCore.QThread.__init__( self ) def run( self ): app = QtGui.QApplication( sys.argv ) hello = QtGui.QPushButton( 'Hello world!' ) hello.resize( 500, 500 ) hello.show() app.exec_() QtCore.QThread.terminate( ) mt = MyThread() mt.start() print 'Main thread continuing...' mt.wait() print 'GUI thread finished.' 8< The app starts up (with a warning WARNING: QApplication was not created in the main() thread. ). I get a window, but no button, and clicking on the close button does nothing and I have to force the program to quit. There's got to be a way to get this working, right? Can anyone help me along the right path? Cheers, Anders -- http://mail.python.org/mailman/listinfo/python-list
Capture file descriptors while running an external program
Hi all! I have a problem with the module subprocess! The problem is that the external software that I am running under subprocess.Popen opens stdin, stdout, stderr, and other file descriptors to write and read in the hard drive. I know how to capture stdin, stdout and stderr, what I cannot do is to capture the other file-descriptors. Is there any way to wrap those non-standard file descriptors and make them write and read from a specific object that I define? I know that I can use tmp files to do that, but i would like something running without tmp files. Regards... Joao ___ O SAPO já está livre de vírus com a Panda Software, fique você também! Clique em: http://antivirus.sapo.pt -- http://mail.python.org/mailman/listinfo/python-list
RE: file backup in windows
| I am sorry I am providing the code i used as it is. Being newbee to | programming I have tinkerd with various options i found on the net. Thanks. That makes it a lot easier [... snip ...] | source = outlook_path | #source = outlook_path +'\\*' | print source [...] | win32file.CopyFile (source, target, 1) | - | output | -- | C:\Documents and Settings\060577\Local Settings\Application | Data\Microsoft\Outlook\* | Successfully created directory D:\temp\outlook1_2006-11-22_17.41.54 | | Traceback (most recent call last): | File "C:\Documents and | Settings\060577\kk\source_code\py\Mypy\pywin32test.py", line 34, in | | win32file.CopyFile (source, target, 1) | error: (123, 'CopyFile', 'The filename, directory name, or | volume label | syntax is incorrect.') Fairly certain that the win32file.CopyFile API call doesn't handle wildcards. You have to do that yourself. (I could be wrong). Quick check: Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os, sys >>> import win32file >>> >>> os.chdir ("c:/temp") >>> os.mkdir ("backup") >>> win32file.CopyFile ("*.txt", "backup", 1) Traceback (most recent call last): File "", line 1, in ? pywintypes.error: (123, 'CopyFile', 'The filename, directory name, or volume label syntax is incorrect.') >>> >>> win32file.CopyFile ("temp.txt", "backup", 1) Traceback (most recent call last): File "", line 1, in ? pywintypes.error: (2, 'CopyFile', 'The system cannot find the file specified.') >>> >>> win32file.CopyFile ("exists.txt", "backup", 1) Traceback (most recent call last): File "", line 1, in ? pywintypes.error: (5, 'CopyFile', 'Access is denied.') >>> win32file.CopyFile ("exists.txt", "backup/exists.txt", 1) >>> Sure enough: 1) Wildcards give the error you had 2) Non-existent file gives a suitable messag 3) Existing filename to folder name only gives Access denied 4) Existing filename to folder name + filename copies ok. Now, that only took about a minute to run through on the interpreter and check, so hopefully that'll help you out next time: create a small test case (without all the long path names). Find out what CopyFile can or can't do and act accordingly. If you haven't already, look at the glob module: http://docs.python.org/lib/module-glob.html 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: Python visual IDE
hmmm,,,ok, i see your point. As i understand it, as a newcomer, it is a little cumbersome to right the code in one ide, "glue" the UI from another toll and all that stuff. I know it works but if someone is coming from VS.Net, it seems a little strange, at first. I also saw that the wxWidgets is the more "feel natural" in all platforms so i believe that if an IDE is able to offer RAD capabilities and build upon this widget, it will be an awesome tool for Python programmers, matches this way VS and other win RAD IDEs... Thanks a lot for your post, i'll have a look at the programs you mention! King Kikapu On Nov 22, 2:09 pm, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > king kikapu wrote: > > Hi to all, > > > i am not sure if this question really belongs here but anyway, here it > > goes: I have seen a lot of IDEs for Python, a lot of good stuff but > > actually none of them has what, for example, Visual Studio has: a > > Visual Editor (with the ability to place controls on forms etc etc), > > or RAD > > > I know that there is Glade but does anybody knows of some product, or > > an ongoing effort to this direction so i can have a look at ? > > > Coming from Windows and vs.net world, i think the only missing point > > here is the integration of the Pyrthon with a RAD IDE... > > > Thanks a lot and i apologize if this isn't the correct place for this > > question...If you use wxWidgets, you may want to have a look at projects > > like > Boa-constructor or PythonCard. If you use QT/KDE, Eric3 offers good > integration with QT Designer IIRC. > > Now as you can see, the problem with RAD tools is that they are specific > to a given GUI toolkit. Python runs on a lot of platforms, and some of > these platforms (ie Linux) are not tied to a specific GUI toolkit. So > integrating the RAD tool in the IDE means you can't use this IDE with > other GUI toolkits. > > Also, there's a tradition in the *n*x world about preferring small, > highly specialized tools over huge monolithic do-it-all applications. As > an example, I daily use half a dozen languages, and I wouldn't like to > have to learn half a dozen IDEs. I'm much more productive with a good > code editor, the command line, and a few external tools when needed. > > My 2 cents... > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in '[EMAIL PROTECTED]'.split('@')])"- Hide quoted text -- Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: text file parsing (awk -> python)
Daniel Nogradi wrote: > I have an awk program that parses a text file which I would like to > rewrite in python. The text file has multi-line records separated by > empty lines and each single-line field has two subfields: > > node 10 > x -1 > y 1 > > node 11 > x -2 > y 1 > > node 12 > x -3 > y 1 > > and this I would like to parse into a list of dictionaries like so: > > mydict[0] = { 'node':10, 'x':-1, 'y':1 } > mydict[1] = { 'node':11, 'x':-2, 'y':1 } > mydict[2] = { 'node':12, 'x':-3', 'y':1 } > > But the names of the fields (node, x, y) keeps changing from file to > file, even their number is not fixed, sometimes it is (node, x, y, z). > > What would be the simples way to do this? data = """node 10 x -1 y 1 node 11 x -2 y 1 node 12 x -3 y 1 """ def open(filename): from cStringIO import StringIO return StringIO(data) converters = dict( x=int, y=int ) def name_value(line): name, value = line.split(None, 1) return name, converters.get(name, str.rstrip)(value) if __name__ == "__main__": from itertools import groupby records = [] for empty, record in groupby(open("records.txt"), key=str.isspace): if not empty: records.append(dict(name_value(line) for line in record)) import pprint pprint.pprint(records) -- http://mail.python.org/mailman/listinfo/python-list
XML Validation in Python using XSV
I'd like to use XSV for validating an XML file in Python. I am working on Linux Debian platform. I'm not sure how to install XSV and how to configure it. My goal is to be able to import the XSV library in Python and be able to use it's functions. XSV v2.10 for Debian available here: ftp://ftp.cogsci.ed.ac.uk/pub/XSV/XSV_2.10-1_all.deb How do i do that? -- http://mail.python.org/mailman/listinfo/python-list
Getting exceptions back from calls to embedded python
Hi all, I have an application that is using embedded python to offer some scripting ability. An API is exposed via SWIG, and I am accessing that API from my embedded python interpreter. Scripts are present as separate files, and I'm invoking them at present using the following: iserr = PyRun_AnyFileEx(f,name,1); if(iserr){ /* tell the user */ return 1; }else{ /* all good */ return 0; } My question is, if I want to be able to get information about exceptions that have occurred here (perhaps a syntax error, or an import error, or perhaps a runtime error), what would be the easiest way to do this now? I understand that I'm currently using the 'very high level interface' for python embedding. What's the easiest next step down that will allow me to catch exceptions and report them? Would appreciate any thoughts. Cheers JP -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
On Wednesday 22 November 2006 12:37 pm, anders wrote: > I am writing a plugin for a piece of software in python, and I want to > start up a PyQt GUI in the plugin, without stalling the main thread > while the gui is running (later i will want to pass messages between > the main thread and the gui thread). > > I'm new to pyqt, so I'm probably doing something very silly, but for > the moment I'm just trying to get the first pyqt tutorial example > running in a seperate thread: > > 8< > > import sys > from PyQt4 import QtGui > from PyQt4 import QtCore > > class MyThread( QtCore.QThread ): > def __init__( self ): > QtCore.QThread.__init__( self ) > > def run( self ): > app = QtGui.QApplication( sys.argv ) > hello = QtGui.QPushButton( 'Hello world!' ) > hello.resize( 500, 500 ) > hello.show() > app.exec_() > QtCore.QThread.terminate( ) > > > > mt = MyThread() > mt.start() > print 'Main thread continuing...' > mt.wait() > print 'GUI thread finished.' > > 8< > > The app starts up (with a warning WARNING: QApplication was not created > in the main() thread. ). I get a window, but no button, and clicking on > the close button does nothing and I have to force the program to quit. > > There's got to be a way to get this working, right? Can anyone help me > along the right path? Read http://doc.trolltech.com/4.2/threads.html In particular the bit that says that exec_() must be called from the main thread and not from a QThread. Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: How to sort list
Fredrik Lundh wrote: > note that DSU is built into Python these days: > > L.sort(key=transform) Sweet, thanks for the hint. Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Validation in Python using XSV
[EMAIL PROTECTED] wrote: > I'd like to use XSV for validating an XML file in Python. > I am working on Linux Debian platform. > I'm not sure how to install XSV and how to configure it. My goal is to > be able to import the XSV library in Python and be able to use it's > functions. You can use "dpkg" to install the .deb. Read "man dpkg". BTW: any reason you need to use XSV? There are some other libraries out there that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are much more powerful than XSV. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyparsing Question.
Ant wrote: > So I thought I'd look into the pyparsing module, but can't find a > simple example of processing random text. Have you looked at the examples on the pyparsing web page? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Validation in Python using XSV
No particular reason for XSV I just want to validate XML files against an XML schema through Python. If you can suggest any other package for debian, I'll be glad to try it. Michel Stefan Behnel wrote: > [EMAIL PROTECTED] wrote: > > I'd like to use XSV for validating an XML file in Python. > > I am working on Linux Debian platform. > > I'm not sure how to install XSV and how to configure it. My goal is to > > be able to import the XSV library in Python and be able to use it's > > functions. > > You can use "dpkg" to install the .deb. Read "man dpkg". > > BTW: any reason you need to use XSV? There are some other libraries out there > that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are > much more powerful than XSV. > > Stefan -- http://mail.python.org/mailman/listinfo/python-list
Method argument names
Hi Having a method: def method(self,x,y): is it possible to discover, from outside the method, that the methods arguments are ['self', 'x', 'y']? Thanks. /Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Quadratic Optimization Problem
Stefan Behnel wrote: > [EMAIL PROTECTED] wrote: > > I need to do a quadratic optimization problem in python where the > > constraints are quadratic and objective function is linear. > > > > What are the possible choices to do this. > > Too bad these homework assignments get trickier every time, isn't it? I think this sarcasm is unjustified. It is not obvious to me that this is a homework assignment. The problem where constraints are linear and the objective function is linear (quadratic) is known as linear (quadratic) programming, and there are specialized codes for these problems. I don't know of software in any language for the particular problem of a linear objective function with quadratic constraints, so I would use a general algorithm for nonlinearly constrained optimization. Maybe CVXOPT http://www.ee.ucla.edu/~vandenbe/cvxopt/ will work for the OP -- I have not tried it. The site http://www.solver.com/probconic.htm calls the problem "conic optimization". A good newsgroup to ask about optimization algorithms is sci.math.num-analysis. -- http://mail.python.org/mailman/listinfo/python-list
Re: Method argument names
[EMAIL PROTECTED] wrote: > Hi > > Having a method: > > def method(self,x,y): > > is it possible to discover, from outside the method, that the methods > arguments are ['self', 'x', 'y']? import inspect help(inspect.getargspec) 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: PyQt app in seperate thread
Phil Thompson wrote: > On Wednesday 22 November 2006 12:37 pm, anders wrote: > > I am writing a plugin for a piece of software in python, and I want to > > start up a PyQt GUI in the plugin, without stalling the main thread > > while the gui is running (later i will want to pass messages between > > the main thread and the gui thread). > > > > I'm new to pyqt, so I'm probably doing something very silly, but for > > the moment I'm just trying to get the first pyqt tutorial example > > running in a seperate thread: > > > > 8< > > > > import sys > > from PyQt4 import QtGui > > from PyQt4 import QtCore > > > > class MyThread( QtCore.QThread ): > > def __init__( self ): > > QtCore.QThread.__init__( self ) > > > > def run( self ): > > app = QtGui.QApplication( sys.argv ) > > hello = QtGui.QPushButton( 'Hello world!' ) > > hello.resize( 500, 500 ) > > hello.show() > > app.exec_() > > QtCore.QThread.terminate( ) > > > > > > > > mt = MyThread() > > mt.start() > > print 'Main thread continuing...' > > mt.wait() > > print 'GUI thread finished.' > > > > 8< > > > > The app starts up (with a warning WARNING: QApplication was not created > > in the main() thread. ). I get a window, but no button, and clicking on > > the close button does nothing and I have to force the program to quit. > > > > There's got to be a way to get this working, right? Can anyone help me > > along the right path? > > Read http://doc.trolltech.com/4.2/threads.html > > In particular the bit that says that exec_() must be called from the main > thread and not from a QThread. > > Phil OK so that's all good... so how do I go about doing what I want then? Can I set up a window in the second thread and start its event loop without running the event loop in the core app? -- http://mail.python.org/mailman/listinfo/python-list
Re: text file parsing (awk -> python)
> > I have an awk program that parses a text file which I would like to > > rewrite in python. The text file has multi-line records separated by > > empty lines and each single-line field has two subfields: > > > > node 10 > > x -1 > > y 1 > > > > node 11 > > x -2 > > y 1 > > > > node 12 > > x -3 > > y 1 > > > > and this I would like to parse into a list of dictionaries like so: > > > > mydict[0] = { 'node':10, 'x':-1, 'y':1 } > > mydict[1] = { 'node':11, 'x':-2, 'y':1 } > > mydict[2] = { 'node':12, 'x':-3', 'y':1 } > > > > But the names of the fields (node, x, y) keeps changing from file to > > file, even their number is not fixed, sometimes it is (node, x, y, z). > > > > What would be the simples way to do this? > > data = """node 10 > x -1 > y 1 > > node 11 > x -2 > y 1 > > node 12 > x -3 > y 1 > """ > > def open(filename): > from cStringIO import StringIO > return StringIO(data) > > converters = dict( > x=int, > y=int > ) > > def name_value(line): > name, value = line.split(None, 1) > return name, converters.get(name, str.rstrip)(value) > > if __name__ == "__main__": > from itertools import groupby > records = [] > > for empty, record in groupby(open("records.txt"), key=str.isspace): > if not empty: > records.append(dict(name_value(line) for line in record)) > > import pprint > pprint.pprint(records) Thanks very much, that's exactly what I had in mind. Thanks again, Daniel -- http://mail.python.org/mailman/listinfo/python-list
What's going on here?
Python 2.4.2 (#1, Oct 13 2006, 17:11:24) [GCC 4.1.0 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = object() >>> a >>> a.spam = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'spam' >>> class b(object): ...pass ... >>> a = b() >>> a <__main__.b object at 0xb7b4dcac> >>> a.spam = 1 >>> What is subclassing adding to the class here? Why can't I assign to attributes of an instance of object? -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
On Wednesday 22 November 2006 2:06 pm, anders wrote: > Phil Thompson wrote: > > On Wednesday 22 November 2006 12:37 pm, anders wrote: > > > I am writing a plugin for a piece of software in python, and I want to > > > start up a PyQt GUI in the plugin, without stalling the main thread > > > while the gui is running (later i will want to pass messages between > > > the main thread and the gui thread). > > > > > > I'm new to pyqt, so I'm probably doing something very silly, but for > > > the moment I'm just trying to get the first pyqt tutorial example > > > running in a seperate thread: > > > > > > 8< > > > > > > import sys > > > from PyQt4 import QtGui > > > from PyQt4 import QtCore > > > > > > class MyThread( QtCore.QThread ): > > > def __init__( self ): > > > QtCore.QThread.__init__( self ) > > > > > > def run( self ): > > > app = QtGui.QApplication( sys.argv ) > > > hello = QtGui.QPushButton( 'Hello world!' ) > > > hello.resize( 500, 500 ) > > > hello.show() > > > app.exec_() > > > QtCore.QThread.terminate( ) > > > > > > > > > > > > mt = MyThread() > > > mt.start() > > > print 'Main thread continuing...' > > > mt.wait() > > > print 'GUI thread finished.' > > > > > > 8< > > > > > > The app starts up (with a warning WARNING: QApplication was not created > > > in the main() thread. ). I get a window, but no button, and clicking on > > > the close button does nothing and I have to force the program to quit. > > > > > > There's got to be a way to get this working, right? Can anyone help me > > > along the right path? > > > > Read http://doc.trolltech.com/4.2/threads.html > > > > In particular the bit that says that exec_() must be called from the main > > thread and not from a QThread. > > > > Phil > > OK so that's all good... so how do I go about doing what I want then? > Can I set up a window in the second thread and start its event loop > without running the event loop in the core app? No. Read the second sentence of the paragraph I referred to. Also read the section "QObject Reentrancy". Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
I haven't used it but Komodo (Professional version) says it has: ActiveState GUI Builder (Komodo Professional only) Enhance your applications with GUI dialogs: Simple, Tk-based dialog builder with seamless round-trip integration, for Perl, Python, Ruby, and Tcl. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Validation in Python using XSV
> [EMAIL PROTECTED] wrote: > Stefan Behnel wrote: >> BTW: any reason you need to use XSV? There are some other libraries out there >> that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are >> much more powerful than XSV. > > No particular reason for XSV > I just want to validate XML files against an XML schema through Python. > If you can suggest any other package for debian, I'll be glad to try > it. Well, as I said: http://packages.debian.org/unstable/python/python-lxml http://codespeak.net/lxml/ Just try "apg-get install python-lxml". Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand Python objects
Thanks everybody. I will sort all of this out, but right now my head is spinning. Is there some book, or other reference, that explains of this? I was thinking about "Python for Dummies." The "Think like a Computer Scientist" book, and "Dive into Python" book don't seem to explain Python's object model clearly enough for me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
I have already downloaded and seen the trial of Komodo Professional. Indeed it has a simple Gui Builder but one can only use TKinter on it. No wxWidgets support and far from truly RAD, but it is the only "integrated" GUI builder in these IDEs... On Nov 22, 4:31 pm, "Steve" <[EMAIL PROTECTED]> wrote: > I haven't used it but Komodo (Professional version) says it has: > > ActiveState GUI Builder (Komodo Professional only) > > Enhance your applications with GUI dialogs: Simple, Tk-based dialog > builder with seamless round-trip integration, for Perl, Python, Ruby, > and Tcl. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
Phil Thompson wrote: > On Wednesday 22 November 2006 2:06 pm, anders wrote: > > Phil Thompson wrote: > > > On Wednesday 22 November 2006 12:37 pm, anders wrote: > > > > I am writing a plugin for a piece of software in python, and I want to > > > > start up a PyQt GUI in the plugin, without stalling the main thread > > > > while the gui is running (later i will want to pass messages between > > > > the main thread and the gui thread). > > > > > > > > I'm new to pyqt, so I'm probably doing something very silly, but for > > > > the moment I'm just trying to get the first pyqt tutorial example > > > > running in a seperate thread: > > > > > > > > 8< > > > > > > > > import sys > > > > from PyQt4 import QtGui > > > > from PyQt4 import QtCore > > > > > > > > class MyThread( QtCore.QThread ): > > > > def __init__( self ): > > > > QtCore.QThread.__init__( self ) > > > > > > > > def run( self ): > > > > app = QtGui.QApplication( sys.argv ) > > > > hello = QtGui.QPushButton( 'Hello world!' ) > > > > hello.resize( 500, 500 ) > > > > hello.show() > > > > app.exec_() > > > > QtCore.QThread.terminate( ) > > > > > > > > > > > > > > > > mt = MyThread() > > > > mt.start() > > > > print 'Main thread continuing...' > > > > mt.wait() > > > > print 'GUI thread finished.' > > > > > > > > 8< > > > > > > > > The app starts up (with a warning WARNING: QApplication was not created > > > > in the main() thread. ). I get a window, but no button, and clicking on > > > > the close button does nothing and I have to force the program to quit. > > > > > > > > There's got to be a way to get this working, right? Can anyone help me > > > > along the right path? > > > > > > Read http://doc.trolltech.com/4.2/threads.html > > > > > > In particular the bit that says that exec_() must be called from the main > > > thread and not from a QThread. > > > > > > Phil > > > > OK so that's all good... so how do I go about doing what I want then? > > Can I set up a window in the second thread and start its event loop > > without running the event loop in the core app? > > No. Read the second sentence of the paragraph I referred to. Also read the > section "QObject Reentrancy". > > Phil OK I see that now. Thanks for pointing that out. So basically, I can't do what I want at all. That's a bit of a pain. Is there no way of tricking Qt into thinking I'm running it in the main thread? A -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
On 22 Nov 2006 06:43:55 -0800, anders <[EMAIL PROTECTED]> wrote: > > Phil Thompson wrote: > > On Wednesday 22 November 2006 2:06 pm, anders wrote: > > > Phil Thompson wrote: > > > > On Wednesday 22 November 2006 12:37 pm, anders wrote: > > > > > I am writing a plugin for a piece of software in python, and I want to > > > > > start up a PyQt GUI in the plugin, without stalling the main thread > > > > > while the gui is running (later i will want to pass messages between > > > > > the main thread and the gui thread). > > > > > > > > > > I'm new to pyqt, so I'm probably doing something very silly, but for > > > > > the moment I'm just trying to get the first pyqt tutorial example > > > > > running in a seperate thread: > > > > > > > > > > 8< > > > > > > > > > > import sys > > > > > from PyQt4 import QtGui > > > > > from PyQt4 import QtCore > > > > > > > > > > class MyThread( QtCore.QThread ): > > > > > def __init__( self ): > > > > > QtCore.QThread.__init__( self ) > > > > > > > > > > def run( self ): > > > > > app = QtGui.QApplication( sys.argv ) > > > > > hello = QtGui.QPushButton( 'Hello world!' ) > > > > > hello.resize( 500, 500 ) > > > > > hello.show() > > > > > app.exec_() > > > > > QtCore.QThread.terminate( ) > > > > > > > > > > > > > > > > > > > > mt = MyThread() > > > > > mt.start() > > > > > print 'Main thread continuing...' > > > > > mt.wait() > > > > > print 'GUI thread finished.' > > > > > > > > > > 8< > > > > > > > > > > The app starts up (with a warning WARNING: QApplication was not > > > > > created > > > > > in the main() thread. ). I get a window, but no button, and clicking > > > > > on > > > > > the close button does nothing and I have to force the program to quit. > > > > > > > > > > There's got to be a way to get this working, right? Can anyone help me > > > > > along the right path? > > > > > > > > Read http://doc.trolltech.com/4.2/threads.html > > > > > > > > In particular the bit that says that exec_() must be called from the > > > > main > > > > thread and not from a QThread. > > > > > > > > Phil > > > > > > OK so that's all good... so how do I go about doing what I want then? > > > Can I set up a window in the second thread and start its event loop > > > without running the event loop in the core app? > > > > No. Read the second sentence of the paragraph I referred to. Also read the > > section "QObject Reentrancy". > > > > Phil > > OK I see that now. Thanks for pointing that out. So basically, I can't > do what I want at all. That's a bit of a pain. Is there no way of > tricking Qt into thinking I'm running it in the main thread? > It's possible with hackery from C++ but I seriously doubt you can do it from PyQt. > A > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyVISA 1.1 -- GPIB, USB, RS232 instrument control
Hallöchen! At http://pyvisa.sourceforge.net you can find information about the PyVISA package. It realises Python bindings for the VISA library functions, which enables you to control GPIB, USB, and RS232-serial measurement devices via Python. Yesterday I released version 1.1, which works much better together with older VISA implementations. Moreover, we finally have reports from Linux users. They successfully used PyVISA with Linux + NI/Tektronix GPIB hardware. Tschö, Torsten. F'up to comp.lang.python -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 (See http://ime.webhop.org for Jabber, MSN, etc.) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's going on here?
Dale Strickland-Clark wrote: > Python 2.4.2 (#1, Oct 13 2006, 17:11:24) a = object() a.spam = 1 > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'spam' class B(object): pass a = B() a.spam = 1 > > What is subclassing adding to the class here? Why can't I assign to > attributes of an instance of object? object itself doesn't have a __dict__ slot, so that very small objects (such as points) can be built without that overhead. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What's going on here?
> What is subclassing adding to the class here? A __dict__: >>> o = object() >>> dir(o) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] >>> class C(object): pass ... >>> c = C() >>> dir(c) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What's going on here?
Dale Strickland-Clark wrote: > Why can't I assign to attributes of an instance of object? it doesn't have any attribute storage. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
king kikapu wrote: > I have already downloaded and seen the trial of Komodo Professional. > Indeed it has a simple Gui Builder but one can only use TKinter on it. > No wxWidgets support and far from truly RAD, but it is the only > "integrated" > GUI builder in these IDEs... > > > On Nov 22, 4:31 pm, "Steve" <[EMAIL PROTECTED]> wrote: >> I haven't used it but Komodo (Professional version) says it has: >> >> ActiveState GUI Builder (Komodo Professional only) >> >> Enhance your applications with GUI dialogs: Simple, Tk-based dialog >> builder with seamless round-trip integration, for Perl, Python, Ruby, >> and Tcl. > I do a lot of GUI programming with wxPython. I find that switching from desktop 1 (Eclipse/PyDev) to desktop 2 (wxDesigner) becomes a reflex quite quickly ... even under Windows thanks to virtuawin (http://virtuawin.sourceforge.net) - both packages also are smart enough to notice when an open file has been modified elsewhere. I also program in Visual-Studio and overall do not find the RAD/IDE integration that much more convenient. Also, I generally get the job done in wxDesigner at the beginning of the project, and seldom have to get back into it to twick the interface. hg -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Validation in Python using XSV
I've read a bit about lxml, didn't found anything related to validating XML schema... Maybe you can give more details on how to install lxml and use it in Python to validate XML files against an XML Schema I'm going to ask the server administrator to install lxml, so I can't play around a lot with the system trying stuff. It would be nice if you can tell me: - What files to download, where to download them from - How to install it and configure it - How to import the functions in Python Thanks again Michel Stefan Behnel wrote: > > [EMAIL PROTECTED] wrote: > > Stefan Behnel wrote: > >> BTW: any reason you need to use XSV? There are some other libraries out > >> there > >> that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are > >> much more powerful than XSV. > > > > No particular reason for XSV > > I just want to validate XML files against an XML schema through Python. > > If you can suggest any other package for debian, I'll be glad to try > > it. > > Well, as I said: > > http://packages.debian.org/unstable/python/python-lxml > http://codespeak.net/lxml/ > > Just try "apg-get install python-lxml". > > Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Validation in Python using XSV
[EMAIL PROTECTED] wrote: > Stefan Behnel wrote: >>> [EMAIL PROTECTED] wrote: >>> Stefan Behnel wrote: BTW: any reason you need to use XSV? There are some other libraries out there that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are much more powerful than XSV. >>> No particular reason for XSV >>> I just want to validate XML files against an XML schema through Python. >>> If you can suggest any other package for debian, I'll be glad to try >>> it. >> Well, as I said: >> >> http://packages.debian.org/unstable/python/python-lxml >> http://codespeak.net/lxml/ >> >> Just try "apg-get install python-lxml". > > I've read a bit about lxml, didn't found anything related to validating > XML schema... > > Maybe you can give more details on how to install lxml and use it in > Python to validate XML files against an XML Schema > I'm going to ask the server administrator to install lxml, so I can't > play around a lot with the system trying stuff. > > It would be nice if you can tell me: > - What files to download, where to download them from > - How to install it and configure it > - How to import the functions in Python Being able to read can simplify a lot of things these days. See above to find out how to install lxml on Debian. See the page mentioned above to find out how to use lxml. I mean this page: http://codespeak.net/lxml/ in particular this section: http://codespeak.net/lxml/#documentation or simply search that page for things like "XML Schema" or "API documentation". Hope that gets you on the right track, Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: What's going on here?
Perhaps this piece of code might explain the behaviour: >>> class C( object ): ... __slots__ = () ... >>> o = C() >>> o.a = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'a' object behaves like having an implict __slots__ attribute. HTH, Gerald Dale Strickland-Clark schrieb: > Python 2.4.2 (#1, Oct 13 2006, 17:11:24) > [GCC 4.1.0 (SUSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > a = object() a > > > a.spam = 1 > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'spam' > class b(object): > > ...pass > ... > a = b() a > > <__main__.b object at 0xb7b4dcac> > a.spam = 1 > > > What is subclassing adding to the class here? Why can't I assign to > attributes of an instance of object? -- http://mail.python.org/mailman/listinfo/python-list
Re: file backup in windows
Hi! " are your friend. See, also: filepath = '"%HOMEPATH%\\LocalSettings\\Application Data\\Microsoft\\Outlook\\*"' and %USERPROFILE% %APPDATA% etc. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Validation in Python using XSV
This works for me. You were very helpful, thank you! Michel Stefan Behnel wrote: > [EMAIL PROTECTED] wrote: > > Stefan Behnel wrote: > >>> [EMAIL PROTECTED] wrote: > >>> Stefan Behnel wrote: > BTW: any reason you need to use XSV? There are some other libraries out > there > that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They > are > much more powerful than XSV. > >>> No particular reason for XSV > >>> I just want to validate XML files against an XML schema through Python. > >>> If you can suggest any other package for debian, I'll be glad to try > >>> it. > >> Well, as I said: > >> > >> http://packages.debian.org/unstable/python/python-lxml > >> http://codespeak.net/lxml/ > >> > >> Just try "apg-get install python-lxml". > > > > I've read a bit about lxml, didn't found anything related to validating > > XML schema... > > > > Maybe you can give more details on how to install lxml and use it in > > Python to validate XML files against an XML Schema > > I'm going to ask the server administrator to install lxml, so I can't > > play around a lot with the system trying stuff. > > > > It would be nice if you can tell me: > > - What files to download, where to download them from > > - How to install it and configure it > > - How to import the functions in Python > > Being able to read can simplify a lot of things these days. > > See above to find out how to install lxml on Debian. See the page mentioned > above to find out how to use lxml. I mean this page: > > http://codespeak.net/lxml/ > > in particular this section: > > http://codespeak.net/lxml/#documentation > > or simply search that page for things like "XML Schema" or "API > documentation". > > Hope that gets you on the right track, > Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyparsing Question.
"Ant" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I have a home-grown Wiki that I created as an excercise, with it's own > wiki markup (actually just a clone of the Trac wiki markup). The wiki > text parser I wrote works nicely, but makes heavy use of regexes, tags > and stacks to parse the text. As such it is a bit of a mantainability > nightmare - adding new wiki constructs can be a bit painful. > > So I thought I'd look into the pyparsing module, but can't find a > simple example of processing random text. For example, I want to parse > the following: > > "Some random text and '''some bold text''' and some more random text" > > into: > > "Some random text and some bold text and some more > random text" > > I have the following as a starting point: > > from pyparsing import * > > def parse(text): >italics = QuotedString(quoteChar="''") > >parser = Optional(italics) > >parsed_text = parser.parseString(text) > > > print parse("Test this is '''bold''' but this is not.") > > So if you could provide a bit of a starting point, I'd be grateful! > > Cheers, > Ant, Welcome to pyparsing! The simplest way to implement a markup processor in pyparsing is to define the grammar of the markup, attach a parse action to each markup type to convert the original markup to the actual results, and then use transformString to run through the input and do the conversion. This discussion topic has some examples: http://pyparsing.wikispaces.com/message/view/home/31853. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: file backup in windows
"MC" wrote: > " are your friend. to be precise, list2cmdline is your friend. see discussion and examples here: http://effbot.org/pyfaq/why-can-t-raw-strings-r-strings-end-with-a-backslash.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
I didn't know about this product you mention (wxDesigner). I download the trial and it seems pretty good, reminds me the wxGlade. So you make the GUI in this, generate Python code and import the module on your main project and reference it respectively ?? On Nov 22, 4:58 pm, hg <[EMAIL PROTECTED]> wrote: > king kikapu wrote: > > I have already downloaded and seen the trial of Komodo Professional. > > Indeed it has a simple Gui Builder but one can only use TKinter on it. > > No wxWidgets support and far from truly RAD, but it is the only > > "integrated" > > GUI builder in these IDEs... > > > On Nov 22, 4:31 pm, "Steve" <[EMAIL PROTECTED]> wrote: > >> I haven't used it but Komodo (Professional version) says it has: > > >> ActiveState GUI Builder (Komodo Professional only) > > >> Enhance your applications with GUI dialogs: Simple, Tk-based dialog > >> builder with seamless round-trip integration, for Perl, Python, Ruby, > >> and Tcl.I do a lot of GUI programming with wxPython. > > I find that switching from desktop 1 (Eclipse/PyDev) to desktop 2 > (wxDesigner) becomes a reflex quite quickly ... even under Windows > thanks to virtuawin (http://virtuawin.sourceforge.net) - both packages > also are smart enough to notice when an open file has been modified > elsewhere. > > I also program in Visual-Studio and overall do not find the RAD/IDE > integration that much more convenient. > > Also, I generally get the job done in wxDesigner at the beginning of the > project, and seldom have to get back into it to twick the interface. > > hg- Hide quoted text -- Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
king kikapu wrote: > > Hi to all, > > i am not sure if this question really belongs here but anyway, here it > goes: I have seen a lot of IDEs for Python, a lot of good stuff but > actually none of them has what, for example, Visual Studio has: a > Visual Editor (with the ability to place controls on forms etc etc), > or RAD > > I know that there is Glade but does anybody knows of some product, or > an ongoing effort to this direction so i can have a look at ? > > Coming from Windows and vs.net world, i think the only missing point > here is the integration of the Pyrthon with a RAD IDE... > > Thanks a lot and i apologize if this isn't the correct place for this > question... > > > Kikapu You might want to check out "dabo" www.dabodev.com. It's only at .7 but it has a GUI designer (uses wxPython). Has a 3 tier design and able to use MySQL, Postgres, FireBird, and soon MSSQL. The project has a ways to go but it's goal is to be similar to windows IDEs such as VFP, VB6 and VS. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Data not flushed at the moment
Here it's very well explained: http://groups.google.com/group/django-developers/browse_thread/thread/7bcb01ec38e7e6cd syncdb() method: http://code.djangoproject.com/browser/django/trunk/django/core/management.py#L435 But I'm not sure if is a django problem or from python. MindClass ha escrito: > I've to modifying a file, then I use a method imported that access to > that file and has to read the new data, but they are not read ( as if > the data were not flushed at the moment even using .close() > explicitly). > > --- > ... > ... > # If it is not installed, it looking for the line and insert it. > if not is_application: > print "Activating I18n application ..." > writefile_line = 0 > a = fileinput.input(settings, inplace=1) > #for line in fileinput.input(settings, inplace=1): > for line in a: > writefile_line += 1 > if writefile_line == readfile_line: > print "'%s'," % application_name > print line[:-1] > else: > print line[:-1] > a.close() > > update() > > def update(): > # Update the data base. > try: > from django.core.management import syncdb > except ImportError, err: > print "Can't import from Django: %s" % err > sys.exit(1) > > syncdb() > --- > > Note that it only fails if the update() method is run inner of 'if not > is_application', and I don't understand because it is happening so. But > the problem is that I need run it when that condition is performed. Any > idea? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python visual IDE
Yes, Actually when you create the project from wxDesigner, the "main" will also be generated for you ... then you include the correct files in eclipse (note that one file never needs to be edited ... like glade). I went for wxDesigner years ago when wxglade was fairly unstable ... have not tested it lately. wxDesigner has its own editor (so you can say it is a complete environment) ... but I only use it to automatically generate classes, events ... as eclipse+pydev bring much more to the picture. I really do not regret the expense. PS: wxDesigner will also generate code for other languages (never tried) : c++, c#, perl PPS: I'm not getting any money from them ;-) hg king kikapu wrote: > I didn't know about this product you mention (wxDesigner). > I download the trial and it seems pretty good, reminds me the wxGlade. > > So you make the GUI in this, generate Python code and import the module > > on your main project and reference it respectively ?? > > On Nov 22, 4:58 pm, hg <[EMAIL PROTECTED]> wrote: >> king kikapu wrote: >>> I have already downloaded and seen the trial of Komodo Professional. >>> Indeed it has a simple Gui Builder but one can only use TKinter on it. >>> No wxWidgets support and far from truly RAD, but it is the only >>> "integrated" >>> GUI builder in these IDEs... >>> On Nov 22, 4:31 pm, "Steve" <[EMAIL PROTECTED]> wrote: I haven't used it but Komodo (Professional version) says it has: ActiveState GUI Builder (Komodo Professional only) Enhance your applications with GUI dialogs: Simple, Tk-based dialog builder with seamless round-trip integration, for Perl, Python, Ruby, and Tcl.I do a lot of GUI programming with wxPython. >> I find that switching from desktop 1 (Eclipse/PyDev) to desktop 2 >> (wxDesigner) becomes a reflex quite quickly ... even under Windows >> thanks to virtuawin (http://virtuawin.sourceforge.net) - both packages >> also are smart enough to notice when an open file has been modified >> elsewhere. >> >> I also program in Visual-Studio and overall do not find the RAD/IDE >> integration that much more convenient. >> >> Also, I generally get the job done in wxDesigner at the beginning of the >> project, and seldom have to get back into it to twick the interface. >> >> hg- Hide quoted text -- Show quoted text - > -- http://mail.python.org/mailman/listinfo/python-list
Re: Caution newbie question: python window to stay open ?
Michael, put this at the top of your code. After the window closes read the testLog.out file. It may give you a clue as to what is happening. sys.stdout = open('testLog.out', 'w') jim-on-linux http://www.inqvista.com On Tuesday 21 November 2006 22:20, mkengel wrote: > Caution: newbie question > > I am using python 2.4.3-11 on Windows XP. > Problem: Python window closes immediately after > executing a *.py file (e.g. containing a > "print..." command. What do I have to do to > keep it open to see the results ? > > "Interactive window" stays open. > > Thank you. > Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
> OK I see that now. Thanks for pointing that out. So basically, I can't > do what I want at all. That's a bit of a pain. Is there no way of > tricking Qt into thinking I'm running it in the main thread? Maybe you can either invert the thread-roles - that is, run your "main" application in a thread, and if needed start the Qt-thing, or you might consider spawning a process and using pyro. Which will work very neat, done so myself. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
Diez B. Roggisch wrote: > > OK I see that now. Thanks for pointing that out. So basically, I can't > > do what I want at all. That's a bit of a pain. Is there no way of > > tricking Qt into thinking I'm running it in the main thread? > > Maybe you can either invert the thread-roles - that is, run your "main" > application in a thread, and if needed start the Qt-thing, or you might > consider spawning a process and using pyro. Which will work very neat, done > so myself. > > Diez Yeah I was thinking that's going to have to be the way to go... I can't run the main app in a child thread, so I'll have to spawn the GUI as a seperate process and communicate with it. Didn't know about pyro though, thanks for the link. You've used it successfully with PyQt in a seperate process? Cheers, Anders -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt app in seperate thread
anders wrote: > > Diez B. Roggisch wrote: >> > OK I see that now. Thanks for pointing that out. So basically, I can't >> > do what I want at all. That's a bit of a pain. Is there no way of >> > tricking Qt into thinking I'm running it in the main thread? >> >> Maybe you can either invert the thread-roles - that is, run your "main" >> application in a thread, and if needed start the Qt-thing, or you might >> consider spawning a process and using pyro. Which will work very neat, >> done so myself. >> >> Diez > > Yeah I was thinking that's going to have to be the way to go... I can't > run the main app in a child thread, so I'll have to spawn the GUI as a > seperate process and communicate with it. Didn't know about pyro > though, thanks for the link. You've used it successfully with PyQt in a > seperate process? Yup. I used it to spawn a python interpreter in a subprocess, and communicate some stuff between that and my main GUI app. The idea was to have a scriptable application, which allowed you could kill the script. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Note about getattr and '.'
Steven D'Aprano wrote: > On Tue, 21 Nov 2006 22:39:09 +0100, Mathias Panzenboeck wrote: > > Yes, this is known. I think IronPython uses a specialized dictionary for > > members, which prohibits > > malformed names. I don't know if there will be such a dictionary in any > > future CPython version. > > (Would be good.) > > Why would it be good? > > How many bugs have you found that were caused by this behaviour? It's not bugs. A specialized dictionary could be better optimized if you know it can only hold Python identifiers. There's talk of such a dictionary in Python 3000. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: text file parsing (awk -> python)
Peter Otten, your solution is very nice, it uses groupby splitting on empty lines, so it doesn't need to read the whole files into memory. But Daniel Nogradi says: > But the names of the fields (node, x, y) keeps changing from file to > file, even their number is not fixed, sometimes it is (node, x, y, z). Your version with the converters dict fails to convert the number of node, z fields, etc. (generally using such converters dict is an elegant solution, it allows to define string, float, etc fields): > converters = dict( > x=int, > y=int > ) I have created a version with a RE, but it's probably too much rigid, it doesn't handle files with the z field, etc: data = """node 10 y 1 x -1 node 11 x -2 y 1 z 5 node 12 x -3 y 1 z 6""" import re unpack = re.compile(r"(\D+) \s+ ([-+]? \d+) \s+" * 3, re.VERBOSE) result = [] for obj in unpack.finditer(data): block = obj.groups() d = dict((block[i], int(block[i+1])) for i in xrange(0, 6, 2)) result.append(d) print result So I have just modified and simplified your quite nice solution (I have removed the pprint, but it's the same): def open(filename): from cStringIO import StringIO return StringIO(data) from itertools import groupby records = [] for empty, record in groupby(open("records.txt"), key=str.isspace): if not empty: pairs = ([k, int(v)] for k,v in map(str.split, record)) records.append(dict(pairs)) print records Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
PyParsing and Headaches
Hi, I'm trying to construct a parser, but I'm stuck with some basic stuff... For example, I want to match the following: letter = "A"..."Z" | "a"..."z" literal = letter+ include_bool := "+" | "-" term = [include_bool] literal So I defined this as: literal = Word(alphas) include_bool = Optional(oneOf("+ -")) term = include_bool + literal The problem is that: term.parseString("+a") -> (['+', 'a'], {}) # OK term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't recognize any token since I didn't said the SPACE was allowed between include_bool and literal. Can anyone give me an hand here? Cheers! Hugo Ferreira BTW, the following is the complete grammar I'm trying to implement with pyparsing: ## L ::= expr | expr L ## expr ::= term | binary_expr ## binary_expr ::= term " " binary_op " " term ## binary_op ::= "*" | "OR" | "AND" ## include_bool ::= "+" | "-" ## term ::= ([include_bool] [modifier ":"] (literal | range)) | ("~" literal) ## modifier ::= (letter | "_")+ ## literal ::= word | quoted_words ## quoted_words ::= '"' word (" " word)* '"' ## word ::= (letter | digit | "_")+ ## number ::= digit+ ## range ::= number (".." | "...") number ## letter ::= "A"..."Z" | "a"..."z" ## digit ::= "0"..."9" And this is where I got so far: word = Word(nums + alphas + "_") binary_op = oneOf("* and or", caseless=True).setResultsName("operator") include_bool = oneOf("+ -") literal = (word | quotedString).setResultsName("literal") modifier = Word(alphas + "_") rng = Word(nums) + (Literal("..") | Literal("...")) + Word(nums) term = ((Optional(include_bool) + Optional(modifier + ":") + (literal | rng)) | ("~" + literal)).setResultsName("Term") binary_expr = (term + binary_op + term).setResultsName("binary") expr = (binary_expr | term).setResultsName("Expr") L = OneOrMore(expr) -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically replacing an API for another module
On Tue, Nov 21, 2006 at 05:00:32PM -0800, Tom Plunket wrote: > Bruno Desthuilliers wrote: > > > > I've got a bunch of code that runs under a bunch of unit tests. It'd > > > be really handy if when testing I could supply replacement > > > functionality to verify that the right things get called without those > > > things actually getting called, since frequently those calls take a > > > long time to execute and do things that, well, I don't really want to > > > do. > > > > Congratulation, you just rediscovered the MockObject. > > How do I rediscover something that I'm explicitly implementing? I had > set out specifically to mock an API, there was no rediscovery going > on. > > That does allow me to discover via Google the Python Mock Module, > though, which may well do what I want: > > from TestedModule import * > > my_win32file = Mock({ >'CopyFile': 'CopyFile called' >} > > win32file = my_win32file > > ...perhaps. > > I'm just a bit loathe to download and install more stuff when > something simpler appears to be near-at-hand. ...especially > considering the page describing this module doesn't offer any download > links! http://python-mock.sourceforge.net/ How about mini-mock: http://blog.ianbicking.org/minimock.html > > > -tom! > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically replacing an API for another module
> > I'm just a bit loathe to download and install more stuff when > > something simpler appears to be near-at-hand. ...especially > > considering the page describing this module doesn't offer any download > > links! http://python-mock.sourceforge.net/ > How about mini-mock: > http://blog.ianbicking.org/minimock.html Oh yeah, and the download link for python-mock is: http://sourceforge.net/project/showfiles.php?group_id=138804 -- http://mail.python.org/mailman/listinfo/python-list
KeyboardInterrupt from syscalls
Dear List, I was writing a Python extension module, including a sleeping call to poll(2), and noticed, to my great surprise (and joy), that even when blocking there, KeyboardInterrupt still worked properly when sending SIGINTs to the interpreter. It really got me wondering how it works, though. I would have thought that I would have to check manually for interrupts in one way or another, seeing how the thread in question should be stuck in my syscall. Sure, I return on EINTR, but I only return Py_FALSE, not NULL, so I wouldn't have thought that the interpreter would look for an exception having taken place (I would assume that it gets set in the sighandler). So how does it work? Does my code get to return Py_FALSE, and the interpreter ignores it, seeing that an exception is set? Is a non-local exit performed right over my call stack (in which case my next question would be how to clean up resources being used from my C code)? Or does something completely else happen? Fredrik Tolf -- http://mail.python.org/mailman/listinfo/python-list
utf - string translation
Hi, I'm bringing over a thread that's going on on f.c.l.python. The point was to get rid of french accents from words. We noticed that len('à') != len('a') and I found the hack below to fix the "problem" ... yet I do not understand - especially since 'à' is included in the extended ASCII table, and thus can be stored in one byte. Any clue ? hg # -*- coding: utf-8 -*- import string def convert(mot): print len(mot) print mot[0] print '%x' % ord(mot[1]) table = string.maketrans('àâäéèêëîïôöùüû','\x00a\x00a\x00a\x00e\x00e\x00e\x00e\x00i\x00i\x00o\x00o\x00u\x00u\x00u') return mot.translate(table).replace('\x00','') c = 'àbôö a ' print convert(c) -- http://mail.python.org/mailman/listinfo/python-list
How to pass a boolean to a stored proc using Cx_Oracle?
Hi, I am using Python 2.4 and cx_Oracle. I have a stored proc that takes two arguments. First is an NUMBER, second is a BOOLEAN. How do you call that stored procedure? After properly extablishing a connection, I have something like this: cursor = con.cursor() cursor.callproc("testproc",[123,True]) The problem I have ran into is that I keep getting an error from Oracle stating I don't have the variables defined in with the proper type. I changed to proc just to test it, so that it would take two numbers. I was able to make it run properly. So, what is the trick to pass a boolean? Thanks, joe -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt from syscalls
Fredrik Tolf wrote: > So how does it work? Does my code get to return Py_FALSE, and the > interpreter ignores it, seeing that an exception is set? Is a non-local > exit performed right over my call stack (in which case my next question > would be how to clean up resources being used from my C code)? Or does > something completely else happen? the signal handler adds an entry to a "pending calls" queue, which is checked by the interpreter at regular intervals. -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
hg wrote: > We noticed that len('à') != len('a') sounds odd. >>> len('à') == len('a') True are you perhaps using an UTF-8 editor? to keep your sanity, no matter what editor you're using, I recommend adding a coding directive to the source file, and using *only* Unicode string literals for non-ASCII text. or in other words, put this at the top of your file (where "utf-8" is whatever your editor/system is using): # -*- coding: utf-8 -*- and use u'' for all non-ASCII literals. -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
Fredrik Lundh wrote: > hg wrote: > >> We noticed that len('à') != len('a') > > sounds odd. > len('à') == len('a') > True > > are you perhaps using an UTF-8 editor? > > to keep your sanity, no matter what editor you're using, I recommend > adding a coding directive to the source file, and using *only* Unicode > string literals for non-ASCII text. > > or in other words, put this at the top of your file (where "utf-8" is > whatever your editor/system is using): > ># -*- coding: utf-8 -*- > > and use > >u'' > > for all non-ASCII literals. > > > Hi, The problem is that: # -*- coding: utf-8 -*- import string print len('a') print len('à') returns 1 then 2 and string.maketrans(str1, str2) requires that len(str1) == len(str2) hg -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
hg wrote: > Fredrik Lundh wrote: >> hg wrote: >> >>> We noticed that len('à') != len('a') >> sounds odd. >> > len('à') == len('a') >> True >> >> are you perhaps using an UTF-8 editor? >> >> to keep your sanity, no matter what editor you're using, I recommend >> adding a coding directive to the source file, and using *only* Unicode >> string literals for non-ASCII text. >> >> or in other words, put this at the top of your file (where "utf-8" is >> whatever your editor/system is using): >> >># -*- coding: utf-8 -*- >> >> and use >> >>u'' >> >> for all non-ASCII literals. >> >> >> > > Hi, > > The problem is that: > > # -*- coding: utf-8 -*- > import string > print len('a') > print len('à') > > returns 1 then 2 > > and string.maketrans(str1, str2) requires that len(str1) == len(str2) > > hg > > > > > PS: I'm running this under Idle -- http://mail.python.org/mailman/listinfo/python-list
Re: A python IDE for teaching that supports cyrillic i/o
tool69 wrote: > Sorry, but did someone knows if Pida works under Windows ? > Thanks. No, it doesn't really. You can start it up with a bit of hacking, and I have seen screenshots around, but only with the scintilla-based editor. We are waiting for SVG support in GTK on windows. Writing a vim-windows (non-embedded) plugin should be a trivial matter, but then we need some brave Windows user to do it). Ali -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
hg <[EMAIL PROTECTED]> wrote: >> or in other words, put this at the top of your file (where "utf-8" is >> whatever your editor/system is using): >> >># -*- coding: utf-8 -*- >> >> and use >> >>u'' >> >> for all non-ASCII literals. >> >> >> > > Hi, > > The problem is that: > > # -*- coding: utf-8 -*- > import string > print len('a') > print len('à') > > returns 1 then 2 And if you do what was suggested and write: # -*- coding: utf-8 -*- import string print len(u'a') print len(u'à') then you get: 1 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
Duncan Booth wrote: > hg <[EMAIL PROTECTED]> wrote: > >>> or in other words, put this at the top of your file (where "utf-8" is >>> whatever your editor/system is using): >>> >>># -*- coding: utf-8 -*- >>> >>> and use >>> >>>u'' >>> >>> for all non-ASCII literals. >>> >>> >>> >> Hi, >> >> The problem is that: >> >> # -*- coding: utf-8 -*- >> import string >> print len('a') >> print len('à') >> >> returns 1 then 2 > > And if you do what was suggested and write: > > # -*- coding: utf-8 -*- > import string > print len(u'a') > print len(u'à') > > then you get: > > 1 > 1 OK, How would you handle the string.maketrans then ? hg -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
hg wrote: > How would you handle the string.maketrans then ? maketrans works on bytes, not characters. what makes you think that you can use maketrans if you haven't gotten the slightest idea what's in the string? if you want to get rid of accents in a Unicode string, you can do the approaches described here http://www.peterbe.com/plog/unicode-to-ascii or here http://effbot.org/zone/unicode-convert.htm which both works on any Unicode string. -- http://mail.python.org/mailman/listinfo/python-list
PyParsing and Headaches
Hi, I'm trying to construct a parser, but I'm stuck with some basic stuff... For example, I want to match the following: letter = "A"..."Z" | "a"..."z" literal = letter+ include_bool := "+" | "-" term = [include_bool] literal So I defined this as: literal = Word(alphas) include_bool = Optional(oneOf("+ -")) term = include_bool + literal The problem is that: term.parseString("+a") -> (['+', 'a'], {}) # OK term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't recognize any token since I didn't said the SPACE was allowed between include_bool and literal. Can anyone give me an hand here? Cheers! Hugo Ferreira BTW, the following is the complete grammar I'm trying to implement with pyparsing: ## L ::= expr | expr L ## expr ::= term | binary_expr ## binary_expr ::= term " " binary_op " " term ## binary_op ::= "*" | "OR" | "AND" ## include_bool ::= "+" | "-" ## term ::= ([include_bool] [modifier ":"] (literal | range)) | ("~" literal) ## modifier ::= (letter | "_")+ ## literal ::= word | quoted_words ## quoted_words ::= '"' word (" " word)* '"' ## word ::= (letter | digit | "_")+ ## number ::= digit+ ## range ::= number (".." | "...") number ## letter ::= "A"..."Z" | "a"..."z" ## digit ::= "0"..."9" And this is where I got so far: word = Word(nums + alphas + "_") binary_op = oneOf("* and or", caseless=True).setResultsName("operator") include_bool = oneOf("+ -") literal = (word | quotedString).setResultsName("literal") modifier = Word(alphas + "_") rng = Word(nums) + (Literal("..") | Literal("...")) + Word(nums) term = ((Optional(include_bool) + Optional(modifier + ":") + (literal | rng)) | ("~" + literal)).setResultsName("Term") binary_expr = (term + binary_op + term).setResultsName("binary") expr = (binary_expr | term).setResultsName("Expr") L = OneOrMore(expr) -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically replacing an API for another module
Chris Lambacher wrote: > > > I'm just a bit loathe to download and install more stuff when > > > something simpler appears to be near-at-hand. ...especially > > > considering the page describing this module doesn't offer any download > > > links! http://python-mock.sourceforge.net/ > > Oh yeah, and the download link for python-mock is: > http://sourceforge.net/project/showfiles.php?group_id=138804 Heh, yeah I'm sure that's what I got when I went to sf.net and typed in the project name, then submitted a bug for the homepage that it doesn't offer any links to find the download. ;) -tom! -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
Fredrik Lundh wrote: > hg wrote: > >> How would you handle the string.maketrans then ? > > maketrans works on bytes, not characters. what makes you think that you > can use maketrans if you haven't gotten the slightest idea what's in the > string? > > if you want to get rid of accents in a Unicode string, you can do the > approaches described here > > http://www.peterbe.com/plog/unicode-to-ascii > > or here > > http://effbot.org/zone/unicode-convert.htm > > which both works on any Unicode string. > > > Thanks -- http://mail.python.org/mailman/listinfo/python-list
regex problem
Hi all, line is am trying to match is 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra29.90.00011 1 regex i have written is re.compile (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') I am trying to extract 0.0011 value from the above line. why doesnt it match the group(4) item of the match ? any idea whats wrong with it ? regards, KM -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
hg wrote: > Duncan Booth wrote: > > hg <[EMAIL PROTECTED]> wrote: > > > >>> or in other words, put this at the top of your file (where "utf-8" is > >>> whatever your editor/system is using): > >>> > >>># -*- coding: utf-8 -*- > >>> > >>> and use > >>> > >>>u'' > >>> > >>> for all non-ASCII literals. > >>> > >>> > >>> > >> Hi, > >> > >> The problem is that: > >> > >> # -*- coding: utf-8 -*- > >> import string > >> print len('a') > >> print len('à') > >> > >> returns 1 then 2 > > > > And if you do what was suggested and write: > > > > # -*- coding: utf-8 -*- > > import string > > print len(u'a') > > print len(u'à') > > > > then you get: > > > > 1 > > 1 Some general comments: 1. There has been at least one thread on the subject of ripping accents off Latin1 characters in the last 3 or 4 months. Try Google. 2. About your earlier problem, when len(thing1) != len(thing2): In that and similar situations, it can be *very* useful to use this technique: print repr(thing1), type(thing1) print repr(thing2), type(thing2) Go back now and try it out! > OK, > > How would you handle the string.maketrans then ? > I suggest that you first read the documentation on the str and unicode "translate" methods. You can obtain this quickly at the interactive prompt by doing help(''.translate) and help(u''.translate) respectively. Next steps: Is your *real* data (not the examples you were hard-coding earlier) encoded (latin1, utf8) in str objects or is it in unicode objects? After reading previous posts my head is spinning & I'm not going to guess; you determine it yourself. [pseudocode -- blend of Pythonic & Knuthian styles] if latin1: (A) you can use string.maketrans and str.translate immediately. elif unicode: (B) either (1) encode to latin1; goto (A) or (2) use unicode.translate with do-it-yourself mapping elif utf8: decode to unicode; goto (B) else: ??? HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: PyParsing and Headaches
On Wed, Nov 22, 2006 at 11:17:52AM -0800, Bytter wrote: > Hi, > > I'm trying to construct a parser, but I'm stuck with some basic > stuff... For example, I want to match the following: > > letter = "A"..."Z" | "a"..."z" > literal = letter+ > include_bool := "+" | "-" > term = [include_bool] literal > > So I defined this as: > > literal = Word(alphas) > include_bool = Optional(oneOf("+ -")) > term = include_bool + literal + here means that you allow a space. You need to explicitly override this. Try: term = Combine(include_bool + literal) > > The problem is that: > > term.parseString("+a") -> (['+', 'a'], {}) # OK > term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't > recognize any token since I didn't said the SPACE was allowed between > include_bool and literal. > > Can anyone give me an hand here? > > Cheers! > > Hugo Ferreira > > BTW, the following is the complete grammar I'm trying to implement with > pyparsing: > > ## L ::= expr | expr L > ## expr ::= term | binary_expr > ## binary_expr ::= term " " binary_op " " term > ## binary_op ::= "*" | "OR" | "AND" > ## include_bool ::= "+" | "-" > ## term ::= ([include_bool] [modifier ":"] (literal | range)) | ("~" > literal) > ## modifier ::= (letter | "_")+ > ## literal ::= word | quoted_words > ## quoted_words ::= '"' word (" " word)* '"' > ## word ::= (letter | digit | "_")+ > ## number ::= digit+ > ## range ::= number (".." | "...") number > ## letter ::= "A"..."Z" | "a"..."z" > ## digit ::= "0"..."9" > > And this is where I got so far: > > word = Word(nums + alphas + "_") > binary_op = oneOf("* and or", caseless=True).setResultsName("operator") > include_bool = oneOf("+ -") > literal = (word | quotedString).setResultsName("literal") > modifier = Word(alphas + "_") > rng = Word(nums) + (Literal("..") | Literal("...")) + Word(nums) > term = ((Optional(include_bool) + Optional(modifier + ":") + (literal | > rng)) | ("~" + literal)).setResultsName("Term") > binary_expr = (term + binary_op + term).setResultsName("binary") > expr = (binary_expr | term).setResultsName("Expr") > L = OneOrMore(expr) > > > -- > GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: gopherlib deprecated in 2.5
"Szabolcs Nagy" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I've just seen that gopherlib is deprecated in python 2.5 > http://docs.python.org/lib/module-gopherlib.html > > we still use this protocol (though there are only few working gopher > servers are left on the net) > > My friend just wrote a standard compliant gopher server (pygopherd had > some problems oslt) and it's much better for hierarchycal content > sharing than the http (which is overrated and misused in this respect). > > So i don't really understand why would one remove it from python. It's > a friendly, tiny, simple, standard protocol. The devolopers thought that perhaps gopherlib was unused in new or updated-to-new releases code. Even if it is by a few, there is still the question of whether gopherlib should be in the stdlib in preference to modules that would be useful to more people or whether it should be a downloadable module at PyPI. The latter would require someone to take ownership of it. You might consider posting a note on py dev (easily accessible via gmane) to let them know there is at least one current user. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Protecting against SQL injection
Tor Erik Soenvisen wrote: > How safe is the following code against SQL injection: > > # Get user privilege > digest = sha.new(pw).hexdigest() > # Protect against SQL injection by escaping quotes > uname = uname.replace("'", "''") > sql = 'SELECT privilege FROM staff WHERE ' + \ > 'username=\'%s\' AND password=\'%s\'' % (uname, digest) > res = self.oraDB.query(sql) This is definitely *not* safe. For instance, set uname = r"\' or 1=1 --" You must replace the backslash with a double backslash as well. But as already suggested, you should better use query parameters. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: regex problem
> line is am trying to match is > 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra29.90.00011 1 > > regex i have written is > re.compile > (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') > > I am trying to extract 0.0011 value from the above line. > why doesnt it match the group(4) item of the match ? > > any idea whats wrong with it ? Well, your ".{25}\s{3}" portion only gets you to one space short of your 29.9, so your "(\d+..." fails to match " 29.9" because there's an extra space there. My guess (from only one datum, so this could be /way/ off base) would be that you mean "\s{4}" or possibly "\s{3,4}" It seems like a very overconstrained regexp, but it might be just what you need to isolate the single line (or class of line) amongst the chaff of thousand others of similar form. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
Thank you for your answers. In fact, I'm getting start with Python. I was looking for transform a text through elementary cryptographic processes (Vigenère). The initial text is in a file, and my system is under UTF-8 by default (Ubuntu) -- http://mail.python.org/mailman/listinfo/python-list
Re: regex problem
HI Tim, oof! thats true! thanks a lot. Is there any tool to simplify building the regex ? regards, KM On 11/23/06, Tim Chase <[EMAIL PROTECTED]> wrote: > line is am trying to match is > 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra29.90.00011 1 > > regex i have written is > re.compile > (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') > > I am trying to extract 0.0011 value from the above line. > why doesnt it match the group(4) item of the match ? > > any idea whats wrong with it ? Well, your ".{25}\s{3}" portion only gets you to one space short of your 29.9, so your "(\d+..." fails to match " 29.9" because there's an extra space there. My guess (from only one datum, so this could be /way/ off base) would be that you mean "\s{4}" or possibly "\s{3,4}" It seems like a very overconstrained regexp, but it might be just what you need to isolate the single line (or class of line) amongst the chaff of thousand others of similar form. -tkc -- http://mail.python.org/mailman/listinfo/python-list