sorting a file
Hi all, I have a file with three columns i need to sort the file with respect to the third column. How do I do it uisng python. I used Linux command to do this. Sort but i not able to do it ? can any body ssuggest me -- Beema Shafreen -- http://mail.python.org/mailman/listinfo/python-list
Re: How to sort very large arrays?
On Jun 14, 1:54 am, kj <[EMAIL PROTECTED]> wrote: > I'm downloading some very large tables from a remote site. I want > to sort these tables in a particular way before saving them to > disk. In the past I found that the most efficient way to do this > was to piggy-back on Unix's highly optimized sort command. So, > from within a Perl script, I'd create a pipe handle through sort > and then just print the data through that handle: This is a python clone of your code from a python rookie :) from os import popen p = popen("sort -t '\t' -k1,1 -k2,2 -u > %s" % out_file) for line in data: print >> p, line there is no "die $!" here, I think it is good to let python throw the exception to your console > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python > Way" to do this. > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to sort very large arrays?
On Jun 14, 1:54 am, kj <[EMAIL PROTECTED]> wrote: > I'm downloading some very large tables from a remote site. I want > to sort these tables in a particular way before saving them to > disk. In the past I found that the most efficient way to do this > was to piggy-back on Unix's highly optimized sort command. So, > from within a Perl script, I'd create a pipe handle through sort > and then just print the data through that handle: This is a python clone of your code from a python rookie :) from os import popen p = popen("sort -t '\t' -k1,1 -k2,2 -u > %s" % out_file) for line in data: print >> p, line there is no "die $!" here, I think it is good to let python throw the exception to your console > > open my $out, "|$sort -t '\t' -k1,1 -k2,2 -u > $out_file" or die $!; > print $out $_ for @data; > > But that's distinctly Perlish, and I'm wondering what's the "Python > Way" to do this. > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
ANN: pytoken 1.0 - native 86 machine code scanner generator
I am pleased to announce the 1.0 version of pytoken. It is available here: http://code.google.com/p/pytoken/downloads/list What is pytoken Pytoken is a scanner generator. Given an input specification - a bunch of regular expressions - pytoken will generate x86 machine code that recognizes those regular expressions. Pytoken will be most useful for programmers that want to parse complex text files. Pytoken has separate objects for scanners and buffers. Here is a simple example: import pytoken lexer_obj = pytoken.lexer() lexer_obj.add_pattern("a", 1) lexer_obj.add_pattern("b", 2) lexer_obj.compile_to_machine_code() buf = pytoken.lexer_state() buf.set_input("ab") tok = lexer_obj.get_token(buf) assert tok == 1 tok = lexer_obj.get_token(buf) assert tok == 2 Pytoken has been written in a portable fashion - it is designed to support multiple CPU types, even though only the x86 (32 bit) is supported now. -Ram -- http://mail.python.org/mailman/listinfo/python-list
######THEY DO DIFFERENT THINGS TO GET HERE#########
Hi girls and friends.. earn more money in my site its really very different you want like it see it . www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com www.superthings4.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy: handling float('NaN') different in XP vs. Linux
On Jun 14, 3:33 pm, "John [H2O]" <[EMAIL PROTECTED]> wrote: > John Machin wrote: > > > Avoid impolite astonishment; RTFloatingM instead: > > """ > > > HTH, > > John > > -- > > I guess the key here is that it is not an issue with Python, but C... can I > change 'the underlying C code?' The underlying C code for the Windows C RTL is probably on a server in a bunker in Redmond WA ... good luck :-) Perhaps you could start lashing up something along the lines that Dan mentioned, e.g. floated = { 'NaN': 1e1000 / 1e1000, 'Inf': whatever, }.get def myfloat(s): try: return float(s) except: value = floated(s) if value is not None: raise return value Then when/if your mapping has enough entries to make it worthwhile, you could maybe suggest that this be done in Numpy or in the Python core. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: os.startfile() on a mac
search, search for example http://groups.google.be/group/comp.lang.python/browse_thread/thread/bddbb6861bf5b084/af7070e5b3971d53?hl=fr&lnk=gst&q=os.startfile+unix#af7070e5b3971d53 -- http://mail.python.org/mailman/listinfo/python-list
Hard to understand 'eval'
Hi, It seems to be strange that give me syntax error inside an eval statement. I'm looking at it carefully but I can't see any flaw. Here it's part of the code: for nn in stn_items: value= eval('cp.%s' %nn) if value and (nn in 'log, trash, multithread, verbose, download'): cfl[wchkey][nn]= chkbool(value) continue if value: cnfg= 'cfl[wchkey][nn]= _%s(value)' %nn eval(cnfg) And the output on pdb: (Pdb) p cnfg 'cfl[wchkey][nn]=_append(value)' (Pdb) p cfl[wchkey][nn] False (Pdb) eval('cfl[wchkey][nn]= _append(value)') *** SyntaxError: invalid syntax (, line 1) (Pdb) p value '230k' (Pdb) p nn 'append' Obviously I've an _append() function to convert into decimal the given value. Other "eval" before this not issuing problems and also rather complicated, but I'm not seeing the error here. I'd like to study a class that might get a string and convert it into function, once it's found inside the program. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html -- http://mail.python.org/mailman/listinfo/python-list
write Python dict (mb with unicode) to a file
hi all, what's the best way to write Python dictionary to a file? (and then read) There could be unicode field names and values encountered. Thank you in advance, D. -- http://mail.python.org/mailman/listinfo/python-list
We are all consenting adults here
Who coined this originally? I was reminded of it having just received a text message from mobile phone company Orange, in response to my request for them to review their policy of blocking access to this group (and, I suspect, all of Usenet). I quote: "Your request has been actioned and the content is confirmed as only suitable for customers over the age of 18. URL: http://groups/google.com/group/comp.lang.python"; David -- http://mail.python.org/mailman/listinfo/python-list
Re: can't assign to literal
On 17:06, venerdì 13 giugno 2008 Dennis Lee Bieber wrote: > -=-=-=-=-=-=- (make sure you have a fixed width client) > Very good indeed :) Specially to do with block reformatting. I just post my script to demonstrate my thoughts in what I meant as justifying. Specially considering that I meant character justification regardless of its width. Monospace chars will show pretty alignment. BTW, I'm beginner and my coding takes much try-and-test. ;) -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking list by using of exception
On 15:37, venerdì 13 giugno 2008 Nader wrote: > try: > list_of_files != [] > get the files > For file in list_of_files: try: myfile = open(file, 'r') except (IOError, OSError): print"Your %s file wasn't open" %file # here you can do something with your open file as read option myfile.readlines() # for example -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Debuggers
On 19:21, venerdì 13 giugno 2008 R. Bernstein wrote: > I'm not completely sure what you mean, but I gather that in > post-mortem debugging you'd like to inspect local variables defined at the > place of error. Yes, exactly. This can be seen with pdb, but not pydb. If I'm testing a piece of code and it breaks, then I'd like to see the variables and find which of them doesn't go as expected. > Python as a language is a little different than say Ruby. In Python > the handler for the exception is called *after* the stack is unwound I'm not doing comparison with other languages. I'm simply curious to know why pydb don't keep variables like pdb. Final, I agreed the idea to restart the debugger when an exception is trow. It could be feasible to let reload the file and restart. Some time I can re-run the program , as the error is fixed, but sometime pdb doesn't recognize the corrections applied. I mean that after a post-mortem event, the debugger should forget all variables and reload the program, which meanwhile could be debugged. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: write Python dict (mb with unicode) to a file
dmitrey wrote: > hi all, > what's the best way to write Python dictionary to a file? > > (and then read) > > There could be unicode field names and values encountered. > Thank you in advance, D. pickle/cPickle, perhaps, if you're willing to trust the file (since it's basically eval()ed)? Or JSON (use simplejson or the enhanced version of cjson), though I doubt it would be super-fast. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Summing a 2D list
Maric Michaud <[EMAIL PROTECTED]> writes: > Le Friday 13 June 2008 17:55:44 Karsten Heymann, vous avez écrit : >> Maric Michaud <[EMAIL PROTECTED]> writes: >> > So, writing C in python, which has dictionnary as builtin type, >> > should be considered "more elegant" ? >> >> IMO that's a bit harsh. > harsh ? Sorry, I'm not sure to understand. Never mind, I got carried away. >> I'd never argue that using a dictionary is the obvious and natural >> data structure for this case. But is it the best? Honestly, as your >> very nice example shows, we have two solutions that are equally >> fast, equally complex to code and equally robust, but one needs > > Yes, but my example take ordered integer for keys (users' names) > which they should not be in a real case, so retrieving the result is > by way easier (and faster) with a dictionnary. Of course. As I wrote in my first post, my proposal dependeds upon the users being a numerical and compact list with a known maximum, as in the OP's example. Otherwise my approach makes no sense at all :-) >> approximately the double amount of memory compared to the other. > > I don't see how you came to this conclusion. Are you sure the extra > list take twice more memory than the extra dictionary ? I'm referring to the resulting data structure. A list with n items should take approx. half the space of a dictionary with n keys and n entries. Or, the other way round, if i have a dictionary with keys 1..n, why shouldn't I use a list instead. Yours, Karsten -- http://mail.python.org/mailman/listinfo/python-list
Re: write Python dict (mb with unicode) to a file
On 17:13, sabato 14 giugno 2008 dmitrey wrote: > hi all, > what's the best way to write Python dictionary to a file? > Pickle or ConfigParser. You may gather more details at http://docs.python.org/lib/persistence.html -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: write Python dict (mb with unicode) to a file
On Jun 14, 7:13 pm, dmitrey <[EMAIL PROTECTED]> wrote: > hi all, > what's the best way to write Python dictionary to a file? > > (and then read) > > There could be unicode field names and values encountered. I'm presuming that "field names" means "dictionary keys". If not unicode, are the remainder of the keys and values: strings encoded in ASCII? strings encoded otherwise? neither str nor unicode? > Thank you in advance, D. "Best" depends on how you measure it. cPickle is one alternative (ensure you use protocol=-1). Speed should be OK, but format not documented AFAIK other than in the source code, so not readable outside the Python universe. Also it won't matter what types of data you have. A portable alternative (and simple enough if all your data are str/ unicode) would be to encode all your strings as UTF-8, and then write the key/value pairs out to a csv file: # untested pseudocode for basestring-only case: for k, v in mydict.iteritems(): csv_writer.writerow((k.encode('utf8'), v.encode('utf8'))) # if you have str instances encoded other than in ASCII or your system's default encoding, you'll have to work a bit harder ... Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
WORK PART TIME GET $100 A WEEK CLICK HERE
HI I AM DOING HOME BASED BUSINESS WITH PART TIME I AM GETTING GOOD EARNING DAILY MINIMUM OF THE PAYMENT WEAKLY $100 JUST CLICK HERE YOU DEFIANTLY YOU WILL WON http://www.eyeearn.com/10122618/signup -- http://mail.python.org/mailman/listinfo/python-list
Re: python screen scraping/parsing
Dan Stromberg wrote: BeautifulSoup is a pretty nice python module for screen scraping (not necessarily well formed) web pages. On Fri, 13 Jun 2008 11:10:09 -0700, bruce wrote: Hi... got a short test app that i'm playing with. the goal is to get data off the page in question. basically, i should be able to get a list of "tr" nodes, and then to iterate/parse them. i'm missing something, as i think i can get a single node, but i can't figure out how to display the contents of the node.. nor how to get the list of the "tr" nodes my test code is: #!/usr/bin/python #test python script import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList # # Parse pricegrabber.com # datafile tfile = open("price.dat", 'wr+') efile = open("price_err.dat", 'wr+') urlopen = urllib2.urlopen ##cj = urllib2.cookielib.LWPCookieJar() Request = urllib2.Request br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } url ="http://www.pricegrabber.com/rating_summary.php/page=1"; #=== if __name__ == "__main__": # main app txdata = None # # get the kentucky test pages #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] br.open(url) #cj.save(COOKIEFILE)# resave cookies res = br.response() # this is a copy of response s = res.read() # s contains HTML not XML text d = libxml2dom.parseString(s, html=1) print "d = d",d #get the input/text dialogs #tn1 = "//[EMAIL PROTECTED]'main_content']/form[1]/input[position()=1]/@name" t1 = "/html/body/[EMAIL PROTECTED]'pgSiteContainer']/[EMAIL PROTECTED]'pgPageContent']/table [2]/tbo dy" tr = "/html/body/[EMAIL PROTECTED]'pgSiteContainer']/[EMAIL PROTECTED]'pgPageContent']/table [2]/tbo dy/tr[4]" tr_=d.xpath(tr) print "len =",tr_[1].nodeValue print "fin" --- my issue appears to be related to the last "tbody", or tbody/tr[4]... if i leave off the tbody, i can display data, as the tr_ is an array with data... with the "tbody" it appears that the tr_ array is not defined, or it has no data... however, i can use the DOM tool with firefox to observe the fact that the "tbody" is there... so.. what am i missing... thoughts/comments are most welcome... also, i'm willing to send a small amount via paypal!! -bruce FYI: Mechanize includes all of BeautifulSoup's methods and adds additional functionality (like forms handling). Larry -- http://mail.python.org/mailman/listinfo/python-list
Platform independent code?
I have read that Python is a platform independent language. But on this page: http://docs.python.org/tut/node4.html#SECTION00422 it seems that making a python script executable is platform dependant: 2.2.2 Executable Python Scripts On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line #! /usr/bin/env python (assuming that the interpreter is on the user's PATH) at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows ("\r\n") line ending. Note that the hash, or pound, character, "#", is used to start a comment in Python. The script can be given an executable mode, or permission, using the chmod command: $ chmod +x myscript.py Are there any guidelines (API'S) that gurantees that the python code will be platform independent? -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy: handling float('NaN') different in XP vs. Linux
John [H2O] wrote: > I have a script: > > from numpy import float > OutD=[] > v=['3','43','23.4','NaN','43'] > OutD.append([float(i) for i in v[1]]) > > > On linux: > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > [EMAIL PROTECTED] analysis]$ python jnk.py > [[3.0, 43.0, 23.399, nan, 43.0]] > > On XP: > Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\analysis>C:\Python25\python.exe jnk.py > Traceback (most recent call last): > File "jnk.py", line 4, in > OutD.append([float(i) for i in v]) > ValueError: invalid literal for float(): NaN I've fixed the issue for Python 2.6 and 3.0 a while ago. Mark and I have spent a lot of time on fixing several edge cases regarding inf, nan and numerical unsound functions in Python's math und cmath module. Christian -- http://mail.python.org/mailman/listinfo/python-list
How do I sort items in a tableview without a column being selected?
I have this TableView, which is sorted by column when the user clicks on the header. The problem is though, that all the items are selected and nothing gets sorted. But if the window loses focus everything's get's sorted. Basically I have list of tags say, [{"artist":"Artist1","title":Title1"} , {"artist":"Artist2" , "title": "Title2"}] etc. Where each tag is listed in a column. Then I sort them and reset. Here's the code: def sort(self,column,order=Qt.DescendingOrder): tag=self.headerdata.text newdic={} li=[] i=0 for z in self.taginfo: #taginfo has all the tags if not newdic.has_key(z[tag]): newdic[z[tag]]=z li.append(z[tag]) else: newdic[z[tag] + str(i)]=z li.append(z[tag] + str(i)) i+=1 li.sort() self.taginfo=[newdic[z] for z in li] self.reset() Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: Platform independent code?
Hi, Python is a platform independent language, period. You can always excute a Python script with python script.py. Now, with Windows, you can execute the script by doucle-clicking on it. With Linux, it's different, you have to use the shebang line to execute a script with the correct interpreter. But this has nothing to do with the fact that Python is a platform independent language. Some modules may not be available on all platform, for the answer to this question, see the documentation of the module ;) Matthieu 2008/6/14 saneman <[EMAIL PROTECTED]>: > I have read that Python is a platform independent language. But on this > page: > > http://docs.python.org/tut/node4.html#SECTION00422 > > it seems that making a python script executable is platform dependant: > > 2.2.2 Executable Python Scripts > On BSD'ish Unix systems, Python scripts can be made directly executable, > like shell scripts, by putting the line > > > #! /usr/bin/env python > (assuming that the interpreter is on the user's PATH) at the beginning of > the script and giving the file an executable mode. The "#!" must be the > first two characters of the file. On some platforms, this first line must > end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows > ("\r\n") line ending. Note that the hash, or pound, character, "#", is used > to start a comment in Python. > > The script can be given an executable mode, or permission, using the chmod > command: > > > $ chmod +x myscript.py > > > > Are there any guidelines (API'S) that gurantees that the python code will be > platform independent? > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -- http://mail.python.org/mailman/listinfo/python-list
Re: Platform independent code?
saneman wrote: I have read that Python is a platform independent language. But on this page: http://docs.python.org/tut/node4.html#SECTION00422 it seems that making a python script executable is platform dependant: 2.2.2 Executable Python Scripts On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line #! /usr/bin/env python (assuming that the interpreter is on the user's PATH) at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows ("\r\n") line ending. Note that the hash, or pound, character, "#", is used to start a comment in Python. The script can be given an executable mode, or permission, using the chmod command: $ chmod +x myscript.py Are there any guidelines (API'S) that gurantees that the python code will be platform independent? Generally you have to stay away from platform "dependent" constructs. Esamples: 1) Use os.path methods everywhere in your code so you won't need to worry about os.path.sep (slash or backslash). 2) Use lowest common denominator when naming files to make your scripts work cross platform. 3) Stay away from os-specific calls/interfaces when possible. Manipulating file permissions, etc is always os-specific. 4) Use config files instead of relying on registry in Windows. 5) Stay away from code that depends on 32/64 bit objects or endian-ness of storage (struct objects). This is machine specific not OS specific but still counts. 6) If you have GUI, use something like wxWindows which provides cross platform GUI support. 7) Be careful using non-Python libraries (C-libraries) should be done with care to make sure that the library is available for all target operating systems. 8) using os.system or the subsystem module must be done with much care and probably won't be cross platform compatible. Hope the suggestions help. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Summing a 2D list
On Jun 12, 3:48 pm, Mark <[EMAIL PROTECTED]> wrote: > Is this possible? def foobar(user,score): sums = {} for u,s in zip(user,score): try: sums[u] += s except KeyError: sums[u] = s return [(u, sums[u]) for u in sums].sort() usersum = foobar(user,score) for u,s in usersum: print "%d %d" % (u,s) -- http://mail.python.org/mailman/listinfo/python-list
#define in swig
I've a problem with python wrapper of C library. In a library's file there are #define istruction but I can't access it from python. Other functio works correctly. The define istruction is like this: #define START_OF_D _table_element=_mainsys- >matD,_table_end=_table_element+Dsize(_mainsys) #define START_OF_X _table_element=_mainsys- >matX,_table_end=_table_element+_mainsys->matXsize #define START_OF_MAT(set,num) _table_element=(set),_table_end=_table_element+(num)*_mainsys- >setAsize #define END_OF_MAT (_table_element<_table_end) #define NEXT_OF_MAT_table_element+=_mainsys->setAsize #define ELEM_OF_MAT_table_element #define ElemOfRule(rules,num,attr) (rules)[(num)*(_mainsys- >attributes_num)+(attr)] thanks Gianluca -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a file
On Saturday 14 June 2008 03:15, Beema shafreen wrote: > Hi all, > > I have a file with three columns i need > to sort the file with respect to the third > column. How do I do it uisng python. I > used Linux command to do this. Sort but i > not able to do it ? can any body ssuggest > me I have used this method to solve similar problems. This is a consept of how to do what you want, but you will have to work a little to get it right. You might try something like this; Dict = {} ##create a dictionary make a list of all column3 values for loop colum3 values Make these values the key in a dictionary If the values are long, you can use the first 7 to 15 characters if you want. use this key to equal all the values in the other columns on the same row. Dict[column3] = column1, column2, column3 once the dictionary is made get the dictionary key x = Dict.keys() ## get the keys from Dict x.sort() # produce a sorted list of keys of column3 Loop these sorted keys to extract from the dictionary the values related to each jim-on-linux http://:inqvista.com -- http://mail.python.org/mailman/listinfo/python-list
NATURIST
http://carsmodifications.blogspot.com http://naturismeurope.blogspot.com http://computerconstruction.blogspot.com http://scoutingguiding.blogspot.com http://britishwaterways.blogspot.com http://ukfinanceissues.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Creating a TCP/IP connection on already-networked computers
Let me see if this question even makes sense...I'm reading Core Python Programming and I jumped ahead to the more specific topics like network programming. I plan to follow along with the example in that chapter and create a socket connection between my desktop and laptop. However, these two computers are already connected on my home network (using the Windows Network Setup Wizard), so I was wondering if this will have any effect on what I might try to do with Python. In other words, if the program I write actually works and allows the two computers to speak to each other, will that be a result purely of the program, or will it have anything to do with the fact that they are already on a home network together? (i.e. there's another variable in play?) Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Was the move to Python 2.0 as big a deal?
Just curious if people put up any resistance to 2.0 like some people do for 3.0. Was it as big of a change in the language, or was the transition smoother? It seems silly for anyone to say they would prefer to stick with 1.x versions at this point, so perhaps we'll get there with 3.0 eventually too. Anyway, I'm just trying to figure out if the whole "I don't like 3.0" mentality (of some people, not all of course) is merely a result of it still being new and not even released yet, and will completely go away after a year or two; or if there really are such drastic changes that people won't want to adopt it at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Was the move to Python 2.0 as big a deal?
> Just curious if people put up any resistance to 2.0 like some people do > for 3.0. IIRC, yes, it was. People have continued to use Python 1.5.2 afterwards for several years. > Was it as big of a change in the language, or was the > transition smoother? The changes were significantly smaller, so the transition was smoother. > It seems silly for anyone to say they would prefer > to stick with 1.x versions at this point, so perhaps we'll get there > with 3.0 eventually too. People will continue to use 2.x for several years certainly. > Anyway, I'm just trying to figure out if the whole "I don't like 3.0" > mentality (of some people, not all of course) is merely a result of it > still being new and not even released yet, and will completely go away > after a year or two; or if there really are such drastic changes that > people won't want to adopt it at all. A year or two won't be sufficient. IMO, the resistance is due to the feeling "it will cause me efforts to change my code, and I don't like additional efforts". This is a reasonable point to take, IMO, so people who have the time and inclination to convert their code will do so, and many others won't. Over time, people will convert the code when they do have the time (or the feeling that they shouldn't push it away further). Eventually, those people will convert that need some kind of library (change) that is only available for 3.x. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-14, John Salerno <[EMAIL PROTECTED]> wrote: > Let me see if this question even makes sense...I'm reading > Core Python Programming and I jumped ahead to the more > specific topics like network programming. I plan to follow > along with the example in that chapter and create a socket > connection between my desktop and laptop. > > However, these two computers are already connected on my home > network (using the Windows Network Setup Wizard), so I was > wondering if this will have any effect on what I might try to > do with Python. I don't know the example programs you're talking about, but it's a pretty good bet that the example programs won't work if the two computers can't reach each other using IP networking. > In other words, if the program I write actually works and > allows the two computers to speak to each other, will that be > a result purely of the program, or will it have anything to do > with the fact that they are already on a home network > together? (i.e. there's another variable in play?) The two Python programs won't be able to communicate with each other unless the two computers are already set up on network(s) that allow the routing of IP packets between the two computers. I presume that's what the "Network Setup Wizard" did (set up IP networking), but I don't really do windows (I especially don't do "Wizards" if I can avoid it). -- Grant Edwards grante Yow! Alright, you!! at Imitate a WOUNDED SEAL visi.compleading for a PARKING SPACE!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Was the move to Python 2.0 as big a deal?
On 2008-06-14, John Salerno <[EMAIL PROTECTED]> wrote: > Just curious if people put up any resistance to 2.0 like some > people do for 3.0. Not that I remember. > Was it as big of a change in the language, or was the > transition smoother? It was pretty much a non-event. The changes from 1.x->2.0 were mostly all backwards-compatible. > Anyway, I'm just trying to figure out if the whole "I don't > like 3.0" mentality >From what I can tell, 2.x->3.0 is going to be a much larger change than was 1.x->2.0. A lot of code is going break (that wasn't true with the 1.x->2.0 transition). > (of some people, not all of course) is merely a result of it > still being new and not even released yet, and will completely > go away after a year or two; or if there really are such > drastic changes that people won't want to adopt it at all. My prediction is that it will be pretty much universally adopted. It may take a couple years and will involve some bitching an moaning, but it's pretty much an identity that open-source + Usenet == bitching and moaning Some of us will always find something to complain about... -- Grant Edwards grante Yow! I hope I bought the at right relish ... z visi.com... -- http://mail.python.org/mailman/listinfo/python-list
Re: Automatically restarting system calls?
On Jun 13, 10:41 am, Dan Stromberg <[EMAIL PROTECTED]> wrote: > I wrote a script(1) replacement in python (http://stromberg.dnsalias.org/ > ~dstromberg/pypty/), but I'm encountering a problem in it. > > I think I know the solution to the problem, but I'd've thought python was > high level enough that this solution isn't required, so I wanted to > inquire about it here. > > Specifically, the program has a signal handler for window size changes. > And if the window is resized during an os.write() (for example), I get a > python exception about needing to restart the system call. > > In C, I know you're supposed to wrap your system calls with while loops > until you don't get an ERESTART, but does one really need to wrap all of > one's os.write()'s (for example) with such while loops in python? Unfortunately, signals are sometimes used to intentionally interrupt system calls, so we can't always loop on ERESTART. However, os.write() is a low level API. Maybe file.write() or socket.send() would be a little more robust? -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to create a timer
On Jun 12, 11:42 pm, Alexnb <[EMAIL PROTECTED]> wrote: > I am wondering what is the best way to create a timer, like an alarm, once it > reaches a time, it triggers an event. I have a way of doing this but it > seems like it isn't good at all. If it helps at all I am using a Tkinter, > but that probably doesn't mean much. The way I was doing it was using a > while loop, and just saying while current time is not = to trigger time, do > nothing, and when it is, do event. Tkinter makes a big difference here. Like most (all?) event loops, it provides a way to call a function after a specified amount of time. Here's two pages I found: http://mail.python.org/pipermail/python-list/2001-August/101233.html http://www.astro.washington.edu/owen/TkinterSummary.html#After Note that it only fires once. If you want it to fire again you're callback will have to setup another timer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Making HEAD/PUT/DELETE requests with urllib2?
Phillip B Oldham schrieb: Thanks for the info. That's working like a charm. Looks as though I'll be able to handle all request types with that object. I got a little worried then that the python dev's had missed something truly important! I've done that in urrlib2 like this: class MyRequest(urllib2.Request): def get_method(self): if alternate_http_method is not None: return alternate_http_method return urllib2.Request.get_method(self) THe alternate_http_method is part of a class-closure, but of course you could do that with an instance variable as well. I then use it like this: req = MyRequest() handlers = [] if USE_PROXY: handlers.append(urllib2.ProxyHandler({'http' : PROXY})) req = self._create_request(url, connector, urlparams, queryparams, alternate_http_method) opener = urllib2.build_opener(*handlers) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Platform independent code?
On Jun 14, 6:28 am, "saneman" <[EMAIL PROTECTED]> wrote: > I have read that Python is a platform independent language. But on this > page: > > http://docs.python.org/tut/node4.html#SECTION00422 > > it seems that making a python script executable is platform dependant: > > 2.2.2 Executable Python Scripts > On BSD'ish Unix systems, Python scripts can be made directly executable, > like shell scripts, by putting the line > > #! /usr/bin/env python > (assuming that the interpreter is on the user's PATH) at the beginning of > the script and giving the file an executable mode. The "#!" must be the > first two characters of the file. On some platforms, this first line must > end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows > ("\r\n") line ending. Note that the hash, or pound, character, "#", is used > to start a comment in Python. > > The script can be given an executable mode, or permission, using the chmod > command: > > $ chmod +x myscript.py > > Are there any guidelines (API'S) that gurantees that the python code will be > platform independent? The only guarantee is testing it on both yourself. Some modules are inherently os-dependant (much of the 'os' module for example), and some constructs just don't work on all platforms (using os.environ['LOGNAME'] or system('cat file') as examples). If you stick to python code that doesn't touch the OS directly, you won't (read: shouldn't) have a problem, but when you start interacting with the OS directly you have to think hard about what you're doing. --Buck -- http://mail.python.org/mailman/listinfo/python-list
Python + RDBM framework?
It seems that whenever I have an application that uses a database (MySQL) I end up writing a database framework from scratch. Is there some accepted pre-existing project that has done this? I see Django, but that seems to have a lot of web-framework that I don't (necessarily) need. I just want to have my objects go in and out of the database in a consistent manner without writing a ton of code. Can you just use the database part without making a full-blow web app? I see Zope, but that doesn't use MySQL (as far as I can tell), which I've invested a lot of time learning to use and optimize. Also, my manager wants to be able to log into a MySQL prompt and be able to look at the data. --Buck -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
Andrea Gavana schrieb: Hi Diez & All, And on a personal note: I find it *buttugly*. Do you mind explaining "why" you find it *buttugly*? I am asking just out of curiosity, obviously. I am so biased towards wxPython that I won't make any comment on this thread in particular, but I am curious to know why some people find it "ugly" or "bad" or whatever. It has its own bugs and missing features, of course, but it is one of the major GUI player in the arena, together with PyQt and PyGTK. For the curious: Not the look & feel (albeit I prefer KDE on linux over Gnome, which is a Qt/GTK thing and thus affects wx look & feel as well), but the code & the designers. I've been spoiled by Qt and Apple Interface Builder I guess. But as I said: that's a personal opinion, and I'm well aware of the limitations of Qt (licensing and costs) and of course IB (OSX only) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Was the move to Python 2.0 as big a deal?
On Jun 14, 9:35 am, John Salerno <[EMAIL PROTECTED]> wrote: > Just curious if people put up any resistance to 2.0 like some people do > for 3.0. Was it as big of a change in the language, or was the > transition smoother? It seems silly for anyone to say they would prefer > to stick with 1.x versions at this point, so perhaps we'll get there > with 3.0 eventually too. > > Anyway, I'm just trying to figure out if the whole "I don't like 3.0" > mentality (of some people, not all of course) is merely a result of it > still being new and not even released yet, and will completely go away > after a year or two; or if there really are such drastic changes that > people won't want to adopt it at all. A lot of the bigger changes and warts that have emerged in the past decade or so of the 2.0 series (text encoding madness anyone?) have been tabled until the 3.0 transition, so any compatibility breaks for the sake of fixing inconsistencies and ugliness in Python have been accruing and are finally being applied in 3.0. The 1.5->2.0 transition was a little strange, but I think a large reason that it was less painful was because the language was younger, less established and had far fewer people programming in it (and correspondingly smaller codebases) to transition over. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + RDBM framework?
bukzor wrote: It seems that whenever I have an application that uses a database (MySQL) I end up writing a database framework from scratch. Is there some accepted pre-existing project that has done this? I see Django, but that seems to have a lot of web-framework that I don't (necessarily) need. I just want to have my objects go in and out of the database in a consistent manner without writing a ton of code. Can you just use the database part without making a full-blow web app? I see Zope, but that doesn't use MySQL (as far as I can tell), which I've invested a lot of time learning to use and optimize. Also, my manager wants to be able to log into a MySQL prompt and be able to look at the data. --Buck Zope definitely has MySQL interface, but if you think Django is a lot then Zope is even more. If I'm understanding your correctly what you want is ORM/ These links should help: http://pythonnotes.blogspot.com/2004/09/python-orm-tools.html http://www.sqlalchemy.org/ http://www.sqlobject.org/ -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing list, what special methods do this?
On Jun 13, 8:43 pm, Matimus <[EMAIL PROTECTED]> wrote: ...chop... > So, it looks like as long as you want to subclass list, you are stuck > implementing both __*slice__ and __*item__ methods. > > Matt Thanks. That was clear and concise, just what I needed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + RDBM framework?
On Jun 14, 10:43 am, Larry Bates <[EMAIL PROTECTED]> wrote: > bukzor wrote: > > It seems that whenever I have an application that uses a database > > (MySQL) I end up writing a database framework from scratch. Is there > > some accepted pre-existing project that has done this? > > > I see Django, but that seems to have a lot of web-framework that I > > don't (necessarily) need. I just want to have my objects go in and out > > of the database in a consistent manner without writing a ton of code. > > Can you just use the database part without making a full-blow web app? > > > I see Zope, but that doesn't use MySQL (as far as I can tell), which > > I've invested a lot of time learning to use and optimize. Also, my > > manager wants to be able to log into a MySQL prompt and be able to > > look at the data. > > > --Buck > > Zope definitely has MySQL interface, but if you think Django is a lot then > Zope > is even more. If I'm understanding your correctly what you want is ORM/ > These > links should help: > > http://pythonnotes.blogspot.com/2004/09/python-orm-tools.htmlhttp://www.sqlalchemy.org/http://www.sqlobject.org/ > > -Larry Both of those would work. I have a lot of data-integrity checks to make that would be impossible at the MySQL level and hard at the python/MySQLdb level. This will help a lot. I'll probably use the SQLAlchemy. Thanks so much! --Buck -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing list, what special methods do this?
"Matimus" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | So, it looks like as long as you want to subclass list, you are stuck | implementing both __*slice__ and __*item__ methods. Unless writing in 3.0, where they have finally disappeared. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
John Salerno wrote: if the program I write actually works and allows the two computers to speak to each other, will that be a result purely of the program, or will it have anything to do with the fact that they are already on a home network together? Here are the two programs. Server first, then client. They work, which in itself amazes me that it's so simple to create a network connection like this! But my basic question is this: would this connection work if the two computers (each running one of these scripts) were completely unrelated to one another? My two are on a home network, but if I were to run the server program and have a friend of mine (who lives somewhere else) run the client program, would it still work? - #!/usr/bin/env python from socket import * from time import ctime HOST = '192.168.1.100' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: print 'waiting for connection...' tcpCliSock, addr = tcpSerSock.accept() print '...connected from:', addr while True: data = tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s] %s' % (ctime(), data)) tcpCliSock.close() tcpSerSock.close() - - #!/usr/bin/env python from socket import * HOST = '192.168.1.100' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = raw_input('> ') if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data tcpCliSock.close() - -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing list, what special methods do this?
On Jun 13, 1:38 pm, Mike Kent <[EMAIL PROTECTED]> wrote: > For Python 2.5 and new-style classes, what special method is called > for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a > list, and seq is some sequence)? > > I'm trying to subclass list, and I'm having trouble determining what > special methods I have to override in my class for the above two > operations. From my testing, it seems to be __setslice__ for both, > but the docs say __setslice__ and brethren are deprecated. I would > have thought that __setitem__ and __delitem__ would be what was > called, but again, my testing says otherwise. Or you could forget this "subclassing" stuff, and just implement __setitem__, __getitem__, __delitem__, __len__, and __iter__ in your own class, and not worry about what list does or doesn't do. You could have your class contain a list to implement with, and then delegate to it from your class's code. Overall, I think Python as a language favors composition/delegation over inheritance - c/d is so easy to do with __getattribute__, and inheritance is largely unnecessary since type/interface is not checked until runtime. Yet many O-O texts are written around C++ and Java's static type models, so we see a preponderance of patterns and conventional O-O wisdom recommending inheritance. For Python, it ain't necessarily so... -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy: handling float('NaN') different in XP vs. Linux
"Christian Heimes" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] || I've fixed the issue for Python 2.6 and 3.0 a while ago. Mark and I have | spent a lot of time on fixing several edge cases regarding inf, nan and | numerical unsound functions in Python's math und cmath module. I just tested 'NaN' on XP. Works. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
John Salerno wrote: - #!/usr/bin/env python from socket import * from time import ctime HOST = '192.168.1.100' - #!/usr/bin/env python from socket import * HOST = '192.168.1.100' A question about this. Is the "HOST" referring to the IP address of the server computer in both of these cases? Because when I ran the program and got to the part where it says "connected from:" on the server side, it shows this same IP address. Shouldn't it be something different, since the requests are coming from a different computer than the server computer? -- http://mail.python.org/mailman/listinfo/python-list
Re: Was the move to Python 2.0 as big a deal?
"John Salerno" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | Just curious if people put up any resistance to 2.0 like some people do | for 3.0. Was it as big of a change in the language, or was the | transition smoother? 2.0 (from BeOpen) was essentially 1.6 (final CNRI version) rebranded. A bigger change was 2.2 which introduced new-style classes, the new iterator protocol, and generators. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On Sat, Jun 14, 2008 at 11:54 AM, John Salerno <[EMAIL PROTECTED]> wrote: > John Salerno wrote: > > - >> #!/usr/bin/env python >> >> from socket import * >> from time import ctime >> >> HOST = '192.168.1.100' >> > > > - >> #!/usr/bin/env python >> >> from socket import * >> >> HOST = '192.168.1.100' >> > > A question about this. Is the "HOST" referring to the IP address of the > server computer in both of these cases? Because when I ran the program and > got to the part where it says "connected from:" on the server side, it shows > this same IP address. Shouldn't it be something different, since the > requests are coming from a different computer than the server computer? > > -- > http://mail.python.org/mailman/listinfo/python-list > John, It looks to me as if you're running both client and server on the same box, and in effect conecting to yourself. You asked in an earlier message if a friend on a different network could connect to you using your client programme and that depends on a LOT of things. Your friend certainly wouldn't be able to using the 192.168.x.x address as that is an unroutable address. But you would likely have a bit of work to do to get it to work through you and your friend's firewalls (that is likely a conversation for a later time though. -- Stand Fast, tjg. -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
On 2008-06-14, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: >>> And on a personal note: I find it *buttugly*. >> >> Do you mind explaining "why" you find it *buttugly*? [...] > For the curious: Not the look & feel (albeit I prefer KDE on > linux over Gnome, which is a Qt/GTK thing and thus affects wx > look & feel as well), but the code & the designers. I've never used any of the designers, but I agree 100% that wxPython code is nasty ugly. wxPython has a very un-Pythonic API that's is, IMO, difficult to use. The API isn't really Robin Dunn's fault: wxPython is a very thin wrapper around wxWidgets, so it largely retains the same nasty low-level C++ API that wxWidgets has. I presume much of wxPython is generated in some automated fasion (a la swing). There have been a couple attempts to wrap wxPython in a cleaner, more Pythonic API, but they've have limited success (wax is the one I can think of off the top of my head). -- Grant Edwards grante Yow! If I had a Q-TIP, I at could prevent th' collapse visi.comof NEGOTIATIONS!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-14, John Salerno <[EMAIL PROTECTED]> wrote: > John Salerno wrote: >> if the program I write actually works and allows the two >> computers to speak to each other, will that be a result purely of the >> program, or will it have anything to do with the fact that they are >> already on a home network together? > > Here are the two programs. Server first, then client. They work, which > in itself amazes me that it's so simple to create a network connection > like this! But my basic question is this: would this connection work if > the two computers (each running one of these scripts) were completely > unrelated to one another? That depends on your definition of "unrelated." > My two are on a home network, but if I were to run the server > program and have a friend of mine (who lives somewhere else) > run the client program, would it still work? Yes, if the routers/firewalls/PCs were set up properly and if you changed the IP addresses in the programs appropriately. -- Grant Edwards grante Yow! I want the presidency at so bad I can already taste visi.comthe hors d'oeuvres. -- http://mail.python.org/mailman/listinfo/python-list
Configuration files
What is the most Pythonic way to maintain a configuration file? Are there any libraries mimicking registry / ini file writing that many windows programming languages/environments offer? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-14, John Salerno <[EMAIL PROTECTED]> wrote: > John Salerno wrote: > >> - >> #!/usr/bin/env python >> >> from socket import * >> from time import ctime >> >> HOST = '192.168.1.100' > > >> - >> #!/usr/bin/env python >> >> from socket import * >> >> HOST = '192.168.1.100' > > A question about this. Is the "HOST" referring to the IP > address of the server computer in both of these cases? Yes. > Because when I ran the program and got to the part where it > says "connected from:" on the server side, it shows this same > IP address. Then you must have been either running the client program on the same machine as the server program or you've got some sort of NAT/port-forwarding going on. > Shouldn't it be something different, since the requests are > coming from a different computer than the server computer? Works fine for me. When I run the client program on a machine different than the server program, the server program prints out "connected from:" and then the client machine's IP address. -- Grant Edwards grante Yow! Maybe I should have at asked for my Neutron Bomb visi.comin PAISLEY -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
Hallöchen! Grant Edwards writes: > On 2008-06-14, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: > And on a personal note: I find it *buttugly*. >>> >>> Do you mind explaining "why" you find it *buttugly*? > > [...] > >> For the curious: Not the look & feel (albeit I prefer KDE on >> linux over Gnome, which is a Qt/GTK thing and thus affects wx >> look & feel as well), but the code & the designers. > > I've never used any of the designers, but I agree 100% that > wxPython code is nasty ugly. wxPython has a very un-Pythonic API > that's is, IMO, difficult to use. I know that such requests may start a never-ending thread but I'd really like to know what you mean with this. I had almost no GUI experience when I started to use wxPython, yet it was a pleasure for me. Really, aesthetics of the source is important to me being a hobby programmer, and I don't like wxPython's camel case and getters and setters. However, even many (if not most) core Python modules don't respect PEP8 or don't use current language features. Besides, passing function names as strings is also a wart, and *I* have simply never understood signal and slots. Maybe we should accept that there is no silver bullet in GUI toolkits, and any personal preferences amongst the Big Four are just a matter of taste. This "un-Pythonic" thing is arbitrary and unfair wording in my opinion. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Hard to understand 'eval'
On 14 juin, 10:31, TheSaint <[EMAIL PROTECTED]> wrote: > Hi, > > It seems to be strange that give me syntax error inside an eval statement. > I'm looking at it carefully but I can't see any flaw. > > Here it's part of the code: > > for nn in stn_items: > value= eval('cp.%s' %nn) Hem... Not obvious from this snippet, but what's wrong with getattr(cp, nn) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Configuration files
> What is the most Pythonic way to maintain a configuration file? > Are there any libraries mimicking registry / ini file writing that many > windows programming languages/environments offer? Check this out: http://www.voidspace.org.uk/python/configobj.html Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
Grant Edwards wrote: Shouldn't it be something different, since the requests are coming from a different computer than the server computer? Works fine for me. When I run the client program on a machine different than the server program, the server program prints out "connected from:" and then the client machine's IP address. Hmm, so could the reason that the client request is shown to be coming from the same IP address as the server machine be that they are on the same home network? I guess to truly test my question, I need to have two computers that are completely "unrelated" to one another -- meaning they are in no way connected via any type of network prior to running these scripts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
Grant Edwards wrote: That depends on your definition of "unrelated." Heh heh, you mean that wasn't specific enough!? :) I just mean completely unconnected in any possible way, network or otherwise. My two are on a home network, but if I were to run the server program and have a friend of mine (who lives somewhere else) run the client program, would it still work? Yes, if the routers/firewalls/PCs were set up properly and if you changed the IP addresses in the programs appropriately. Ok, that's basically what I was curious about. Since my two computers are already on a network, I couldn't be positive that this wasn't allowing them to connect, rather than the two client/server scripts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comments on my first script?
On 13 juin, 13:39, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote: > On Fri, 13 Jun 2008 10:19:38 +0200 > > Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > > Ok, since you asked for it, let's go: > > Good commentary. One small improvement: > > > REC_CLEANERS = { > > '.net' : clean_net, > > '.com' : clean_com, > > '.tv' : clean_net, > > '.uk' : clean_co_uk, > > (etc...) > > } FWIW, the keys should not start with a '.'. My fault... > > for domain in rec: > > # code here > > ext = domain.rsplit('.', 1)[1] > > cleaner = REC_CLEANERS.get(ext, None) > > if cleaner: > > rec = cleaner(rec) > > How about this? > > for domain in rec: > # code here > ext = domain.rsplit('.', 1)[1] > rec = REC_CLEANERS.get(ext, lambda x: x) Depends on if you want to know if there's a match or if you just don't care. > I suppose you could predefine the default function as well. Yeps. That's usually what I do when I end up using the above variant more than once in a module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comments on my first script?
On 13 juin, 17:24, Lie <[EMAIL PROTECTED]> wrote: > On Jun 13, 3:19 pm, Bruno Desthuilliers [EMAIL PROTECTED]> wrote: > > Phillip B Oldham a écrit : > (snip) > > >try: > > >for line in rec.split("\n"): > > >bits = line.split(': ') > > >a = bits.pop(0) > > >b = bits.pop(0) > > > if you expect only one ': ', then: > > a, b = line.split(': ') > > > if you can have many but don't care about the others: > > bits = line.split(': ') > > a, b = bits[0], bits[1] > > or: > a, b = line.split(': ')[:1] > ValueError: need more than 1 value to unpack You probably meant: a, b = line.split(': ')[:2] -- http://mail.python.org/mailman/listinfo/python-list
XML validation in stdlib?
Hi! I took a look at the standard library and tried to find some validation against schema tools, but found none. I googled, but found only links to external libraries, that can do some validation. Does it mean, that there is no validation in stdlib or have I just missed something? -- Filip Gruszczyński -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
On 2008-06-14, Torsten Bronger <[EMAIL PROTECTED]> wrote: >> I've never used any of the designers, but I agree 100% that >> wxPython code is nasty ugly. wxPython has a very un-Pythonic >> API that's is, IMO, difficult to use. > > I know that such requests may start a never-ending thread but > I'd really like to know what you mean with this. [...] Well, if we want this thread to be never ending, I'd better put a little dramatic hyperbole into my answer, so here goes... ;) IMO, a few of the "un-Pythonic" things about wxPython are: 1) Window ID numbers. "You don't need to know what it's for, just pass a -1." Their very existence at the user level feels wrong. I'm told that for approximately 3 uber-sophisticated wxWidgets programmers window IDs can be useful in some rare situations. Meanwhile everybody else working under "normal" conditions has to pass a useless positional parameter every time they instantiate a widget. Things that are useful only in exceptional situations should only be visible in exception situations. 2) the "flags" parameter. "1975 called, and they want their bit-masks back." The mashing together of a several dozen different, completely unrelated attributes into the "flags" parameter is a trick left over from C/assembly language programming on machines who's memory size was measure in KB. Rather than OR-ing together a bunch of bit-patterns to make the window act the way you want, you should be setting individually named object attributes or passing optional, named parameters to the class method. 3) the parent/child tree "the only thing less well understood than Window IDs" I've been writing wxPython apps for about 9 years now, and I still have only a very vague idea what the parent/child tree is for. Everybody I know just makes everything the child of the first panel they put in the application frame. The same people who specify Window IDs other than -1 probably use complex parent/child trees for something. 4) sizers "they're like aspirin -- they work, but nobody knows exactly how" OK, that's a bit out-of-date since I seem to recall that somebody did finally figure out how aspirin works a couple years back. The way sizers work seems pretty complex compared to other GUI toolkits I've used, and the extra complexity doesn't seem to provide any extra capability. The one thing that seems to me to be particular complicated is controlling which objects "stretch" in what axis when a window is resized. I've been using them for many years, but I've never gotten them more than about 90% figured out. Every time I write a wxPython apps, I'm initially surprised at its behavior when the window is resized and have to spend some trial-and-error time fiddling with the sizer parameters. I don't remember having to do that in tkInter or in Trestle: things "just worked". 5) binding "What? you wanted a button that _did_ something when you clicked it?" Binding has actually improved a bit in the past few years. It's not as obscure as it used to be, but it's still an extra explicit step that shouldn't be required. It should only take one line of code to create a button widget that calls a specified callable when it's clicked. Something like this: b = wx.Button(label="Click Me", action=myCallable) Instead you used to have to create a button and then call some utility function in some other object to bind that button to a callable (IIRC this was one place where Window IDs could be used). Now, the button actually has a method you can use. It's still an extra step... 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS "After all, everything is really just a base-2 integer." Since we don't have objects or attributes or named parameters or strings, all information must be passed into and out of the library as arbitrary integers constants. The really great thing about that sort of API is it's versatility: you can pass any value any where! Pass a width in pixels where a bitmask of window attributes is expected? No problem! Well, the build I was running has finished, so that's probably enough... -- Grant Edwards grante Yow! Those people look at exactly like Donnie and visi.comMarie Osmond!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-14, John Salerno <[EMAIL PROTECTED]> wrote: > Grant Edwards wrote: > >>> Shouldn't it be something different, since the requests are >>> coming from a different computer than the server computer? >> >> Works fine for me. When I run the client program on a machine >> different than the server program, the server program prints >> out "connected from:" and then the client machine's IP address. > > Hmm, so could the reason that the client request is shown to be coming > from the same IP address as the server machine be that they are on the > same home network? No, not for the usual value of "on the same home network". I've no idea how your home network is set up, so that's about all I can say. > I guess to truly test my question, I need to have two > computers that are completely "unrelated" to one another -- > meaning they are in no way connected via any type of network > prior to running these scripts. If the two computers are in no way connected via any type of network, then the two programs won't be able to talk to each other. The programs can't create a network, they can only use one that already exists. -- Grant Edwards grante Yow! I've got an IDEA!! at Why don't I STARE at you visi.comso HARD, you forget your SOCIAL SECURITY NUMBER!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-14, John Salerno <[EMAIL PROTECTED]> wrote: > Grant Edwards wrote: > >> That depends on your definition of "unrelated." > > Heh heh, you mean that wasn't specific enough!? :) > > I just mean completely unconnected in any possible way, network or > otherwise. If they're completely unconnected in any possible way, then I take that to mean that any communication between the two computers is impossible. -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Summing a 2D list
On Jun 14, 4:05 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > On Jun 12, 3:48 pm, Mark <[EMAIL PROTECTED]> wrote: > > > Is this possible? > > def foobar(user,score): >sums = {} >for u,s in zip(user,score): > try: > sums[u] += s > except KeyError: > sums[u] = s >return [(u, sums[u]) for u in sums].sort() > sort() sorts the list in-place and returns None. Try this instead: return sorted([(u, sums[u]) for u in sums]) or, better yet: return sorted(sums.items()) > usersum = foobar(user,score) > for u,s in usersum: > print "%d %d" % (u,s) -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
Hallöchen! Grant Edwards writes: > [...] > > IMO, a few of the "un-Pythonic" things about wxPython are: > > 1) Window ID numbers. When I started to use wxPython, there was a newly-introduced wx.ID_ANY that you could give instead of -1. My eyes filtered it out after a couple of hours, just as they do with "self". > [...] > > 2) the "flags" parameter. Well, I like flags, and I don't see that they are unpythonic. I find the code they produce very legible. > [...] > > 3) the parent/child tree See wx.ID_ANY. > [...] > > 4) sizers Maybe because I come from TeX/LaTeX, i liked sizers immediately. They worked well for me. > [...] > > 5) binding > > "What? you wanted a button that _did_ something when you > clicked it?" You're right, this can be better. There's too much explicitness. However, if you really hate the construct, you can define a shortcut. > [...] > > 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS Thank you for the thorough explanations but in my opinion your points are minor. Additionally, most of them are a matter of taste. I don't think that because you didn't find sizers convenient, or some parts too explicit, you can say that wxWidgets is un-Pythonic. I rather have the impression that you like terseness, which is totally okay but a different thing. I agree that changing the naming conventions and making use of properties would increase pythonicness, but on an already high level. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Avoiding redirects with urllib
Hi, I'musing urllib to download pages from a site. How can I detect if a given url is being redirected somewhere else? I want to avoid this, is it possible? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a file
On Jun 14, 12:00 pm, jim-on-linux <[EMAIL PROTECTED]> wrote: > On Saturday 14 June 2008 03:15, Beema > > shafreen wrote: > > Hi all, > > > I have a file with three columns i need > > to sort the file with respect to the third > > column. How do I do it uisng python. I > > used Linux command to do this. Sort but i > > not able to do it ? can any body ssuggest > > me > > I have used this method to solve similar > problems. > > This is a consept of how to do what you want, > but you will have to work a little to get it > right. > > You might try something like this; > > Dict = {} ##create a dictionary > > make a list of all column3 values > > for loop colum3 values > > Make these values the key in a dictionary > If the values are long, you can use the first > 7 to 15 characters if you want. > > use this key to equal all the values in the > other columns on the same row. > > Dict[column3] = column1, column2, column3 > > once the dictionary is made > > get the dictionary key > x = Dict.keys() ## get the keys from Dict > > x.sort() # produce a sorted list of keys of > column3 > > Loop these sorted keys to extract from the > dictionary the values related to each > > jim-on-linux > http://:inqvista.com Here's another way to attack it. Make a class that takes your columns as arguments. define an operator on that class to get the comparison you want. make a list that is your rows, and call sort. here's an example using only two columns class twoColumns : def __init__(self, c1 = 0, c2 = 0) : self.c1 = c1 self.c2 = c2 #just use this for debugging if you want to see everything def getVals(self): print self.c1, self.c2 #order members of this class by the second column def __lt__(c,d): if (c.c2 < d.c2) : return 1 else : return 0 #end class definition Here's what happened when I used this class. >>> r1 = twoColumns(3,4) >>> r2 = twoColumns(1,5) >>> test = [r1,r2] #this is already sorted >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 >>> test.sort() #and the sort looks the same >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 >>> test = [r2,r1] #I reversed the rows >>> test[0].getVals() 1 5 >>> test[1].getVals() 3 4 >>> test.sort() #and we get what we want >>> test[0].getVals() 3 4 >>> test[1].getVals() 1 5 I think that does what you're asking. -- http://mail.python.org/mailman/listinfo/python-list
Socket Programming
Hi, Is there any way(method) to find whether the socket got closed or not?? Thanks, Srini Best Jokes, Best Friends, Best Food and more. Go to http://in.promos.yahoo.com/groups/bestofyahoo/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
Grant Edwards wrote: On 2008-06-14, Torsten Bronger <[EMAIL PROTECTED]> wrote: I've never used any of the designers, but I agree 100% that wxPython code is nasty ugly. wxPython has a very un-Pythonic API that's is, IMO, difficult to use. I know that such requests may start a never-ending thread but I'd really like to know what you mean with this. [...] Well, if we want this thread to be never ending, I'd better put a little dramatic hyperbole into my answer, so here goes... ;) (blatant self-promotion warning: I'm one of the founders of Dabo, and it sounds like you may like to take a look at it, given your comments below) IMO, a few of the "un-Pythonic" things about wxPython are: 1) Window ID numbers. "You don't need to know what it's for, just pass a -1." Their very existence at the user level feels wrong. I'm told that for approximately 3 uber-sophisticated wxWidgets programmers window IDs can be useful in some rare situations. Meanwhile everybody else working under "normal" conditions has to pass a useless positional parameter every time they instantiate a widget. Things that are useful only in exceptional situations should only be visible in exception situations. Dabo is a nice wrapper around wxPython, which among other things does away with id numbers. There are a few places (wxMenu events, for one) where you need to deal with window id's, but Dabo doesn't expose the user to that, it handles it the way it should work. 2) the "flags" parameter. "1975 called, and they want their bit-masks back." The mashing together of a several dozen different, completely unrelated attributes into the "flags" parameter is a trick left over from C/assembly language programming on machines who's memory size was measure in KB. Rather than OR-ing together a bunch of bit-patterns to make the window act the way you want, you should be setting individually named object attributes or passing optional, named parameters to the class method. Dabo uses properties for everything, including the individual style bits. And it handles making the setting in the right place so it "just works" without the user needing to know, for instance, that flag x only works after the class is fully instantiated, or vice-versa. Properties can be set on the object once instantiated, sent to the constructor, or set in a subclass: # create a textbox by instantiating the baseclass # and sending property values to the constructor: txt = dabo.ui.dTextBox(self, Value="Hello", FontBold=True) # tweak some other properties: txt.FontItalic = True txt.BackColor = "yellow" 3) the parent/child tree "the only thing less well understood than Window IDs" I've been writing wxPython apps for about 9 years now, and I still have only a very vague idea what the parent/child tree is for. Everybody I know just makes everything the child of the first panel they put in the application frame. The same people who specify Window IDs other than -1 probably use complex parent/child trees for something. Every container object needs to know about its children, and every object needs to know about its parent. So, in Dabo we have 2 properties: Children and Parent. 4) sizers "they're like aspirin -- they work, but nobody knows exactly how" OK, that's a bit out-of-date since I seem to recall that somebody did finally figure out how aspirin works a couple years back. The way sizers work seems pretty complex compared to other GUI toolkits I've used, and the extra complexity doesn't seem to provide any extra capability. The one thing that seems to me to be particular complicated is controlling which objects "stretch" in what axis when a window is resized. I've been using them for many years, but I've never gotten them more than about 90% figured out. Every time I write a wxPython apps, I'm initially surprised at its behavior when the window is resized and have to spend some trial-and-error time fiddling with the sizer parameters. I don't remember having to do that in tkInter or in Trestle: things "just worked". Sizers are admittedly a bit complex in Dabo, too. Or, sizers aren't complex, but the code that creates them gets pretty wordy pretty fast. vs = dabo.ui.dSizer("v") hs = dabo.ui.dSizer("h") hs.append(dabo.ui.dLabel(self, Caption="Name:")) hs.append(dabo.ui.dTextBox(self)) vs.append(hs) 5) binding "What? you wanted a button that _did_ something when you clicked it?" Binding has actually improved a bit in the past few years. It's not as obscure as it used to be, but it's still an extra explicit step that shouldn't be required. It should only take one line of code to create a button widget that calls a specified callable when it's clicked. Something like this: b = wx.Button(label="Click Me", action=myCallable) In
Re: Making wxPython a standard module?
On 2008-06-14, Paul McNett <[EMAIL PROTECTED]> wrote: > Grant Edwards wrote: >> On 2008-06-14, Torsten Bronger <[EMAIL PROTECTED]> wrote: >> I've never used any of the designers, but I agree 100% that wxPython code is nasty ugly. wxPython has a very un-Pythonic API that's is, IMO, difficult to use. >>> I know that such requests may start a never-ending thread but >>> I'd really like to know what you mean with this. >> >> [...] >> >> Well, if we want this thread to be never ending, I'd better put >> a little dramatic hyperbole into my answer, so here goes... ;) > > (blatant self-promotion warning: I'm one of the founders of Dabo, and it > sounds like you may like to take a look at it, given your comments below) Yes! Dabo was the other one I was trying to remember. The last time I looked Dabo appeared to be catching on better than wax was. > But in the end, wxPython is the best GUI toolkit for Python, > by far, I've been using it for 9 years. :) I can pretty much always make it work, and the result looks native to Windows users and "native enough" to Linux users... -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
os.walk Value Error?
Hi, I'm using os.walk as follows: (basedir, pathnames, files) = os.walk("results", topdown=True) and I'm getting the error: ValueError: too many values to unpack >From my googling, that means: This is the standard message when Python tries to unpack a tuple into fewer variables than are in the tuple. >From what I can see of the examples on the python site, I'm using it correctly. I have commas in my original code, and the "results" directory exists and is directly under the directory from which my script is run. I'm assuming that 12 files (the number of files in the "results" directory) is not too many for Python to handle! ;-) Is there any other reason I might get that error? -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
On 2008-06-14, Torsten Bronger <[EMAIL PROTECTED]> wrote: >> [...] >> >> IMO, a few of the "un-Pythonic" things about wxPython are: >> >> 1) Window ID numbers. > > When I started to use wxPython, there was a newly-introduced > wx.ID_ANY that you could give instead of -1. My eyes filtered > it out after a couple of hours, just as they do with "self". Defining a new name for -1 is just painting the wart a different color. >> [...] >> >> 2) the "flags" parameter. > > Well, I like flags, and I don't see that they are unpythonic. I > find the code they produce very legible. You're saying that having the user or-together a bunch of bitmasks and pass the result as an integer is a common way for Python functions/object allow the user to turn optional features on and off? You must be using a different Python than I am. What I see used for that in the standard library modules are either named parameters with useful default values or individual object attributes. The only exceptions I can think are low level routines in the "os" and "socket" modules that allow direct access to things like Unix libc calls like open(), creat(), read(), write() and to the BSD sockets API. >> [...] >> >> 3) the parent/child tree > > See wx.ID_ANY. I don't see what the two have to do with each other, but maybe that's the root of all my problems. >> [...] >> >> 4) sizers > > Maybe because I come from TeX/LaTeX, i liked sizers > immediately. They worked well for me. I came from TeX/LaTeX also, and before wx, I spent a little time using Trestle GUI widgets which follow the TeX box-and-glue paradigm almost exactly. I guess I don't find wx sizers work much like TeX/LaTeX boxes. >> [...] >> >> 5) binding >> >> "What? you wanted a button that _did_ something when you >> clicked it?" > > You're right, this can be better. There's too much explicitness. > However, if you really hate the construct, you can define a > shortcut. I do. I sub-class wx.Button. Users should have to do that to get basic functionality that's required in 99.999% of the widget's use cases. Explicit is fine if it serves a purpose. I don't see the purpose of requiring a second line of code to bind a button to a callable. >> [...] >> >> 6) Thousands of wx.UPPER_CASE_INTEGER_HEX_CONSTANTS > > Thank you for the thorough explanations but in my opinion your > points are minor. They're minor in that they don't prevent you from writing programs that work, but they're not minor in that they unnecessarily increase the workload of the user without providing any benefit. They are sources of bugs. > Additionally, most of them are a matter of taste. I don't > think that because you didn't find sizers convenient, or some > parts too explicit, you can say that wxWidgets is un-Pythonic. Maybe a couple are just bad design decisions that weren't well thought out rather than being "un-Pythonic". OTOH, I consider that being well thoght out and well designed is one of the characteristics of Python, so things that aren't are un-Pythonic. > I rather have the impression that you like terseness, which is > totally okay but a different thing. I think that the most common use cases should be handled with a minimum of "extra" stuff having to be done by the user. It's just not Pythonic to require a user to specify default values for x,y,z when non-default valus for x,y,z are only used in 1 case out of 1. In Python you use named parameters with default values. You don't use positional parameters and then tell the user "yes, I know this is useless almost all the time, so just pass a -1 if you want the default behavior. You shouldn't have to specifically ask for default behavior. You should only have to ask for non-default behavior. > I agree that changing the naming conventions and making use of > properties would increase pythonicness, but on an already high > level. I guess my views on what is "pythonic" are a lot different. I also don't think it's at all surprising that a C++ library like wxWidgets has an API that isn't very Pythonic. -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.comATLANTA, Georgia!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Avoiding redirects with urllib
On Jun 14, 5:22 pm, Fernando Rodriguez <[EMAIL PROTECTED]> wrote: > Hi, > > I'musing urllib to download pages from a site. How can I detect if a given > url is being redirected somewhere else? I want to avoid this, is it possible? > > Thanks in advance! Try this: import urllib url_opener = urllib.URLopener() # create URLopener #You could also work with urllib.FancyURLopener try: data = url_opener.open("http://www.somedomain.com/index.html";) # open index.html except IOError, error_code: if error_code[0] == "http error": if error_code[1] == 301: #do something here if error_code[2] == 302: #do something here I hope that's of some help! I think you may want to delve deeper into FancyURLopener... -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a file
On Jun 15, 2:00 am, jim-on-linux <[EMAIL PROTECTED]> wrote: > On Saturday 14 June 2008 03:15, Beema > > shafreen wrote: > > Hi all, > > > I have a file with three columns i need > > to sort the file with respect to the third > > column. How do I do it uisng python. I > > used Linux command to do this. Sort but i > > not able to do it ? can any body ssuggest > > me > > I have used this method to solve similar > problems. > > This is a consept of how to do what you want, > but you will have to work a little to get it > right. > > You might try something like this; > > Dict = {} ##create a dictionary > > make a list of all column3 values Ummm this appears somewhat baroque try this: Assuming the OP has arranged to read his data into a list of lists "filedata" such that filedata[-1][2] is the data in the 3rd column of the last row. Further assume that the data has just been read with e.g. the csv module so all data is still in text form and may need some conversion before comparison (otherwise e.g. a salary of 10 would appear before a salary of 9). Suppose the 3rd column is a salary, without '$' and ',' in it. Now let's look at the manual for the sort method. It gives us 2 options: a cmp function and a key function, with a strong hint that key is better. So for each row, what do we want on sort on? It's the numerical value of the 3rd item: def sort_key_func(row): return float(row[2]) Then we can simply do: filedata.sort(key=sort_key_func) All that remains is to write the contents of filedata to the output file. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Avoiding redirects with urllib
On Jun 14, 6:18 pm, [EMAIL PROTECTED] wrote: > On Jun 14, 5:22 pm, Fernando Rodriguez > > <[EMAIL PROTECTED]> wrote: > > Hi, > > > I'musing urllib to download pages from a site. How can I detect if a given > > url is being redirected somewhere else? I want to avoid this, is it > > possible? > > > Thanks in advance! > > Try this: > > import urllib > url_opener = urllib.URLopener() # create URLopener > #You could also work with urllib.FancyURLopener > > try: > data = url_opener.open("http://www.somedomain.com/index.html";) # > open index.html > except IOError, error_code: > if error_code[0] == "http error": > if error_code[1] == 301: > #do something here > if error_code[2] == 302: > #do something here > > I hope that's of some help! I think you may want to delve deeper into > FancyURLopener... That last part might better be: if error_code[1] == 301: #do something here elif error_code[1] == 302: #do something here -- http://mail.python.org/mailman/listinfo/python-list
Re: Python + RDBM framework?
bukzor wrote: > It seems that whenever I have an application that uses a database > (MySQL) I end up writing a database framework from scratch. Is there > some accepted pre-existing project that has done this? > > I see Django, but that seems to have a lot of web-framework that I > don't (necessarily) need. I just want to have my objects go in and out > of the database in a consistent manner without writing a ton of code. > Can you just use the database part without making a full-blow web app? > > I see Zope, but that doesn't use MySQL (as far as I can tell), which > I've invested a lot of time learning to use and optimize. Also, my > manager wants to be able to log into a MySQL prompt and be able to > look at the data. > > --Buck Not sure of your project but you might consider Dabo (www.dabodev.com). John -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk Value Error?
[EMAIL PROTECTED] wrote: Hi, I'm using os.walk as follows: (basedir, pathnames, files) = os.walk("results", topdown=True) and I'm getting the error: ValueError: too many values to unpack From my googling, that means: This is the standard message when Python tries to unpack a tuple into fewer variables than are in the tuple. From what I can see of the examples on the python site, I'm using it correctly. I have commas in my original code, and the "results" directory exists and is directly under the directory from which my script is run. I'm assuming that 12 files (the number of files in the "results" directory) is not too many for Python to handle! ;-) Is there any other reason I might get that error? os.walk is a generator so you need to make it a loop target: for basedir, pathnames, files in os.walk("results"): # # Do you work inside the loop # -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk Value Error?
[EMAIL PROTECTED] wrote: > Is there any other reason I might get that error? Yes, you are using it the wrong way. The correct way is for root, dirs, files in os.walk(path): do something os.walk returns an iterator which yields root, dirs and files for each iteration. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
Grant Edwards wrote: On 2008-06-14, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: And on a personal note: I find it *buttugly*. Do you mind explaining "why" you find it *buttugly*? [...] For the curious: Not the look & feel (albeit I prefer KDE on linux over Gnome, which is a Qt/GTK thing and thus affects wx look & feel as well), but the code & the designers. I've never used any of the designers, but I agree 100% that wxPython code is nasty ugly. wxPython has a very un-Pythonic API that's is, IMO, difficult to use. The API isn't really Robin Dunn's fault: wxPython is a very thin wrapper around wxWidgets, so it largely retains the same nasty low-level C++ API that wxWidgets has. I presume much of wxPython is generated in some automated fasion (a la swing). There have been a couple attempts to wrap wxPython in a cleaner, more Pythonic API, but they've have limited success (wax is the one I can think of off the top of my head). WAX doesn't seem to have been maintained since 2004. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk Value Error?
On Jun 14, 7:11 pm, Larry Bates <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi, > > > I'm using os.walk as follows: > > > (basedir, pathnames, files) = os.walk("results", topdown=True) > > > and I'm getting the error: > > > ValueError: too many values to unpack > > > From my googling, that means: > > > This is the standard message when Python tries to unpack a tuple > > into fewer variables than are in the tuple. > > > From what I can see of the examples on the python site, I'm using it > > correctly. I have commas in my original code, and the "results" > > directory exists and is directly under the directory from which my > > script is run. > > > I'm assuming that 12 files (the number of files in the "results" > > directory) is not too many for Python to handle! ;-) > > > Is there any other reason I might get that error? > > os.walk is a generator so you need to make it a loop target: > > for basedir, pathnames, files in os.walk("results"): > # > # Do you work inside the loop > # > > -Larry Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
Dennis Lee Bieber wrote: Is there any possibility you are confusing a Windows Workgroup or Domain in this... (Assuming anyone still runs such) Or other Windows convenience features to automatically detect computers in a local area network and display them in "network neighborhood". What I have is a desktop PC connected via ethernet cable to my cable modem. I also use a router and my laptop uses a wireless connection. This alone, of course, doesn't connect the computers, AFAIK. It's just an internet connection. What I did next was go to My Network Places > Set up a home or small office network, and follow the wizard through the steps that would allow me to share files and folders between the two computers. It's possible I'm using the wrong terminology when I say this is a "home network," because all it is is the two computers being able to access each other's hard drive. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
Grant Edwards wrote: If the two computers are in no way connected via any type of network, then the two programs won't be able to talk to each other. The programs can't create a network, they can only use one that already exists. But isn't that the point of the program, to create a network between the two computers? Isn't that what the host and port are used for, to open a connection? (Just to clarify, when I say "in no way connected", I don't mean not connected to the internet in general. I know they need access to the internet for any kind of networking program to work at all.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-15, John Salerno <[EMAIL PROTECTED]> wrote: >> Is there any possibility you are confusing a Windows Workgroup >> or Domain in this... (Assuming anyone still runs such) Or >> other Windows convenience features to automatically detect >> computers in a local area network and display them in "network >> neighborhood". > > What I have is a desktop PC connected via ethernet cable to my > cable modem. I also use a router and my laptop uses a wireless > connection. This alone, of course, doesn't connect the > computers, AFAIK. It's just an internet connection. That probably means that the computers are on a common subnet and can communicate with each other using normal IP routing. > What I did next was go to My Network Places > Set up a home or > small office network, and follow the wizard through the steps > that would allow me to share files and folders between the two > computers. It's possible I'm using the wrong terminology when > I say this is a "home network," because all it is is the two > computers being able to access each other's hard drive. "home network" is pretty much a meaningless term, so you can use it however you want. My guess is that all the "wizard" did was set up file and print sharing between two computers that were already on the same network and could already talk to each other. IOW, if both computers were able to access the internet via a single cable modem before you ran the wizard, then it's quite likely they could have communicated with each other as well (using the two python programs or any other network aware applications). -- Grant Edwards grante Yow! I'm ZIPPY!! Are we at having FUN yet?? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Socket Programming
On Jun 14, 5:38 pm, srinivasan srinivas <[EMAIL PROTECTED]> wrote: > Hi, > Is there any way(method) to find whether the socket got closed or not?? > Thanks, > Srini > > Best Jokes, Best Friends, Best Food and more. Go > tohttp://in.promos.yahoo.com/groups/bestofyahoo/ That's slightly difficult to answer without knowing any context. Do you want to know if the other end has closed the connection? Assuming that's the case and you're just using the standard socket library, it's largely the same as it would be should you do it in C. A TCP socket with a closed peer will select as 'ready' for read. When you attempt to read that socket, you'll have a 0 length return. If you attempt to write to a socket that's been closed by the other end, you ought to receive a "Broken pipe' socket error. If you attempt to write to a socket that *you've* already closed, then you should just get a standard 'Bad file descriptor' socket.error. Google's your friend with topics like this. There's a lot out there pertaining to the standard POSIX socket calls. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
On 2008-06-15, John Salerno <[EMAIL PROTECTED]> wrote: > Grant Edwards wrote: > >> If the two computers are in no way connected via any type of >> network, then the two programs won't be able to talk to each >> other. >> >> The programs can't create a network, they can only use one that >> already exists. > > But isn't that the point of the program, to create a network between the > two computers? No. For the two programs to work, the network must already exist and be properly configured. In this seinse, a "network" is a mechanism which programs can use to establish connections with each other. > Isn't that what the host and port are used for, to open a > connection? Yes, but a connection and a network aren't the same. When you pick up the phone and dial it, a connection between your phone and the phone your calling is set up. You dialing the phone isn't creating a telephone phone network -- it's using the existing telephone network to create a connection. In the case of the telephones, the "network" is the wires, the central office switches (and associated software), and the interconnecting trunks. In your house, the "network" is the wires and router and cable modem and network cards (and the associated configuration data). Your "home network" may or may not have a connection to the outside world. > (Just to clarify, when I say "in no way connected", I don't > mean not connected to the internet in general. I know they > need access to the internet for any kind of networking program > to work at all.) No, the two computers don't need to be connected to the internet in general. You could set up a network that consists entirely of those two computers and nothing else. Applications on those two computers could still communication with each other. -- Grant Edwards grante Yow! Why don't you at ever enter and CONTESTS, visi.comMarvin?? Don't you know your own ZIPCODE? -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a TCP/IP connection on already-networked computers
Grant Edwards wrote: "home network" is pretty much a meaningless term, so you can use it however you want. My guess is that all the "wizard" did was set up file and print sharing between two computers that were already on the same network and could already talk to each other. Yes, you're right. AFAIK, that was the only effect of what I did. IOW, if both computers were able to access the internet via a single cable modem before you ran the wizard, then it's quite likely they could have communicated with each other as well (using the two python programs or any other network aware applications). So in the case of me trying this with a friend who lives far away, how would these two scripts work if we wouldn't be on the same connection? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python library for clustering from distance vector
On May 19, 2:42 am, jay graves <[EMAIL PROTECTED]> wrote: > On May 17, 11:49 pm, Sengly <[EMAIL PROTECTED]> wrote: > > > I am looking for a python library which can cluster similar objects > > into their respective groups given their similarity score of each two > > of them. I have searched the group but I couldn't find any helpful > > information yet. > > How about google? Searching for the terms python and cluster gave > some results for me. > > http://www.google.com/search?q=python+cluster > > > Any suggestion is appreciated. Also, if you know any specific group > > that I should post this message, please also suggest. > > The book, "Programming Collective Intelligence" by Toby Segaran is > great and has examples of clustering algorithms written in Python. > > http://www.amazon.com/Programming-Collective-Intelligence-Building-Ap... > > ... > Jay Graves Thank you very much for your pointers. Regards, Sengly -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a file
Thanks lot for your valuable suggestions On Sun, Jun 15, 2008 at 4:04 AM, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Sat, 14 Jun 2008 12:45:47 +0530, "Beema shafreen" > <[EMAIL PROTECTED]> declaimed the following in > gmane.comp.python.general: > >Strange: I don't recall seeing this on comp.lang.py, just the first > responder; and a search on message ID only found it on gmane... > > > Hi all, > > > > I have a file with three columns i need to sort the file with respect to > > the third column. How do I do it uisng python. I used Linux command to do > > this. Sort but i not able to do it ? > > can any body ssuggest me > > Question 1: Will the file fit completely within the memory of a running > Python program? > > Question 2: How are the columns defined? Fixed width, known in advance; > tab separated; comma separated. > > If #1 is true, I'd read the file into a list of tuples/sublists (if line > is fixed width columns, read line, manually split on column widths; if > TSV or CSV use the proper options with the CSV module to read the file). > Define a sort key function to extract the key column and use the > built-in list sort method > >data.sort(key=lambda x : x[2]) #warning, I'm not skilled at lambda > > Actually, if text sort order (not numeric value order) is okay, and the > lines are fixed width columns, no need to manually split the columns > into tuples; just read all lines into a list and define a key function > that picks out the columns needed > >data.sort(key=lambda x : x[colstart:colend]) > > > If #1 if FALSE (too big for memory) you will need to create a sort-merge > procedure in which you read n-lines of the file; sort them, write to > temporary file; alternating among 2+ temporary files keeping the same > n-lines (except for the last packet). Then merge the 2+ temporaries over > the n-lines in the batch to a new temporary file; after the first n > lines have been merged (giving n*2+ lines in the batch) switch to > another temporary file for the next batch When all original batches > are merged, repeat the merge using batches of size n*2+... Repeat until > only one temporary file is left (ie, only one long merge batch is > written). > >Or figure out how to call whatever system sort command is available > with whatever parameters are needed -- after all, why reinvent the wheel > if you can reach outside the snake and grab that is already in the snake > pit ("outside the snake" => os.system(...); "snake pit" => the OS > environment). Even WinXP has a command line sort command; as long as you > don't need a multikey sort it can handle the simple text record sorting > with limitations on memory size to use. > > -- >WulfraedDennis Lee Bieber KD6MOG >[EMAIL PROTECTED] [EMAIL PROTECTED] >HTTP://wlfraed.home.netcom.com/ >(Bestiaria Support Staff: [EMAIL PROTECTED]) >HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- Beema Shafreen -- http://mail.python.org/mailman/listinfo/python-list