Re: Using non-ascii symbols
Robert Kern wrote: >> I can't find "?, ?, or ?" on my keyboard. > > Get a better keyboard? or OS? > > On OS X, > > ? is Alt-, > ? is Alt-. > ? is Alt-= > > Fewer keystrokes than <= or >= or !=. Sure, but I can't find OS X listed as a prerequisite for using Python. So, while I don't give a damn if those symbols are going to be supported by Python, I don't think the plain ASCII version should be deprecated. There are too many situations where it's still useful (coding across old terminals and whatnot). -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython layout problem
"py" <[EMAIL PROTECTED]> wrote: > >I have the following code: >... >there are two problems. >1) i want the sizer (that is returned from buildTopPanel()) to fill the >screen wide/tall. now the text control in it is very small in the >upper-left corner. > >2) the scroll bars and borders on the text controls dont appear until i >mouse over them, any ideas? The panel you create in buildTopPanel has not been added to any sizer. So, you have the odd condition that the self.text control is controlled by a sizer, but its parent panel is not. The layout is confused. You need to build this up bit by bit. The frame gets a panel. The panel is controlled by a sizer. The panel will contain other panels, added to the parent panel's sizer. The inner panels may need their own sizers. The controls owned by the inner panels need to be added to the inner sizers. The borders don't appear because parts of the panels are overlapping them in strange ways. Several folks have suggested that you create the controls from the outside in, making sure that the control ownership is correct, and then as a separate step, add those controls to sizers from the inside out. That works for me, but some kind of structure is needed to make sure that ownership and sizership are handled completely. You might try posting on the wxPython mailing list, http://www.wxpython.org/maillist.php. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.unlink() AND win32api.DeleteFile()
rbt <[EMAIL PROTECTED]> wrote: > >Can someone detail the differences between these two? On Windows which >is preferred? os.unlink() calls unlink() in the C run-time library. In VC++, unlink() passes its parameter directly to DeleteFile. There is no difference. DeleteFile() is the only way to delete files on Windows. However, if you call os.unlink(), your script will ALSO work in Linux. win32api.DeleteFile() makes your script Windows-only. >Also, is it true that win32api.DeleteFile() can remove the 'special' >files located in the 'special' folders only accessible by the shell >object such as Temporary Internet Files, etc. "Temporary Internet Files" is a perfectly normal directory, living at "\Documents and Settings\username\Local Settings\Temporary Internet Files". It happens to be marked with the "system" attribute ('attrib +s'), but that doesn't make it special. Now, there certainly ARE special shell folders that do not exist in the file system. Control Panel and My Network Places are two examples. DeleteFile cannot touch those. You must use shell APIs. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirecting standard out in a single namespace
On 23 Jan 2006 04:00:40 -0800, "Fuzzyman" <[EMAIL PROTECTED]> wrote: > >Bengt Richter wrote: > [...] >> It wouldn't be shadowing, but I suppose you could replace sys.stdout with >> a custom object whose methods check where they were called from. >> Then you could give the object initialization parameters as to which >> namespace >> you want to have the effect in, and/or methods to control the action or turn >> it on or off etc. BTW, how about stderr? >> > >Redirecting stderr is identical in concept to redirecting stdout. > Yeah, just reminding, in case you need to do that too ;-) >The following in the write method of the custom out object works : > >sys._getframe(1).f_globals['__name__'] > >sys.stdout.write is *always* called from at least one frame deep in the >stack - so it works. Yes, that's about what I had in mind, not being able to think of an alternative (other than the obvious one of using something other than print in the module where you want to redirect, either by hand or by effective source rewrite one way or another to translate print statments into e.g. myprint('the', 'print', 'args') or such. You could do source preprocessing or translating at the AST level, or you could do byte code munging. Nothing too nice. > >However the Python docs say of sys._getframe : > >This function should be used for internal and specialized purposes >only. > >Might this approach be brittle ? > In what sense? I guess it ought to work for the version it's defined for, but the advice is there. Maybe we can get something more specific from the author of the above doc snippet ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehention
On 23/01/2006 18:41, Mathijs uttered: >> len([ref.pop(ref.index(x)) for x in lis if x in ref]) > This is the type of solution I was hoping to see: one-liners, with no > use of local variables. As Tim Chase already wrote, it has only one > less elegant side: it alters the original ref list. > > Thanks for your suggestion. May I suggest another one-liner: len(set(ref).intersection(lis)) I have no idea how this scales/performs compared to the other suggestions you've received, but I find it immediately comprehensible. -- Morten -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for workaround in CSV bug
Simmons, Stephen wrote: > > I've come across a bug in CSV where the csv.reader() raises an > exception if the input line contains '\r'. Example code and output > below shows a test case where csv.reader() cannot read an array > written by csv.writer(). > > Error: newline inside string > WARNING: Failure executing file: Did you play with the csv.Dialect setting lineterminator='\n' ? csv.reader(file(name, 'rb'),lineterminator='\n) See also: http://docs.python.org/lib/csv-fmt-params.html Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
How to enable rotor in python 2.4.2?
Dear all, I've installed python 2.4.2 and Zope 2.8.5 on a 64-bit Linux. As I'm installing FLE (http://fle3.uiah.fi/), I find that it will call the rotor module i npython. However, rotor is removed from python 2.4.2 (http://savannah.nongnu.org/bugs/?func=detailitem&item_id=14434). Could I enable rotor some ways in python again? Thanks. Regards, Murphy -- http://mail.python.org/mailman/listinfo/python-list
Re: os.unlink() AND win32api.DeleteFile()
[rbt] | Can someone detail the differences between these two? On | Windows which is preferred? Looks like that's been answered elsewhere. | Also, is it true that win32api.DeleteFile() can remove the 'special' | files located in the 'special' folders only accessible by the shell | object such as Temporary Internet Files, etc. Generally, you want to look at the functions in the shell module from pywin32 for these. Specifically, look at [using: from win32com.shell import shell, shellcon because I always forget *which* is the shell module I need to import] shell.SHGetSpecialFolderLocation shell.SHFileOperation The former will find the "real" location of various special-looking folders. The latter will move/copy etc. through the shell which means, among other things, that you'll see the "flying folders" animated icon. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehention
[Mathijs] > Example2: > ref=[2, 2, 4, 1, 1] > list=[2, 2, 5, 2, 4] > solution: 3 (note that only the first two 2's count, the third 2 in the > list should not be counted) [Morten Vold] > May I suggest another one-liner: > > len(set(ref).intersection(lis)) > > I have no idea how this scales/performs compared to the other > suggestions you've received, but I find it immediately comprehensible. >>> len(set([2, 2, 4, 1, 1]).intersection([2, 2, 5, 2, 4])) 2 Close, but no cigar. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
Aahz wrote: > >the sample site contains ~600 pages. each page has been automatically > >translated from python.org sources to moinmoin markup, and then stored > >in a moinmoin 1.5 instance. a separate component has then extracted the > >pages from moinmoin, and converted them XHTML fragments for rendering. > > That looks pretty good. The most serious bug I've found so far in your > conversion is the missing form for grabbing SF bugs/patches on > http://www.python.org/dev/ > just after "Links for Developers" forms and tables are not handled well, and there are lots of minor issues with the current html->moin converter (it's a 2x15-minute hack, after all). > I'm curious what you plan to do for handling sidebar links, especially > context-sensitve ones that change as you switch between sections of the > site. I think I mentioned this in an earlier post; simply adding a special SideBar link list at the top of a page should be good enough SideBar: * [link title] * [link title] * [link title] -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehention
On 24/01/2006 09:46, Peter Otten uttered: len(set([2, 2, 4, 1, 1]).intersection([2, 2, 5, 2, 4])) > 2 > Close, but no cigar. I need more coffee! (note to self: Always read entire problem set first) -- Morten -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing for the presence of input from stdin.
Will McDonald wrote: > Hi all. > > I'm writing a little script that operates on either stdin or a file > specified on the command line when run. I'm trying to handle the > situation where the script's run without any input gracefully but > can't think how to test for stdin. > Hi, maybe http://docs.python.org/lib/module-fileinput.html is useful for you: "This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed." HtH, Roland -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension
Patrick Maupin wrote: def occurrences(t): > ... res = {} > ... for item in t: > ... res.setdefault(item,[0])[0] += 1 > ... return res > ... > I think somebody was mentioning "mutable ints" at one point, > which is basically what I abuse [0] to provide. If I were doing a lot > of this in one place, I would code a mutable integer class, and then > the rest of the code would get simpler. Or you could use the facilities built in to Python: use the get method as Bryan did, and the code gets simpler without using mutable integers. I prefer writing an 'if' statement here, Bryan prefers 'get', that's just a choice of style. But 'setdefault' here, that has no style. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to enable rotor in python 2.4.2?
I compiled python 2.3.5 and copy the lib-dynload/rotor.so to the 2.4.2 lib and it works... Thanks anyway. :) Murphy Murphy Wong wrote: > > Dear all, > > I've installed python 2.4.2 and Zope 2.8.5 on a 64-bit Linux. As I'm > installing FLE (http://fle3.uiah.fi/), I find that it will call the > rotor module i npython. However, rotor is removed from python 2.4.2 > (http://savannah.nongnu.org/bugs/?func=detailitem&item_id=14434). Could > I enable rotor some ways in python again? Thanks. > > Regards, > Murphy > -- http://mail.python.org/mailman/listinfo/python-list
Re: Backreferences in python ?
Pankaj <[EMAIL PROTECTED]> wrote: >search for :for ( i = 0; i < 10; i++) >Replace with: for( printf( "10" ), i =0; i < 10; i++) >Where 10 is the line no. >f = open( "./1.c", "r") >fNew = open( "./1_new.c", "w") >for l in f: >print l >lineno = lineno + 1 >strToFind = "for\((.*)\;(.*)" [etc.] >search for :for ( i = 0; i < 10; i++) >Replace with: for( printf( "10" ), i =0; i < 10; i++) Ah, the dangers of thinking of all string manipulation as requiring regexps, thanks to their ubiquity in Perl. Observe: >search for : for ( i = 0; i < 10; i++) >Replace with: for( printf( "10" ), i = 0; i < 10; i++) All you need is: strToFind = "for (" strToReplace = 'for (printf( "+str(lineno)+'" ),' # Note the use of '' to avoid the need to escape the "s fNew.write(l.replace(strToFind, strToReplace) (OK, maybe you do need the regexp if you've got any "for (;" loops, or inconsitencies as to whether it's "for(" or "for (". But if a simple string replace will do the job, use it.) -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Oddities of Tkinter
On 23 Jan 2006 11:28:37 -0800, Tuvas <[EMAIL PROTECTED]> wrote: > I am building a tkinter program. A part of this program is to read data > from an incoming interface, and depending on the data, will display a > bit of text on the tk dialog, it decodes this data, so to speak. If one > command is sent, everything's just fine. When multiple are sent, the > program will stop responding, and will only continue to respond after > one types -c. The statement at fault is something like this. > > e1=StringVar() > Label (master,textvariable=e1, width=32).grid(row=44, column=4) > > def disp_mes1(text): > e1.set(text) > > It's the line 31.set(text) that takes so long when there's other > processes running. I've ran this program sucessfully many times on > another computer, however, when transfering to another with the same > OS, this problem was created. Any ideas as to what I might be able to > do to fix this problem? I've already seen this kind of problems when trying to do Tkinter calls from other threads than the one from which the mainloop was started. Are there any threads involved? I also know that tk can take a very long time on such requests when there are "unusual" non-ascii characters to display (CJK for example) as it automatically looks for a font that will be able to render it; it may take a very long time, especially if there are many installed fonts. Do you try to display such characters? You also don't tell us what your OS is. It may help... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing for the presence of input from stdin.
On 24/01/06, Roland Heiber <[EMAIL PROTECTED]> wrote: > Will McDonald wrote: > > Hi all. > > > > I'm writing a little script that operates on either stdin or a file > > specified on the command line when run. I'm trying to handle the > > situation where the script's run without any input gracefully but > > can't think how to test for stdin. > > maybe http://docs.python.org/lib/module-fileinput.html is useful for you: That looks ideal, I'll have a play with it to see how it behaves in conjunction with getopt. Thanks Roland. Thanks Peter and Diez for your input too. Will. -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing for the presence of input from stdin.
Will McDonald wrote: > > There are more experienced UNIXers here, but from my POV I don't see how > > that can happen. The reason is simply that > > > > - sys.stdin alwasy exists (unless you close it yourself) > > > > - in a pipe (which this essentially is) there is now way to know if there > > is more date to come or not, except for the "broken pipe" error - but that > > won't happen to you, as sys.stdin is not broken just because there is > > currently no data arriving. > > That's a good point. I did wonder if it'd just have to sit there > waiting for input much like cat would. I think that's preferable, and > simpler :), than implementing timeouts. the usual way to implement this is to treat the filename "-" as stdin. if filename == "-": f = sys.stdin else: f = open(filename) ... read from f ... if f is not sys.stdin: f.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to enable rotor in python 2.4.2?
Murphy Wong wrote: > Dear all, > > I've installed python 2.4.2 and Zope 2.8.5 on a 64-bit Linux. As I'm > installing FLE (http://fle3.uiah.fi/), I find that it will call the > rotor module i npython. However, rotor is removed from python 2.4.2 > (http://savannah.nongnu.org/bugs/?func=detailitem&item_id=14434). Could > I enable rotor some ways in python again? Thanks. You could get the module from some older Python version (http://svn.python.org/projects/python/branches/release23-maint/Modules/rotormodule.c) and compile it for Python 2.4. You need a C compiler and a minimal setup.py file for compiling the module: from distutils.core import setup from distutils.extension import Extension setup ( name = "rotor", ext_modules = [Extension( name="rotor", sources=["rotormodule.c"] )] ) HTH, -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
PyGTK Notebook button_press_event connection
Hi all! I have an application that uses a gtk.Notebook to show the content of a GUI. Each page of it has a gtk.Label with a text that explains the content. Each page is added to the notebook with the method append_page(child, tab_label=None), passing a gtk.Label instance as tab_label variable. Now I'd like to connect to the button_press_event of the gtk.Label a function call. I've done something like this: notebook = gtk.Notebook() ... child = gtk.Frame() ... label = gtk.Label('Any text') label.connect('button_press_event', a_function) ... notebook.append_page(child, label) But the button_press_event event is not intercepted (nothing happens when I click on the tab label). Any idea to solve this question? Thanks Luigi -- http://mail.python.org/mailman/listinfo/python-list
socket examples
Hi, I've read the Gordon McMillan's "Socket Programming HOWTO" and I'm looking for other documents that show examples on how to write a socket server that can answer multiple clients at the same time. Does someone know where I can find those documents/tutorials ? Very thanks, K. -- http://mail.python.org/mailman/listinfo/python-list
Re: socket examples
"le dahut" wrote: > I've read the Gordon McMillan's "Socket Programming HOWTO" and I'm > looking for other documents that show examples on how to write a socket > server that can answer multiple clients at the same time. > Does someone know where I can find those documents/tutorials ? see http://effbot.org/tag/python.asyncore http://effbot.org/tag/python.asynchat or google for "twisted". -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Help] HOWTO Send a string???
Firstly i would like to do the Send/Receive function. In the second moment i would implement the threading with this functions. is it a good way?In your opinion where could i found a valid implementation of udp send/receive? 2006/1/23, Eric Brunson <[EMAIL PROTECTED]>: This is a reasonably simple thing to do. The specifications soundremarkably like a homework program I might assign in a basic networkprogramming class, but even if it isn't a school assignment, yourrequest is so broad you need to do a little background reading before we can offer more specific help.Start by reading the Python manual section 11.16(http://docs.python.org/lib/module-SocketServer.html) which covers the base SocketServer classes. There's a simple Threading mix-in class thatcan be included to get your threaded model.If you read that, try to write some code and then have more specificquestions, then post back and I'll see if I can help further. e.Sbaush wrote:> Hi all.> In my application I have to do implement a lot of networking in python> My application can create with a GUI a XML file in a string.(and now> my application can do it wow!!) > This string has to be sended to another host. i need a python> application that send this string via UDP.> The packet of this communication is |int|payload| where payload is the> XML string. > After the send my application has to wait for a response and has to> receive response.> For the heaven it should be implemented with separated thread. A> thread send/receive while another indipendent thread do same. >> Have you any ideas to do it more simply as possible?> What is the best way to di it??> What is the best way to thread programming in python?>> Thanks all for your help with me! > --> Sbaush>> --> Sbaush> >> ___> Python-Help maillist - [EMAIL PROTECTED]> http://mail.python.org/mailman/listinfo/python-help> -- Sbaush -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing for the presence of input from stdin.
Peter Gsellmann <[EMAIL PROTECTED]> writes: > Will McDonald wrote: >> That's a good point. I did wonder if it'd just have to sit there >> waiting for input much like cat would. I think that's preferable, and >> simpler :), than implementing timeouts. >> > In unix you can always use select.select() on files and pipes as sys.stdin > is. Use a timout-value of 0 and you get the 'ready-state' of the file > descriptor i.e. the presence of waiting input-data. If you terminate when select() indicates that there is nothing more to read, you will terminate prematurely in many cases. Even 'dd if=/dev/zero | myprogram.py' will stop at some random point, when the OS happens to decide that myprogram.py should be scheduled twice without dd getting the chance to fill the pipe buffer inbetween. -- Thomas Bellman, Lysator Computer Club, Linköping University, Sweden "We don't understand the software, and! bellman @ lysator.liu.se sometimes we don't understand the hardware, ! but we can *see* the blinking lights!" ! Make Love -- Nicht Wahr! -- http://mail.python.org/mailman/listinfo/python-list
Re: Some thoughts on garbage collection
In message <[EMAIL PROTECTED]>, Frank Millman <[EMAIL PROTECTED]> writes >> You could then also categorize this by type, e.g. If you want a nice GUI and no requirement to modify your code Python Memory Validator could be useful. http://www.softwareverify.com Stephen -- Stephen Kellett Object Media Limitedhttp://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting -- http://mail.python.org/mailman/listinfo/python-list
Send a particular packet with this python client
Hi all, i have a python udp client/server.I would send a packed like this: |int|string| . How can i do it with tih client?Another question: buf is the total packet size? from socket import * # Set the socket parameters host = "192.168.11.49" port = 21567 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg # Send messages while (1): data = raw_input('>> ' ) if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'." # Close socket UDPSock.close()-- Sbaush -- http://mail.python.org/mailman/listinfo/python-list
Show content of an external page in plone.
I'm using plone primary as a news system for my school. Now I want to integrate external sources into my plone site. The page is http://www.vucaarhusamtvucwin.dk/hold.asp?v1=randers&v2=randers&v3=a&v4=a which shows the various courses my school offers. This site i updated from a database. And i want to integrate it into my plone site. The links oni should thus not "link away" from my plone site but only show the informationen. I know this is possible with asp hence it is done here http://www.aaa.dk/aaa/randers-hf-vuc-holdra where the input from the above site is integratet into the layout of the aaa site. how can this be achieved with plone ? i found a page http://plone.org/documentation/how-to/integrate-external-content which somehow seems to solve the problem but since I'm a new user to plone systems I cannot use it, the proces stops already when it tells me to create an external method in the skin folder named getBody.py the custom folder does not accept any external methods. So it has to be somewhat easier any suggestions ? CR ps the page http://www.aaa.dk/aaa/randers-hf-vuc-holdra will be closed in the end of 2006 so I have to find an alternative. I'm competing with a company that offers asp codet pages. very expensive so i tought that plone may be the right solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: socket examples
I have a server that receives data from a client, detect the end of this data and send other data back to the client (it's to measure bandwidth). I think the best way is to thread a part of the server's program am I right ? HOST = socket.gethostname() try: PORT = int(sys.argv[1]) print PORT except: PORT = 50009 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "s.bind((", HOST, PORT, "))" s.bind((HOST, PORT)) s.listen(5) while 1: conn, addr = s.accept() print 'Connected by', addr data='' while 1: data += conn.recv(1024) if data[-5:] == '#': #the end of the data break data2='1'*1024*1024 data2=data2[:-5]+'#' #the end of the data conn.send(data2) conn.close() Fredrik Lundh a écrit : > "le dahut" wrote: > > >>I've read the Gordon McMillan's "Socket Programming HOWTO" and I'm >>looking for other documents that show examples on how to write a socket >>server that can answer multiple clients at the same time. >>Does someone know where I can find those documents/tutorials ? > > > see > > http://effbot.org/tag/python.asyncore > http://effbot.org/tag/python.asynchat > > or google for "twisted". > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirecting standard out in a single namespace
Bengt Richter wrote: [snip..] > >The following in the write method of the custom out object works : > > > >sys._getframe(1).f_globals['__name__'] > > > >sys.stdout.write is *always* called from at least one frame deep in the > >stack - so it works. > Yes, that's about what I had in mind, not being able to think of an > alternative > (other than the obvious one of using something other than print in the module > where you want to redirect, either by hand or by effective source rewrite one > way > or another to translate print statments into e.g. myprint('the', 'print', > 'args') or such. > You could do source preprocessing or translating at the AST level, or you > could do byte code munging. > Nothing too nice. > > > > >However the Python docs say of sys._getframe : > > > >This function should be used for internal and specialized purposes > >only. > > > >Might this approach be brittle ? > > > In what sense? I guess it ought to work for the version it's defined for, but > the advice is there. > Maybe we can get something more specific from the author of the above doc > snippet ;-) > ``inspect.currentframe`` has no such warning. The equivalent would then be : inspect.currentframe().f_back.f_globals['__name__'] I guess unless the implementation of Python changes that will continue to work. :-) Thanks Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
On Tue, 24 Jan 2006 04:09:00 +0100, Christoph Zwerschke wrote: > On the page http://wiki.python.org/moin/Python3%2e0Suggestions > I noticed an interesting suggestion: > > "These operators ≤ ≥ ≠ should be added to the language having the > following meaning: > ><= >= != > > this should improve readibility (and make language more accessible to > beginners). > > This should be an evolution similar to the digraphe and trigraph > (digramme et trigramme) from C and C++ languages." > > How do people on this group feel about this suggestion? > > The symbols above are not even latin-1, you need utf-8. > > (There are not many usefuls symbols in latin-1. Maybe one could use × > for cartesian products...) Or for multiplication :-) > And while they are better readable, they are not better typable (at > least with most current editors). > > Is this idea absurd or will one day our children think that restricting > to 7-bit ascii was absurd? > > Are there similar attempts in other languages? I can only think of APL, > but that was a long time ago. My earliest programming was on (classic) Macintosh, which supported a number of special characters including ≤ ≥ ≠ with the obvious meanings. They were easy to enter too: the Mac keyboard had (has?) an option key, and holding the option key down while typing a character would enter a special character. E.g. option-s gave Greek sigma, option-p gave pi, option-less-than gave ≤, and so forth. Much easier than trying to memorize character codes. I greatly miss the Mac's ease of entering special characters, and I miss the ability to use proper mathematical symbols for (e.g.) pi, not equal, and so forth. > Once you open your mind for using non-ascii symbols, I'm sure one can > find a bunch of useful applications. Variable names could be allowed to > be non-ascii, as in XML. Think class names in Arabian... Or you could > use Greek letters if you run out of one-letter variable names, just as > Mathematicians do. Would this be desirable or rather a horror scenario? > Opinions? I think the use of digraphs like != for not equal is a poor substitute for a real not-equal symbol. I think the reliance of 7-bit ASCII is horrible and primitive, but without easier, more intuitive ways of entering non-ASCII characters, and better support for displaying non-ASCII characters in the console, I can't see this suggestion going anywhere. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with running external process
No, no, that wasn't my intention (I'm just not conscious enough what's going on with these fork, exec, spawn.. functions). My parent process should start the child process and go back to it's tasks. Before executing it for the next time the parent should check if the previous child process is done and start it again. Is it what these lines do? os.spawnlp(os.P_NOWAIT,'ext_script.py','') os.waitpid(-1, os.WNOHANG) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Christoph Zwerschke wrote: > On the page http://wiki.python.org/moin/Python3%2e0Suggestions > I noticed an interesting suggestion: > > "These operators ≤ ≥ ≠ should be added to the language having the > following meaning: > > <= >= != > > this should improve readibility (and make language more accessible to > beginners). > > This should be an evolution similar to the digraphe and trigraph > (digramme et trigramme) from C and C++ languages." > > How do people on this group feel about this suggestion? > > The symbols above are not even latin-1, you need utf-8. > > (There are not many usefuls symbols in latin-1. Maybe one could use × > for cartesian products...) > > And while they are better readable, they are not better typable (at > least with most current editors). > > Is this idea absurd or will one day our children think that restricting > to 7-bit ascii was absurd? > > Are there similar attempts in other languages? I can only think of APL, > but that was a long time ago. > > Once you open your mind for using non-ascii symbols, I'm sure one can > find a bunch of useful applications. Variable names could be allowed to > be non-ascii, as in XML. Think class names in Arabian... Or you could > use Greek letters if you run out of one-letter variable names, just as > Mathematicians do. Would this be desirable or rather a horror scenario? > Opinions? > > -- Christoph One of issues in Python is cross-platform portability. Limiting the range of symbols to lower ASCII and with specification of a code table to ASCII is a good deal here. I think, that Unicode is not yet everywhere and as long it is that way it makes not much sense to go for it in Python. Claudio -- http://mail.python.org/mailman/listinfo/python-list
Re: os.unlink() AND win32api.DeleteFile()
Tim Golden wrote: > [rbt] > > | Can someone detail the differences between these two? On > | Windows which is preferred? > > Looks like that's been answered elsewhere. > > | Also, is it true that win32api.DeleteFile() can remove the 'special' > | files located in the 'special' folders only accessible by the shell > | object such as Temporary Internet Files, etc. > > Generally, you want to look at the functions > in the shell module from pywin32 for these. > Specifically, look at > > [using: from win32com.shell import shell, shellcon > because I always forget *which* is the shell module > I need to import] > > shell.SHGetSpecialFolderLocation > shell.SHFileOperation > > The former will find the "real" location of various > special-looking folders. The latter will move/copy etc. > through the shell which means, among other things, that > you'll see the "flying folders" animated icon. > > TJG > Thanks for the explanation guys! -- http://mail.python.org/mailman/listinfo/python-list
xHTML/XML to Unicode (and back)
Hey guys I'm currently screenscraping some Swedish site, and i need a method to convert XML entities (& etc, plus d etc) to Unicode characters. I'm sure one of python's myriad of XML processors can do this but I can't find which one. Can anyone make any suggestions? Thanks -Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Dominant color & PIL
Sebastjan Trepca wrote: > I was wondering is it possible to find out which colour is dominant in an > image using PIL? > It would be very easy to create interesting mozaic images with that :) some alternatives: >>> i = Image.open(...) >>> i.quantize(1).convert("RGB").getpixel((0, 0)) (208, 205, 202) >>> import ImageStat >>> s = ImageStat.Stat(i) >>> s.mean [208.32295432458699, 204.56614188532555, 202.44663427275671] >>> i.resize((1, 1), Image.ANTIALIAS).getpixel((0,0)) (212, 212, 210) (quantize will only return colors that actually exist, the other two uses different ways to calculate some kind of average color) -- http://mail.python.org/mailman/listinfo/python-list
PyWeek Challenge #2: write a game in a week
The date for the second PyWeek challenge has been set: Sunday 26th March to Sunday 2nd April (00:00UTC to 00:00UTC). The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOT YET OPEN -- In order to reduce the number of unnecessary registrations, we will open the challenge for registration one month before the start date. See the competition timetable and rules at: http://www.pyweek.org/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. -- http://mail.python.org/mailman/listinfo/python-list
About multithreaded webserver
Hi,Do anyone know the Python source codes on how to write a simple multithreaded webserver class?RegardsFind the lowest fare online with MSN Travel -- http://mail.python.org/mailman/listinfo/python-list
Re: xHTML/XML to Unicode (and back)
Robin Haswell wrote: > I'm currently screenscraping some Swedish site, and i need a method to > convert XML entities (& etc, plus d etc) to Unicode characters. > I'm sure one of python's myriad of XML processors can do this but I can't > find which one. > > Can anyone make any suggestions? any decent html-aware screen scraper library should be able to do this for you. if you've already extracted the strings, the strip_html function on this page might be what you need: http://effbot.org/zone/re-sub.htm#strip-html -- http://mail.python.org/mailman/listinfo/python-list
Re: file_name_fixer.py
[EMAIL PROTECTED] wrote: > i put this together to fix a bunch of files with wierd names, please > gimme feedback, i am a newbie Ok, so let's go... Hope you won't hate me too much !-) > > #!/usr/bin/env python > import os > import sys > import string > import platform > dir = sys.argv[1] This will shadow the builtin 'dir' function. > noworky = sys.argv[2] If the user fails to provide args, the program will crash with an IndexError - which may not be very helpful. Also, a better scheme would be myprog [-opt1 [-opt2=val [-optN]]] arg1 arg2 argN Hint: the optparse module is your friend http://www.python.org/doc/2.4.2/lib/module-optparse.html > if platform.system() == 'Linux': > uglychars = ''.join( set(string.punctuation+' ') - set('/_.') ) > else: > if platform.system() == 'Windows':#this is broken because windows > is gay with case > uglychars = ''.join( set(string.punctuation+' ') - > set(':\\/_.') ) > else: > print "wtf... what platform is this anyway?" May be MacOS Classic, MacOS X or any *n*x or *BSD variant, or any other platform supporting Python - are there are some... > underscore = '_' > underscore = underscore * len(uglychars) You don't need the intermediate value: underscores = '_' * len(uglychars) > chars = string.maketrans(uglychars, underscore) > print "# PHASE I, DIRECTORIES" Why not processing dirs and files in one pass ? > for path, subdirs, files in os.walk(dir, topdown=True): Err... is the 'dir' argument supposed to be an absolute path or a relative path ? And why using the topdown option ? > oldname = path woops ! this may be the absolute path. Are you sure you want to process an absolute path ? I think you'd better process files and dirs in one path, walking bottom up (so you don't process any file twice). > newname = oldname.translate(chars) > newname = string.lower(newname) Use the 'str' object methods instead of functions from the string module: newname = newname.lower() You can also chain method/function calls: newname = oldname.translate(chars).lower() > while string.count(newname, "__") > 0: in the context of a boolean expression, 0 evaluate to False, non-zero to True. So you don't have to be so explicit: while newname.count('__'): > newname = string.replace(newname,"__","_") You don't need to actually *count* the occurrences of '__' - if there's one, that's enough: while '__' in newname: # proceed Also, a regexp may be more effective here. > while string.count(newname, "..") > 0: > newname = string.replace(newname,"..",".") Don't forget the '..' and '.' special directories in unix filesystems... > if oldname != newname: > if os.path.isfile(newname) or os.path.isdir(newname): And if there's a special file (device etc) ? hint : os.path.exists() > print oldname, "-->\n", newname, "\t\t\tERROR: file/dir > exists\n" stdout is for 'normal' program outputs (ie: outputs that may be used as inputs to another program). This kind of output should go to stderr: print >> sys.stdout, "%s --> %s : \t\t\tERROR: " "file/dir exists" % (oldname, newname,) > else: > print oldname, "-->\n", newname, "\t\t\tYAY: file > renamed\n" > if noworky == "doit": > os.renames(oldname, newname) How is the user supposed to know that he has to pass the string "doit" as a second arg ? There are some (more or less agreed upon) conventions about cli options. Like '--dry-run' to express the fact that the program shouldn't actually do more than simulate it's execution. > print "# PHASE II, FILES" > for path, subdirs, files in os.walk(dir, topdown=True): > for oldname in files: > oldname = os.path.join(path, oldname) Are you *sure* you want to operate on the *whole* *absolute* path ? (cf my thoughts about the "first phase" and the whole algorithm) > newname = oldname.translate(chars) > newname = string.lower(newname) Aren't you repeating some code here ? hint : all duplicated code should be factored out into a function. > newname = string.replace(newname,".mpeg",".mpg") > newname = string.replace(newname,".ram",".rm") > newname = string.replace(newname,".jpeg",".jpg") > newname = string.replace(newname,".qt",".mov") # outside the loop, define a dict like: ext_map = {'mpeg': 'mpg', 'ram' : 'rm', 'jpeg' : 'jpg', # etc } # then in the loop: base, ext = os.path.split(newname) if ext in ext_map: newname = "%s.%s" % (base, ext_map[ext]) > while string.count(newname, "__") > 0: > newname = string.replace(newname,"__","_") duplicated code... > while string.count(newname, "..") > 0: > newname = string.replace(newname,"..",".") > newname
Unified web API for CGI and mod_python?
I've been digging around, but can't seem to come up with the right combo of words to google for to get helpful results. Is there some handy wrapper/module that allows code to target existance as both a CGI script and a mod_python script, with only one "import" statement? Perhaps some common object model? I've got CGI access on one server, and mod_python on another...I'd prefer to use mod_python for the reduced overhead (my own performance testing seems to indicate it's got a good lead over CGI), but it's not as available on various hosting services as CGI access is. Thanks, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
>> Is this idea absurd or will one day our children think >> that restricting to 7-bit ascii was absurd? Both... this idea will only become none-absurd when unicode will become as prevalent as ascii, i.e. unicode keyboards, universal support under almost every application, and so on. Even if you can easly type it on your macintosh, good luck using it while using said macintosh to ssh or telnet to a remote server and trying to type unicode... -- http://mail.python.org/mailman/listinfo/python-list
ZODB and Zope on one Linux machine, how?
I have a productional Linux web server with a Python/Zope/Plone. Now I'd like to install a non-Zope Python/ZODB application on the same server. What is the recommended way of doing that? Option 1: Install ZODB in the Python installation in the usual way. Should I expect problems when I install and run zope with that Python installation? Option 2: Do not install ZODB in the Python installation. Install Zope in the usual way. Add Zope's ZODB modules to the application's PYTHONPATH. But this may cause upgrade/compatibility problems with the application when Zope and the ZODB in it are upgraded. Option 3: Use separate Python installations for Zope and the application. Install ZODB in the application's Python installation, not in Zope's. Option 4: ? I'm using: - Python 2.3.5 - ZODB 3.2.10 (same as in Zope 2.7.8) - Zope 2.7.8 - Plone 2.1.1 ... all built from source on Debian Woody. Thank you very much in advance. -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
Gerhard Häring wrote: > > the sample site contains ~600 pages. each page has been automatically > > translated from python.org sources to moinmoin markup, and then stored > > in a moinmoin 1.5 instance. a separate component has then extracted the > > pages from moinmoin, and converted them XHTML fragments for rendering. > > Great. > > This sounds a lot like the ugly hacked script I produced that would dump > all MoinMoin contents to XHTML in one directory, and the raw MoinMoin > sources to another directory: > > http://ghaering.de/pydotorg/dumpwiki.py that's quite similar to what I've been using, with the exception that I'm pulling the text from a moinmoin server, and cleaning up the resulting HTML (which is wikified, and quite horrible ;-). > The other part of my experiment was a stupid build system that > recursively looks for KID files in a directory tree and renders them to > HTML. > > What do you think of an approach like this? makes perfect sense, in itself (but I think the choice of templating system can wait until we've sorted out the CMS and rendering side of things). let's get the content in good shape first... -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGTK Notebook button_press_event connection
> > > notebook = gtk.Notebook() > ... > child = gtk.Frame() > ... > label = gtk.Label('Any text') > label.connect('button_press_event', a_function) > ... > notebook.append_page(child, label) > > > > But the button_press_event event is not intercepted (nothing happens > when I click on the tab label). A gtk.Label does not have a gdk window (as in the windowing system of gtk+), so it cannot listen to events. A workaround is to put it in an eventbox: eventbox = gtk.EventBox() eventbox.set_events(gtk.gdk.BUTTON_PRESS_MASK) eventbox.connect('button-press-event', callback) label = gtk.Label() eventbox.add(label) notebook.append_page(..., eventbox) Perhaps you should subscribe to the PyGTK mailing list[1] though, where this kind of question is more appropriately asked [1]: http://www.daa.com.au/mailman/listinfo/pygtk Johan Dahlin -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Christoph Zwerschke wrote: > "These operators ≤ ≥ ≠ should be added to the language having the > following meaning: > > <= >= != > > this should improve readibility (and make language more accessible to > beginners). > I assume most python beginners know some other programming language, and are familiar with the >= and friends. Those learning python as their first programming language will benefit from learning the >= when they learn a new language. Unicode is not yet supported everywhere, so some editors/terminals might display the suggested one-char operators as something else, effectively "guess what operator I was thinking". Fortran 90 allowed >, >= instead of .GT., .GE. of Fortran 77. But F90 uses ! as comment symbol and therefore need /= instead of != for inequality. I guess just because they wanted. However, it is one more needless detail to remember. Same with the suggested operators. -- http://mail.python.org/mailman/listinfo/python-list
Re: xHTML/XML to Unicode (and back)
On Tue, 24 Jan 2006 14:46:46 +0100, Fredrik Lundh wrote: > Robin Haswell wrote: > >> I'm currently screenscraping some Swedish site, and i need a method to >> convert XML entities (& etc, plus d etc) to Unicode characters. >> I'm sure one of python's myriad of XML processors can do this but I can't >> find which one. >> >> Can anyone make any suggestions? > > any decent html-aware screen scraper library should be able to do > this for you. I'm using BeautifulSoup and it appears that it doesn't. I'd also like to know the answer to this for when I do screenscraping with regular expressions :-) Thanks > > if you've already extracted the strings, the strip_html function on > this page might be what you need: > > http://effbot.org/zone/re-sub.htm#strip-html > > -- http://mail.python.org/mailman/listinfo/python-list
append to the end of a dictionary
Hi there, I seem to be unable to find a way to appends more keys/values to the end of a dictionary... how can I do that? E.g: mydict = {'a':'1'} I need to append 'b':'2' to it to have: mydict = {'a':'1','b':'2'} How to do? Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: Send a particular packet with this python client
I can specify the question, so you can request me easily...The int should be an integer of 32 bit fixed. This is total packet size. The string should contain XML.In this example the string is taken from keyboard, so for example. Thanks all for your helps...2006/1/24, Sbaush <[EMAIL PROTECTED]>: Hi all, i have a python udp client/server.I would send a packed like this: |int|string| . How can i do it with tih client?Another question: buf is the total packet size? from socket import * # Set the socket parameters host = "192.168.11.49" port = 21567 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg# Send messages while (1): data = raw_input('>> ' ) if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'." # Close socket UDPSock.close()-- Sbaush -- Sbaush -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyVISA 1.0 -- GPIB, USB, RS232 instrument control
Hallöchen! At http://pyvisa.sourceforge.net you can find information about the PyVISA package. It realises Python bindings for the VISA library functions, which enables you to control GPIB, USB, and RS232-serial measurement devices via Python. Today I released version 1.0. If you have v0.9.7 of last september already, you needn't download it because it contains only minor improvements in the documentation. However, since I've received a couple of positive reports about successful use of PyVISA (and no negatives), I finally dare to jump to 1.0 and declare it stable. Tschö, Torsten. F'up to comp.lang.python -- Torsten Bronger, aquisgrana, europa vetusICQ 264-296-646 -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt wrote: > Hi there, > > I seem to be unable to find a way to appends more keys/values to the end > of a dictionary... how can I do that? > > E.g: > > mydict = {'a':'1'} > > I need to append 'b':'2' to it to have: > > mydict = {'a':'1','b':'2'} > mydict['b'] = '2' -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
> I seem to be unable to find a way to appends more keys/values to the end > of a dictionary... how can I do that? > > E.g: > > mydict = {'a':'1'} > > I need to append 'b':'2' to it to have: > > mydict = {'a':'1','b':'2'} my understanding is that the order of a dictionary should never be relied upon. To do what you want, you'd use mydict['b'] = '2' However, you're just as liable to get >>> mydict {'a':'1','b':'2'} as you are to get >>> mydict {'b':'2','a':'1'} To get them in a key-order, my understanding is that you have to use something like keys = mydict.keys() sort(keys) orderedDict = [(k, mydict[k]) for k in keys] unless you have a way of doing an in-line sort, in which you would be able to do something like orderedDict = [(k,mydict[k]) for k in mydict.keys().sort()] Unfortunately, the version I've got here doesn't seem to support a sort() method for the list returned by keys(). :( -tim -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt: >I seem to be unable to find a way to appends more keys/values to the end >of a dictionary A dictionary has no order, and therefore no end. >mydict = {'a':'1'} > >I need to append 'b':'2' to it to have: > >mydict = {'a':'1','b':'2'} > >How to do? Like this: >>> mydict = {'a':'1'} >>> mydict['b'] = '2' >>> print mydict {'a': '1', 'b': '2'} >>> {'a': '1', 'b': '2'} == {'b': '2', 'a': '1'} True -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt wrote: > I seem to be unable to find a way to appends more keys/values to the end > of a dictionary... how can I do that? > > E.g: > > mydict = {'a':'1'} > > I need to append 'b':'2' to it to have: > > mydict = {'a':'1','b':'2'} to add stuff to a dictionary, use item assignment: mydict["b"] = 2 dictionaries are unordered, so the items you add will appear at an arbitrary location. for more on this, see the tutorial: http://www.python.org/doc/2.4.2/tut/node7.html#SECTION00750 -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt wrote: > I seem to be unable to find a way to appends more keys/values to the end > of a dictionary... how can I do that? A dictionary doesn't have an 'end' because it is an unordered collection. > E.g: > mydict = {'a':'1'} > I need to append 'b':'2' to it to have: mydict['b'] = '2' print mydict http://python.org/doc/2.4.2/tut/node7.html#SECTION00750 HTH. ... jay -- http://mail.python.org/mailman/listinfo/python-list
Re: How to enable rotor in python 2.4.2?
Murphy Wong <[EMAIL PROTECTED]> writes: > I've installed python 2.4.2 and Zope 2.8.5 on a 64-bit Linux. As I'm > installing FLE (http://fle3.uiah.fi/), I find that it will call the > rotor module i npython. However, rotor is removed from python 2.4.2 > (http://savannah.nongnu.org/bugs/?func=detailitem&item_id=14434). > Could I enable rotor some ways in python again? Thanks. I don't know what FLE is but rotor is not a good encryption. Instead of restoring it to a new Python instance, FLE should be updated to not use it. -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Rene Pijlman wrote: > Yves Glodt: >> I seem to be unable to find a way to appends more keys/values to the end >> of a dictionary > > A dictionary has no order, and therefore no end. that means I can neither have a dictionary with 2 identical keys but different values...? I would need e.g. this: (a list of ports and protocols, to be treated later in a loop) ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'} #then: for port,protocol in ports.iteritems(): print port,protocol #do more stuff What would be the appropriate pythonic way of doing this? >> mydict = {'a':'1'} >> >> I need to append 'b':'2' to it to have: >> >> mydict = {'a':'1','b':'2'} >> >> How to do? > > Like this: > mydict = {'a':'1'} mydict['b'] = '2' print mydict > {'a': '1', 'b': '2'} {'a': '1', 'b': '2'} == {'b': '2', 'a': '1'} > True > -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt wrote: > Hi there, > > I seem to be unable to find a way to appends more keys/values to the end > of a dictionary... how can I do that? > > E.g: > > mydict = {'a':'1'} > > I need to append 'b':'2' to it to have: > > mydict = {'a':'1','b':'2'} > > > > How to do? Sorry for the noise... mydict['b'] = '2' > Best regards, > Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
> that means I can neither have a dictionary with 2 identical keys but > different values...? correct :) > I would need e.g. this: > (a list of ports and protocols, to be treated later in a loop) > > ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'} > #then: > for port,protocol in ports.iteritems(): > print port,protocol > #do more stuff > > What would be the appropriate pythonic way of doing this? I would lean towards using tuples, as in ports = [('5631','udp'), ('5632', 'tcp'), ('3389','tcp'), ('5900','tcp')] which you can then drop into your code: for (port, protocol) in ports: print port, protocol #do more stuff This allows you to use the same port with both UDP and TCP. If you want to ensure that only one pair (port+protocol) can be in the list, you can use a set() object: set(ports) (or in earlier versions: from sets import Set s = Set(ports) which I happened to have here) This will ensure that you don't end up with more than one item with the same port+protocol pair. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt <[EMAIL PROTECTED]> writes: > that means I can neither have a dictionary with 2 identical keys but > different values...? No. > I would need e.g. this: > (a list of ports and protocols, to be treated later in a loop) > > ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'} > #then: > for port,protocol in ports.iteritems(): > print port,protocol > #do more stuff > > What would be the appropriate pythonic way of doing this? ports = [('5631', 'udp'), ('5632': 'tcp'), ('3389': 'tcp'), ('5900': 'tcp')] for port,protocol in ports: print port, protocol # ... You'd append with ports.append(('2345', 'tcp')) note the double set of parentheses since you're appending a tuple. -- http://mail.python.org/mailman/listinfo/python-list
Re: Send a particular packet with this python client
Now i can explain better than previous messages.This string has to be sent to another host via UDP with the previous attached simple client/server udp implementation in python. The big problem is:The packet MUST be like this c struct: #define PAYLOAD_LENGHT 5000 struct command_hdr { int lenght; // sizeof(payload) = sizeof(int) + strlen(payload) unsigned char payload[PAYLOAD_LENGHT]; // the xml string} __attribute__ ((packed)); How can i do it in python?2006/1/24, Sbaush < [EMAIL PROTECTED]>:I can specify the question, so you can request me easily... The int should be an integer of 32 bit fixed. This is total packet size. The string should contain XML.In this example the string is taken from keyboard, so for example. Thanks all for your helps...2006/1/24, Sbaush <[EMAIL PROTECTED]>: Hi all, i have a python udp client/server.I would send a packed like this: |int|string| . How can i do it with tih client?Another question: buf is the total packet size? from socket import * # Set the socket parameters host = "192.168.11.49" port = 21567 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg# Send messages while (1): data = raw_input('>> ' ) if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'." # Close socket UDPSock.close()-- Sbaush -- Sbaush -- Sbaush -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Paul Rubin wrote: > Yves Glodt <[EMAIL PROTECTED]> writes: >> that means I can neither have a dictionary with 2 identical keys but >> different values...? > > No. > >> I would need e.g. this: >> (a list of ports and protocols, to be treated later in a loop) >> >> ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'} >> #then: >> for port,protocol in ports.iteritems(): >> print port,protocol >> #do more stuff >> >> What would be the appropriate pythonic way of doing this? > > ports = [('5631', 'udp'), > ('5632': 'tcp'), > ('3389': 'tcp'), > ('5900': 'tcp')] > > for port,protocol in ports: > print port, protocol # ... > > You'd append with > >ports.append(('2345', 'tcp')) > > note the double set of parentheses since you're appending a tuple. Tim, Paul, I love you guys ! Thanks a lot -- http://mail.python.org/mailman/listinfo/python-list
"wxPython in Action" book
New book on wxPython: http://www.manning.com/books/rappin Release date of this month. Does anyone know if it's out yet / has anyone read it and has an opinion? Iain -- http://mail.python.org/mailman/listinfo/python-list
PyAmazon and Book Descriptions
First off, I'm new to Python, so please forgive if I've overlooked something obvious. I work for a publisher and I'm trying to use PyAmazon to programmatically examine our books' listings on Amazon.com. One of the crucial fields for this task is Book Description, which is not one of the available elements, or Bags. Is there a reason why this is the case? I've tried to add this field to the query using language found in broader documentation for Amazon Web services, but no luck. Any insight would be greatly appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt: >I would need e.g. this: >(a list of ports and protocols, to be treated later in a loop) [...] >What would be the appropriate pythonic way of doing this? In the case of tcp and udp ports, it's the combination of protocol and port number that's unique, not the port number by itself. So you could create a dictionary with a tuple (protocol, port) as key, and whatever data you need to associate with it as value. mydict = { ('udp',5631): 'value1', ('tcp',3389): 'value2' } -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: Unified web API for CGI and mod_python?
Tim Chase wrote: > I've been digging around, but can't seem to come up with the > right combo of words to google for to get helpful results. Is > there some handy wrapper/module that allows code to target > existance as both a CGI script and a mod_python script, with only > one "import" statement? Perhaps some common object model? You could try WebStack - it provides a common API which would probably be suitable for your purposes: http://www.python.org/pypi/WebStack The PythonInfo Wiki [1] has a WebProgramming page which also gives information about the different frameworks and standards. Paul [1] http://wiki.python.org/moin/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for workaround in CSV bug
Simmons, Stephen wrote: > > > > I've come across a bug in CSV where the csv.reader() raises an > > exception if the input line contains '\r'. Example code and output > > below shows a test case where csv.reader() cannot read an array > > written by csv.writer(). > > > > Error: newline inside string > > WARNING: Failure executing file: > Michael Stroeder suggested: > Did you play with the csv.Dialect setting lineterminator='\n' ? This didn't make any difference. I found a bug on SourceForge referring to this. It's bug #967934 "csv module cannot handle embedded \r". The description says "CSV module cannot handle the case of embedded \r (i.e. carriage return) in a field. As far as I can see, this is hard-coded into the _csv.c file and cannot be fixed with Dialect changes." However I found a workaround by opening the file in universal newline mode. As shown below, this stops csv from raising an exception. It's still a bug, though, as the programmer needs to know to open the file with mode 'rUb' when it was originally created as 'rb'. Is this fixed for Python 2.5? Cheers Stephen #- import csv s = [ ['a'], ['\r'], ['b'] ] name = 'c://temp//test2.csv' print 'Writing CSV file containing %s' % repr(s) f = file(name, 'wb') csv.writer(f).writerows(s) f.close() print 'CSV file is %s' % repr(file(name, 'rb').read()) print 'Now reading back as CSV...' # This give a _csv.Error exception when csv.reader() encounters the \r: # f = file(name, 'rb') # But adding the universal newline format U makes everything OK again: f = file(name, 'rUb') for r in csv.reader(f): print 'Read row containing %s' % repr(r) # Output is: # Writing CSV file containing [['a'], ['\r'], ['b']] # CSV file is 'a\r\n"\r"\r\nb\r\n' # Now reading back as CSV... # Read row containing ['a'] # Read row containing ['\n'] # Read row containing ['b'] -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
In article <[EMAIL PROTECTED]>, Fredrik Lundh <[EMAIL PROTECTED]> wrote: >Aahz wrote: >>Fredrik: >>> >>>the sample site contains ~600 pages. each page has been automatically >>>translated from python.org sources to moinmoin markup, and then stored >>>in a moinmoin 1.5 instance. a separate component has then extracted the >>>pages from moinmoin, and converted them XHTML fragments for rendering. >> >> That looks pretty good. The most serious bug I've found so far in your >> conversion is the missing form for grabbing SF bugs/patches on >> http://www.python.org/dev/ >> just after "Links for Developers" > >forms and tables are not handled well, and there are lots of minor issues >with the current html->moin converter (it's a 2x15-minute hack, after all). That's fine, just wanted to make sure it wasn't getting lost in the noise. >> I'm curious what you plan to do for handling sidebar links, especially >> context-sensitve ones that change as you switch between sections of the >> site. > >I think I mentioned this in an earlier post; simply adding a special SideBar >link list at the top of a page should be good enough > > SideBar: > * [link title] > * [link title] > * [link title] > > Hrm. So you're suggesting that each page have a manually-created sidebar? One thing I do like about the current (and currently planned future) setup is that it's easy to create a custom sidebar for a section of the website. (E.g. all the dev pages have the same sidebar.) -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis -- http://mail.python.org/mailman/listinfo/python-list
Re: file_name_fixer.py
[EMAIL PROTECTED] wrote: > i put this together to fix a bunch of files with wierd names, please > gimme feedback, i am a newbie See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442517 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Giovanni Bajo wrote: > Robert Kern wrote: > > >>>I can't find "?, ?, or ?" on my keyboard. Posting code to newsgroups might get harder too. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: xHTML/XML to Unicode (and back)
Robin Haswell wrote: > On Tue, 24 Jan 2006 14:46:46 +0100, Fredrik Lundh wrote: > > > Robin Haswell wrote: > > > >> I'm currently screenscraping some Swedish site, and i need a method to > >> convert XML entities (& etc, plus d etc) to Unicode characters. > >> I'm sure one of python's myriad of XML processors can do this but I can't > >> find which one. > >> > >> Can anyone make any suggestions? > > > > any decent html-aware screen scraper library should be able to do > > this for you. And if it's really XHTML/XML, why not just use an XML parser? ;-) > I'm using BeautifulSoup and it appears that it doesn't. I'd also like to > know the answer to this for when I do screenscraping with regular > expressions :-) Anyway, on the subject of XML parsers, here's something to try out: import libxml2dom import urllib f = urllib.urlopen("http://www.sweden.se/";) # some Swedish site! s = f.read() f.close() d = libxml2dom.parseString(s, html=1) Here, we assume that the site isn't well-formed XML and must be treated as HTML, which libxml2 seems to be fairly good at doing. Then... for a in d.xpath("//a"): print repr(a.getAttribute("href")), \ repr(a.getAttribute("title")), \ repr(a.nodeValue) Here, we print out some of the hyperlinks in the page using repr to show what the strings look like (and in a way that doesn't require you to encode them for your terminal). On the above Swedish site, you'll see some things like this: u'Fran\xe7ais' What's interesting is that in some cases such strings may have been encoded using entities (such as in the title attributes), whereas in other cases they may have been encoded using UTF-8 byte sequences (such as in the link texts). The nice thing is that libxml2 just works it out on your behalf. So there's no compelling need for regular expressions, but I'm sure Fredrik will offer some alternative suggestions... and possibly some good Swedish links, too. ;-) Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
Aahz wrote: > >I think I mentioned this in an earlier post; simply adding a special SideBar > >link list at the top of a page should be good enough > > > > SideBar: > > * [link title] > > * [link title] > > * [link title] > > > > > > Hrm. So you're suggesting that each page have a manually-created > sidebar? One thing I do like about the current (and currently planned > future) setup is that it's easy to create a custom sidebar for a section > of the website. (E.g. all the dev pages have the same sidebar.) no, the side bar would of course contain all the sidebar sections that apply to the current page (inheriting from "parent" pages, like today). (I'm beginning to think that categories might be a better way to link pages to each other in the wiki, but the same approach works in that case too, of course). -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Rocco Moretti wrote: [James Stroud wrote:] I can't find "?, ?, or ?" on my keyboard. > > Posting code to newsgroups might get harder too. :-) His post made it through fine. Your newsreader messed it up. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Loading a Python collection from an text-file
another approach (probably frowned upon, but it has worked for me) is to use python syntax (a dictionary, say, or a list) and just import (or reload) the file -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Giovanni Bajo wrote: > Sure, but I can't find OS X listed as a prerequisite for using Python. So, > while I don't give a damn if those symbols are going to be supported by > Python, > I don't think the plain ASCII version should be deprecated. There are too many > situations where it's still useful (coding across old terminals and whatnot). I think we should limit the discussion to allowing non-ascii symbols *alternatively* to (combinations of) ascii chars. Nobody should be forced to use them since not all editors/OSs and keyboards support it. Think about moving from ASCII to LATIN-1 or UTF-8 as similar to moving from ISO 646 to ASCII (http://en.wikipedia.org/wiki/C_trigraph). I think it is a legitimate question, after UTF-8 becomes more and more supported. Editors could provide means to easily enter these symbols once programming languages start supporting them: Automatic expansion of ascii combinations, Alt-Combinations (like in OS-X) or popup menus with all supported symbols. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Ido Yehieli wrote: >>>Is this idea absurd or will one day our children think >>>that restricting to 7-bit ascii was absurd? > > Both... this idea will only become none-absurd when unicode will become > as prevalent as ascii, i.e. unicode keyboards, universal support under > almost every application, and so on. Even if you can easly type it on > your macintosh, good luck using it while using said macintosh to ssh or > telnet to a remote server and trying to type unicode... [~]$ ssh [EMAIL PROTECTED] [EMAIL PROTECTED]'s password: Linux rkernx2 2.6.12-9-amd64-generic #1 Mon Oct 10 13:27:39 BST 2005 x86_64 GNU/Linux The programs included with the Ubuntu system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Mon Jan 9 12:40:28 2006 from 192.168.1.141 [~]$ cat > utf-8.txt x + y ≥ z [~]$ cat utf-8.txt x + y ≥ z Luck isn't involved. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Christoph Zwerschke wrote: > On the page http://wiki.python.org/moin/Python3%2e0Suggestions > I noticed an interesting suggestion: > > "These operators ≤ ≥ ≠ should be added to the language having the > following meaning: > > <= >= != > > this should improve readibility (and make language more accessible to > beginners). > > This should be an evolution similar to the digraphe and trigraph > (digramme et trigramme) from C and C++ languages." > > How do people on this group feel about this suggestion? > > The symbols above are not even latin-1, you need utf-8. > > (There are not many usefuls symbols in latin-1. Maybe one could use × > for cartesian products...) > > And while they are better readable, they are not better typable (at > least with most current editors). > > Is this idea absurd or will one day our children think that restricting > to 7-bit ascii was absurd? > > Are there similar attempts in other languages? I can only think of APL, > but that was a long time ago. > > Once you open your mind for using non-ascii symbols, I'm sure one can > find a bunch of useful applications. Variable names could be allowed to > be non-ascii, as in XML. Think class names in Arabian... Or you could > use Greek letters if you run out of one-letter variable names, just as > Mathematicians do. Would this be desirable or rather a horror scenario? > Opinions? > > -- Christoph This will eventually happen in some form. The problem is that we are still in the infancy of computing. We are using stones and chisels to express logic. We are currently faced with text characters with which to express intent. There will come a time when we are able to represent a program in another form that is readily portable to many platforms. In the meantime (probably 50 years or so), it would be advantageous to use a universal character set for coding programs. To that end, the input to the Python interpreter should be ISO-10646 or a subset such as Unicode. If the # -*- coding: ? -*- line specifies something other than ucs-4, then a preprocessor should convert it to ucs-4. When it is desireable to avoid the overhead of the preprocessor, developers will find a way to save source code in ucs-4 encoding. The problem with using Unicode in utf-8 and utf-16 forms is that the code will forever need to be written and forever execute additional processing to handle the MBCS and MSCS (Multiple-Short Character Set) situation. Ok. Maybe computing is past infancy. But most development environments are not much past toddler stage. -- http://mail.python.org/mailman/listinfo/python-list
Re: IPython 0.7.1 is out.
Fernando Perez wrote: > IPython's homepage is at: > > http://ipython.scipy.org > > and downloads are at: > > http://ipython.scipy.org/dist And if you have easy_install ( install it by running http://peak.telecommunity.com/dist/ez_setup.py if you already haven't done it), you can just say: easy_install ipython If you are on Windows, launch IPython by running the resulting ipython.exe in python scripts folder, typically C:\Python24\Scripts. Linux users will just run "ipython", of course. Please report any problems you might have. -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Tim Chase <[EMAIL PROTECTED]> wrote: >unless you have a way of doing an in-line sort, in which you >would be able to do something like > > orderedDict = [(k,mydict[k]) for k in mydict.keys().sort()] > >Unfortunately, the version I've got here doesn't seem to support >a sort() method for the list returned by keys(). :( I bet it does, but it doesn't do what you think it does. See http://docs.python.org/lib/typesseq-mutable.html , in particular note 7. What you want is the sorted() function (introduced in 2.4 IIRC). -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension
Duncan Booth wrote: > I prefer writing an 'if' statement here, Bryan prefers 'get', that's just a > choice of style. But 'setdefault' here, that has no style. Well, I'm often told I have no style, and I _did_ admit that it's an abuse of setdefault. However, I often use setdefault to populate nested dictionaries, or dictionaries of sets or lists, e.g.: for x, y in somebiglist: bigdict.setdefault(x,set()).add(y) # Strips duplicates for x, y in somebiglist: bigdict.setdefault(x,[]).append(y) # Preserves duplicates To my mind, this latter is so much cleaner and clearer than any of the alternatives that it just isn't funny: for x, y in somebiglist: if x in bigdict: bigdict[x].append(y) else: bigdict[x] = [y] for x, y in somebiglist: if x not in bigdict: bigdict[x] = [] bigdict[x].append(y) for x, y in somebiglist: try: bigdict[x].append(y) except KeyError: bigdict[x] = [y] etc. Since I use setdefault in this manner quite often, I am very comfortable with it. On a single line I know what I am creating (list, dict, set, etc.), what the default value is, and how it is being modified. Because I am NOT a believer in the Perl idiom of TMTOWTDI, and because, TO ME, setdefault screams "This line is creating and subsequently modifying a dictionary entry", setdefault is absolutely my first choice for this particular task. Having said that, my enthusiasm for setdefault (for the given problem!) IS tempered somewhat by having to abuse a list as a mutable integer. That is the only reason that I concede that my solution is an abuse of setdefault, but the setdefault idiom is (to me) so clear and compelling that I view it as a toss-up whether to use a single line setdefault or an if/else in this case. And, as I mentioned earlier, if I had to do this same thing LOTS of times in a program, I most likely would code a class (perhaps not as fancy as a true mutable int, but certainly something with an increment method), because, IMO, it would be a lot cleaner (hmmm, maybe there's no style points in that) than tons and tons of if/else statements. Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
>> orderedDict = [(k,mydict[k]) for k in mydict.keys().sort()] >> >>Unfortunately, the version I've got here doesn't seem to support >>a sort() method for the list returned by keys(). :( > > I bet it does, but it doesn't do what you think it does. See > http://docs.python.org/lib/typesseq-mutable.html , in particular > note 7. > > What you want is the sorted() function (introduced in 2.4 IIRC). Kinda thought so. Yes...the sort() function doesn't return the results, but rather sorts in-place and returns nothing. The sorted() function was what I was reaching for, but only having 2.3.5 on the server at my finger tips, I couldn't verify that. So yes, it looks like the answer would be orderedDict = [(k,mydict[k]) for k in mydict.keys().sorted()] List comprehensions are such lovely things... :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: file_name_fixer.py
thanks for the feedback! I'll work on your suggestions. bruno at modulix wrote: > [EMAIL PROTECTED] wrote: > > i put this together to fix a bunch of files with wierd names, please > > gimme feedback, i am a newbie > > Ok, so let's go... Hope you won't hate me too much !-) > > > > > #!/usr/bin/env python > > import os > > import sys > > import string > > import platform > > dir = sys.argv[1] > This will shadow the builtin 'dir' function. > > > noworky = sys.argv[2] > > If the user fails to provide args, the program will crash with an > IndexError - which may not be very helpful. > > Also, a better scheme would be > myprog [-opt1 [-opt2=val [-optN]]] arg1 arg2 argN > > Hint: the optparse module is your friend > http://www.python.org/doc/2.4.2/lib/module-optparse.html > > > if platform.system() == 'Linux': > > uglychars = ''.join( set(string.punctuation+' ') - set('/_.') ) > > else: > > if platform.system() == 'Windows':#this is broken because windows > > is gay with case > > uglychars = ''.join( set(string.punctuation+' ') - > > set(':\\/_.') ) > > else: > > print "wtf... what platform is this anyway?" > > May be MacOS Classic, MacOS X or any *n*x or *BSD variant, or any other > platform supporting Python - are there are some... > > > underscore = '_' > > underscore = underscore * len(uglychars) > > You don't need the intermediate value: > underscores = '_' * len(uglychars) > > > chars = string.maketrans(uglychars, underscore) > > > print "# PHASE I, DIRECTORIES" > > Why not processing dirs and files in one pass ? > > > for path, subdirs, files in os.walk(dir, topdown=True): > > Err... is the 'dir' argument supposed to be an absolute path or a > relative path ? > > And why using the topdown option ? > > > oldname = path > > woops ! this may be the absolute path. Are you sure you want to process > an absolute path ? > > I think you'd better process files and dirs in one path, walking bottom > up (so you don't process any file twice). > > > newname = oldname.translate(chars) > > newname = string.lower(newname) > > Use the 'str' object methods instead of functions from the string module: > > newname = newname.lower() > > You can also chain method/function calls: > newname = oldname.translate(chars).lower() > > > > while string.count(newname, "__") > 0: > > in the context of a boolean expression, 0 evaluate to False, non-zero to > True. So you don't have to be so explicit: > while newname.count('__'): > > > newname = string.replace(newname,"__","_") > > You don't need to actually *count* the occurrences of '__' - if there's > one, that's enough: > while '__' in newname: > # proceed > > Also, a regexp may be more effective here. > > > while string.count(newname, "..") > 0: > > newname = string.replace(newname,"..",".") > > Don't forget the '..' and '.' special directories in unix filesystems... > > > if oldname != newname: > > if os.path.isfile(newname) or os.path.isdir(newname): > > And if there's a special file (device etc) ? > hint : os.path.exists() > > > > print oldname, "-->\n", newname, "\t\t\tERROR: file/dir > > exists\n" > > stdout is for 'normal' program outputs (ie: outputs that may be used as > inputs to another program). This kind of output should go to stderr: >print >> sys.stdout, "%s --> %s : \t\t\tERROR: " > "file/dir exists" % (oldname, > newname,) > > > else: > > print oldname, "-->\n", newname, "\t\t\tYAY: file > > renamed\n" > > if noworky == "doit": > > os.renames(oldname, newname) > > How is the user supposed to know that he has to pass the string "doit" > as a second arg ? > > There are some (more or less agreed upon) conventions about cli options. > Like '--dry-run' to express the fact that the program shouldn't actually > do more than simulate it's execution. > > > print "# PHASE II, FILES" > > for path, subdirs, files in os.walk(dir, topdown=True): > > for oldname in files: > > oldname = os.path.join(path, oldname) > > Are you *sure* you want to operate on the *whole* *absolute* path ? > (cf my thoughts about the "first phase" and the whole algorithm) > > > newname = oldname.translate(chars) > > newname = string.lower(newname) > > Aren't you repeating some code here ? > hint : all duplicated code should be factored out into a function. > > > newname = string.replace(newname,".mpeg",".mpg") > > newname = string.replace(newname,".ram",".rm") > > newname = string.replace(newname,".jpeg",".jpg") > > newname = string.replace(newname,".qt",".mov") > > # outside the loop, define a dict like: > ext_map = {'mpeg': 'mpg', >'ram' : 'rm', >'jpeg' : 'jpg', ># etc > } > > # then in the loop: > base, ext = os.path.split(n
Re: Using non-ascii symbols
Juho Schultz wrote: > Fortran 90 allowed >, >= instead of .GT., .GE. of Fortran 77. But F90 > uses ! as comment symbol and therefore need /= instead of != for > inequality. I guess just because they wanted. However, it is one more > needless detail to remember. Same with the suggested operators. The point is that it is just *not* the same. The suggested operators are universal symbols (unicode). Nobody would use ≠ as a comment sign. No need to remember was it .NE. or -ne or <> or != or /= ... There is also this old dispute of using "=" for both the assignment operator and equality and how it can confuse newcomers and cause errors. A consequent use of unicode could solve this problem: a ← b # Assignment (now "a = b" in Python, a := b in Pascal) a = b # Eqality (now "a == b" in Python, a = b in Pascal) a ≡ b # Identity (now "a is b" in Python, @a = @b in Pascal) a ≈ b # Approximately equal (may be interesting for floats) (I know this goes one step further as it is incompatible to the existing use of the = sign in Python). Another aspect: Supporting such symbols would also be in accord with Python's trait of being "executable pseudo code." -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
On Tue, 24 Jan 2006 16:33:16 +0200 in comp.lang.python, Juho Schultz <[EMAIL PROTECTED]> wrote: [...] > >Fortran 90 allowed >, >= instead of .GT., .GE. of Fortran 77. But F90 >uses ! as comment symbol and therefore need /= instead of != for >inequality. I guess just because they wanted. However, it is one more >needless detail to remember. Same with the suggested operators. C uses ! as a unary logical "not" operator, so != for "not equal" just seems to follow, um, logically. Pascal used <>, which intuitively (to me, anyway ;-) read "less than or greater than," i.e., "not equal." Perl programmers might see a spaceship. Modula-2 used # for "not equal." I guess that wouldn't work well in Python... Regards, -=Dave -- Change is inevitable, progress is not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
On Tue, 24 Jan 2006 04:09:00 +0100 in comp.lang.python, Christoph Zwerschke <[EMAIL PROTECTED]> wrote: [...] >Once you open your mind for using non-ascii symbols, I'm sure one can >find a bunch of useful applications. Variable names could be allowed to >be non-ascii, as in XML. Think class names in Arabian... Or you could >use Greek letters if you run out of one-letter variable names, just as >Mathematicians do. Would this be desirable or rather a horror scenario? The latter, IMHO. Especially variable names. Consider i vs. ì vs. í vs. î vs. ï vs. ... Regards, -=Dave -- Change is inevitable, progress is not. -- http://mail.python.org/mailman/listinfo/python-list
a 32 bit number to integer
Hi, In python 2.0, this number was an integer: 0x88776655 but in python 2.4 it is a long (every number > 0x7fff it is a long) in python 2.4, is there a way to convert that number to a integer (notice that it only occupies 32 bits) ? thanks, riq. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Robert Kern wrote: > Rocco Moretti wrote: > > [James Stroud wrote:] > >I can't find "?, ?, or ?" on my keyboard. >> >>Posting code to newsgroups might get harder too. :-) > > > His post made it through fine. Your newsreader messed it up. I'm not exactally sure what happened - I can see the three charachters just fine in your (Robert's) and the original (Christoph's) post. In Giovanni's post, they're rendered as question marks. My point still stands: _somewere_ along the way the rendering got messed up for _some_ people - something that wouldn't have happened with the <=, >= and != digraphs. (FWIW, my newsreader is Thunderbird 1.0.6.) -- http://mail.python.org/mailman/listinfo/python-list
Re: a 32 bit number to integer
Ricardo Quesada <[EMAIL PROTECTED]> writes: > 0x88776655 > > but in python 2.4 it is a long (every number > 0x7fff it is a long) > > in python 2.4, is there a way to convert that number to a integer > (notice that it only occupies 32 bits) ? It would be -2005440939 but that's maybe not what you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: a 32 bit number to integer
On Tue, 24 Jan 2006 13:23:05 -0300 in comp.lang.python, Ricardo Quesada <[EMAIL PROTECTED]> wrote: >Hi, > > In python 2.0, this number was an integer: >0x88776655 > > but in python 2.4 it is a long (every number > 0x7fff it is a long) > >in python 2.4, is there a way to convert that number to a integer >(notice that it only occupies 32 bits) ? Well, the sign bit's gonna be set no matter what. But the following might work for you... >>> def short(x): return int(0x8000 - x) >>> x = short(0x88776655) >>> x -142042709 >>> "%x"%x '-8776655' >>> Regards, -=Dave -- Change is inevitable, progress is not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Loading a Python collection from an text-file
Take a look at ConfigParser module. The format of the file would be something like: [members] peter=16 anton=21 People are accustomed to this format file (windows .ini format). -Larry Ilias Lazaridis wrote: > within a python script, I like to create a collection which I fill with > values from an external text-file (user editable). > > How is this accomplished the easiest way (if possible without the need > of libraries which are not part of the standard distribution)? > > something like: > > text-file: > {peter, 16}, > {anton, 21} > > - > > within code: > > users.load(text-file.txt) > > for user in users > user.name > user.age > > . > -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Christoph Zwerschke wrote: > Juho Schultz wrote: > >> Fortran 90 allowed >, >= instead of .GT., .GE. of Fortran 77. But F90 >> uses ! as comment symbol and therefore need /= instead of != for >> inequality. I guess just because they wanted. However, it is one more >> needless detail to remember. Same with the suggested operators. > > > The point is that it is just *not* the same. The suggested operators are > universal symbols (unicode). Nobody would use ≠ as a comment sign. No > need to remember was it .NE. or -ne or <> or != or /= ... > > There is also this old dispute of using "=" for both the assignment > operator and equality and how it can confuse newcomers and cause errors. > A consequent use of unicode could solve this problem: > Being involved in the discussion about assignment and looking for new terms which do not cause confusion when explaining what assignment does, this proposal seems to be a kind of solution: > a ← b # Assignment (now "a = b" in Python, a := b in Pascal) ^-- this seems to me to be still open for further proposals and discussion. There is no symbol coming to my mind, but I would be glad if it would express, that 'a' becomes a reference to a Python object being currently referred by the identifier 'b' (maybe some kind of <-> ?). > a = b # Eqality (now "a == b" in Python, a = b in Pascal) > a ≡ b # Identity (now "a is b" in Python, @a = @b in Pascal) > a ≈ b # Approximately equal (may be interesting for floats) ^-- this three seem to me to be obvious and don't need to be further discussed (only implemented as the time for such things will come). Claudio > > (I know this goes one step further as it is incompatible to the existing > use of the = sign in Python). > > Another aspect: Supporting such symbols would also be in accord with > Python's trait of being "executable pseudo code." > > -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with running external process
In article <[EMAIL PROTECTED]>, "ToMasz" <[EMAIL PROTECTED]> wrote: > No, no, that wasn't my intention (I'm just not conscious enough what's > going on with these fork, exec, spawn.. functions). > My parent process should start the child process and go back to it's > tasks. Before executing it for the next time the parent should check if > the previous child process is done and start it again. > > Is it what these lines do? > > os.spawnlp(os.P_NOWAIT,'ext_script.py','') > os.waitpid(-1, os.WNOHANG) No, do you see them doing it? "Check if the previous child process is done?" In your original post you said you were using os.P_WAIT, but I suppose you really were using os.P_NOWAIT all along, right? This case may call for a working sample program that makes a genuine attempt to do what you want to do. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Creating a more random int?
Hi all, I need to retrieve an integer from within a range ... this works ... below is my out puts ... it just does not seem so random ... Is there perhaps a suggestion out there to create a more random int ...? >>> random.randint(3, 8) 7 >>> random.randint(3, 8) 3 >>> random.randint(3, 8) 3 >>> random.randint(3, 8) 4 >>> random.randint(3, 8) 3 >>> random.randint(3, 8) 4 >>> random.randint(3, 8) 7 >>> random.randint(3, 8) 7 >>> random.randint(3, 8) 7 >>> random.randint(3, 8) 5 >>> random.randint(3, 8) 6 >>> random.randint(3, 8) 3 >>> random.randint(3, 8) 8 >>> random.randint(3, 8) 8 >>> random.randint(3, 8) 5 >>> random.randint(3, 8) 3 >>> random.randint(3, 8) 4 Regards, Steven -- http://mail.python.org/mailman/listinfo/python-list
customized instance dictionaries, anyone?
some time after posting my `Linkdict recipe`__ to aspn__ -- basically, a dictionary with run-time delegational lookup, but this is not important here -- i thought gee that would be fun to make such a customized dictionary thingie an instance dictionary, and get some custom namespace behavior out of that. .. __: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465748 .. __: http://aspn.activestate.com/ here is a simplified example: first, the customized dictionary class and a test:: class CustomDict( dict ): defaultValue = 'THIS ITEM NOT AVAILABLE' def __getitem__( self, name ): try: return super( CustomDict, self ).__getitem__( name ) except KeyError: return self.defaultValue def __contains__( self, name ): return True def has_key( self, name ): return True print '' cd = CustomDict( foo = 'bar' ) print cd[ 'foo' ] print cd[ 'bar' ] print 'bar' in cd print cd.has_key( 'bar' ) this gives us:: bar THIS ITEM NOT AVAILABLE True True so it appears to work. note that we may have failed to implement all the conceivable ways to test for membership (such as searching through ``keys()``) or to retrieve a value for a given key. more on that below. now for the class to utilize this definition:: class X( object ): def __init__( self ): self.__dict__ = CustomDict( foo = 'bar' ) and the test code for that:: print '' x = X() print x.__dict__[ 'foo' ] print x.__dict__[ 'bar' ] print x.foo print x.bar which yields:: bar THIS ITEM NOT AVAILABLE bar Traceback (most recent call last): File "C:\home\projects\__svn__\sundry\#.py", line 39, in ? print x.bar AttributeError: 'X' object has no attribute 'bar' ok. so the custom dict *basically* works as expected, since it does successfully make ``x.foo`` available -- no surprise here. unfortunately, looking up ``x.bar``, which should really return the default value string, causes an ``AttributeError`` to be raised. now of course given the short definition of ``CustomDict``, perhaps there is an essential lookup method that has not been overwritten but that is internally used for attribute lookup. however, i carefully tested my actual class (from the recipe mentioned above) and also compared the methods defined there against the standard ``dict()`` interface, and nothing of importance appeared to be missing. i also tried to bind the dictionary to the instance earlier, in ``__new__``, to no avail. am i missing something here? _wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a more random int?
"Steven Macintyre" <[EMAIL PROTECTED]> writes: > I need to retrieve an integer from within a range ... this works ... below > is my out puts ... it just does not seem so random ... It's pretty normal for random small ints to not look random. Are there some statistical tests that the prng is definitely failing? > Is there perhaps a suggestion out there to create a more random int ...? Try reading bytes from os.urandom and converting them to ints in your program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Some thougts on cartesian products
Bryan Olson wrote: > The claim "everything is a set" falls into the category of > 'not even wrong'. No, it falls into the category of the most fundamental Mathematical concepts. You actually *define* tuples as sets, or functions as sets or relations as sets, or even all kinds of numbers and other things which exist in the heads of Mathematicians as sets. > Watch things not be sets: > >x = [1, 1, 2] >y = [1, 2] >print x == y >print set(x) == set(y) Python tuples and lists are of course not the same as Python sets. But mathematically, you can understand them as sets anyway and associate every Python tuple with a Python set. The naive approach to understand a tuple as the set of its values which is done by casting to set() does not work, as you rightly noticed. The associated set to a Python tuple or list x would be set(enumerate(x)), not set(x). Generally, two approaches are common for constructing tuples as sets: (A) Think of an n-tuple as a function on the index set, range(n). Then remember a function is a special relation is a set. (1, 2, 2) would correspond to the set {(0, 1), (1, 1), (1, 2)} (1, 2) would correspond to the set {(0, 1), (1, 2)} In Python, the tuple or list x would correspond to set(enumerate(x)). As a sidemark, another common approach is this: (B) Define the set corresponding to (1, 2) as {1, 2}. Define the set corresponding to (1, 2, 2) as {{1, 2}, 2}, the set corresponding to (1, 2, 2, 4) as {{{1, 2}, 2}, 4} and so on. > I really did try to raise the real issues. I cannot make you answer, > but the question remains: are duplicate and order significant in > what you call "Cartesian product" or they not? Can you show that > your proposed language extensions are useful and consistent in > some reasonable sense? I already tried to answer. It is not what "I call" Cartesian product. Since functions are sets in Mathematics, once you have a Cartesian product on sets, there is a natural (canonical) way to define a Cartesian product on functions as well. So there is also a canonical way to define a Cartesian product on tuples, if you interpret tuples as functions via (A). And there is a canonical way to understand the resulting sets as tuples again (by the lexicographical order of the index set). So the cartesian product of a string, tuple, or list is well-defined including its order. The only ambiguity is whether the result should be a generator or a tuple, and in the case of strings whether the elements in the result should be returned as tuples, "ab"*"cd" = ("a", c"), ("a", "d"), ("b", "c"), ("b", "d") or concatenated as strings: "ab"*"cd" = "ac", "ad", "bc", "bd" In any way, there is no dispute about duplicates or ordering. This is all canonical and well-defined. Concerning the use, I admit there is no really frequent use, but in some occasions it may be useful and I already gave some examples. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a more random int?
Steven Macintyre wrote: > Hi all, > > I need to retrieve an integer from within a range ... this works ... below > is my out puts ... it just does not seem so random ... What's wrong with it? > > Is there perhaps a suggestion out there to create a more random int ...? What do you think the output should be? What's your criteria for "more random"? > > >>> random.randint(3, 8) > 7 > >>> random.randint(3, 8) > 3 > >>> random.randint(3, 8) > 3 > >>> random.randint(3, 8) > 4 > >>> random.randint(3, 8) > 3 > >>> random.randint(3, 8) > 4 > >>> random.randint(3, 8) > 7 > >>> random.randint(3, 8) > 7 > >>> random.randint(3, 8) > 7 > >>> random.randint(3, 8) > 5 > >>> random.randint(3, 8) > 6 > >>> random.randint(3, 8) > 3 > >>> random.randint(3, 8) > 8 > >>> random.randint(3, 8) > 8 > >>> random.randint(3, 8) > 5 > >>> random.randint(3, 8) > 3 > >>> random.randint(3, 8) > 4 > > Regards, > > > Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension
Patrick Maupin wrote: > Duncan Booth wrote: > >> I prefer writing an 'if' statement here, Bryan prefers 'get', that's >> just a choice of style. But 'setdefault' here, that has no style. > > Well, I'm often told I have no style, and I _did_ admit that it's an > abuse of setdefault. However, I often use setdefault to populate > nested dictionaries, or dictionaries of sets or lists, e.g.: > > for x, y in somebiglist: > bigdict.setdefault(x,set()).add(y) # Strips duplicates > > > for x, y in somebiglist: > bigdict.setdefault(x,[]).append(y) # Preserves duplicates > > To my mind, this latter is so much cleaner and clearer than any of the > alternatives that it just isn't funny: Yes, but storing a mutable is a not unreasonable use of setdefault. What I objected to was storing an immutable just to overwrite it immediately. Also, while I agree it is shorter, I'm not convinced that it is much cleaner, and it is likely to be slower if there are a lot of duplicates, possibly a lot slower if the mutable object has much overhead on its construction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a more random int?
> I need to retrieve an integer from within a range ... this > works ... below is my out puts ... it just does not seem so > random ... > > Is there perhaps a suggestion out there to create a more > random int ...? I'm not sure how you determine that "it just does not seem so random"...I tried the following: >>> import random >>> samples = 1 >>> x = [random.randint(3,8) for i in range(1,samples+1)] >>> s = 0 >>> for i,j,k in [(i,x.count(i), (samples/6.0)-x.count(i)) for i in range(3,9)]: ... print i,j,k ... s = s + k ... 3 1735 -68.33 4 1634 32.67 5 1608 58.67 6 1688 -21.33 7 1670 -3.333 8 1665 1.667 >>> s -5.6843418860808015e-14 It also seems to hover fairly closely about the mid-point in terms of distribution. Looks like a fairly decent sampling to me. Is there some statistical test it's failing for you? -tim -- http://mail.python.org/mailman/listinfo/python-list
Re: Some thougts on cartesian products
Bryan Olson wrote: > The claim "everything is a set" falls into the category of > 'not even wrong'. No, it falls into the category of the most fundamental Mathematical concepts. You actually *define* tuples as sets, or functions as sets or relations as sets, or even all kinds of numbers and other things, which exist only in the heads of Mathematicians, as sets. > Watch things not be sets: > >x = [1, 1, 2] >y = [1, 2] >print x == y >print set(x) == set(y) Python tuples and lists are of course not the same as Python sets. But mathematically, you can understand them as sets anyway and associate every Python tuple with a Python set. The naive approach to understand a list as the set of its values which is done by casting with set() does not work, as you rightly noticed. The associated set to a Python tuple or list x would be set(enumerate(x)), not set(x). Generally, two approaches are common for constructing tuples as sets: (A) Think of an n-tuple as a function on the index set, range(n). Then remember a function is a special relation is a set. (1, 2, 2) would correspond to the set {(0, 1), (1, 2), (2, 2)} (1, 2) would correspond to the set {(0, 1), (1, 2)} In Python, the tuple or list x would correspond to set(enumerate(x)). As a sidemark, another common approach is this: (B) Define the set corresponding to (1, 2) as {{1}, 2}. Define the set corresponding to (1, 2, 2) as {{{1}, 2}, 2}, the set corresponding to (1, 2, 2, 4) as 1}, 2}, 2}, 4} and so on. > I really did try to raise the real issues. I cannot make you answer, > but the question remains: are duplicate and order significant in > what you call "Cartesian product" or they not? Can you show that > your proposed language extensions are useful and consistent in > some reasonable sense? I already tried to answer. It is not what "I call" Cartesian product. If there is a canonical set representation of something like a function or a tuple you immediately have a well-defined Cartesian product on these things, and this would be also called Cartesian product. A Cartesian product of functions and tuples is a well-defined mathematical concept. The Cartesian product of functions is even a function again, and (via lexicographical order of the index set) you can also interpret the Cartesian product of tuples as a tuple again (this was probably the point where you had doubts, but I already tried to explain). The only ambiguity is whether the result should be a generator or a tuple, and in the case of strings whether the elements in the result should be returned as tuples, "ab"*"cd" = ("a", c"), ("a", "d"), ("b", "c"), ("b", "d") or concatenated as strings: "ab"*"cd" = "ac", "ad", "bc", "bd" In any way, there is no dispute about duplicates or ordering. This is all canonical and well-defined. Concerning the use, I admit there is no really frequent use, but in some occasions it may be useful and I already gave some examples. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Using non-ascii symbols
Rocco Moretti schrieb: > My point still stands: _somewere_ along the way the rendering got messed > up for _some_ people - something that wouldn't have happened with the > <=, >= and != digraphs. Yes, but Python is already a bit handicapped concerning posting code anyway because of its significant whitespace. Also, I believe once Python will support this, the editors will allow converting "digraphs" <=, >= and != to symbols back and forth, just as all editors learned to convert tabs to spaces back and forth... And newsreaders and mailers are also improving. Some years ago, I used to write all German Umlauts as digraphs because you could never be sure how they arrived. Nowadays, I'm using Umlauts as something very normal. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list