Building PIL under Cygwin & Python 2.5
This has apparently been a problematic thing for a while now, as the following article indicates. I first ran into the error message about not being able to remap C:\cygwin\bin\tk84.dll to be the same address as it's parent. Using that information, Google helped me find this article: http://blog.datahammer.info/2008/11/install-pil-under-cygwin-python-25.html After following it's advice and running: $ ./rebase -b 0x10 tk84.dll I was able to get the PIL build to proceed, but when it was done, it said that there was no support built for Tk, and I then noticed that basic Tkinter functionality was broken from the Python interpreter. I went back to Cygwin setup, and had it reinstall the tcl/tk package, and then Tkinter (import from the interactive interp.) got fixed. Googling some more, I found this article (which implied datahammer isn't quite right): http://www.pythonchallenge.com/forums/viewtopic.php?t=135 I ran /usr/bin/rebaseall (from ash)(and if you end up doing this yourself, be aware that it takes a while - I was afraid that process had hung and I was going to have to rebuild the whole Cygwin shooting match from scratch, but it eventually completed (silently)). After this, I checked that Tkinter still worked from Python (it did), and then tore out the whole PIL directory (Imaging-1.1.6) I had tried to install from before, re-extracted the tar file to get a clean install directory, and then again attempted to build PIL. Now, instead of getting the failure message about not being able to remap the dll, the build just hangs: $ python setup.py build_ext -i running build_ext building '_imaging' extension creating build creating build/temp.cygwin-1.5.25-i686-2.5 creating build/temp.cygwin-1.5.25-i686-2.5/libImaging gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict- prototypes -DHAVE_LIBJPEG -DHAVE_LIBZ -I/usr/include/freetype2 - IlibImaging -I/usr/include -I/home/ej/python/PIL/jpeg-6b -I/usr/ include/python2.5 -c _imaging.c -o build/temp.cygwin-1.5.25-i686-2.5/ _imaging.o Now, I'm rather stuck and I'm thinking "This really shouldn't be that hard." So, rebasing (rebaseall'ing) the cygwin system as outlined in the datahammer blog entry (along with the ash advice of the pychallenge article) still doesn't seem to be enough to get a clean build. I think this is an issue that probably needs to be addressed by PIL maintainers that fully understand the root of the problem (and it should probably go in the PIL FAQ), but in the meantime does anyone out there know how to get around this issue? Thanks, -ej -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: popen question
On May 27, 6:10 pm, thebiggestbangthe...@gmail.com wrote: > hello everyone :-), > I am a newbie to python. I am trying to run a > bash script from within a python program. I would greatly appreciate > any pointers/comments about how to get around the problem I am facing. > > I want to run bash script: code.sh from within a python program. > code.sh needs to be run like so from the command line > [code] > $ sudo code.sh arg1 arg2 > [/code] > > I read up on some documentation but am not very clear about how to use > popen. I want to relegate the shell to a background process, but it > needs to accept the sudo passwd too! > > I have tried > [code] > p = subprocess.Popen(['/bin/bash', 'sudo '+mypath+'code.sh '+arg1+' > '+arg2], > stdout=subprocess.PIPE, > stderr=subprocess.STDOUT) > [/code] > I tried some code from stackoverflow.com/questions/694000/why-doesnt- > subprocess-popen-always-return > > nothing really happens when this executes, the PIPE option pshes it to > the background and I can't push in the sudo passwd. Can someone please > give me an idea of how to go about this. > > To recap, I want to run a shell script, which needs to be started with > sudo, and then push it into the background. > > Thanks, > -A Your best bet is to make sudo not ask for a password. :) If you don't have the rights, then you can use pexpect to do what you want to do. http://pexpect.sourceforge.net/pexpect.html See the second example on that page. child = pexpect.spawn('scp foo myn...@host.example.com:.') child.expect ('Password:') child.sendline (mypassword) ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: popen question
On Thu, May 28, 2009 at 9:11 AM, Sean DiZazzo wrote: > On May 27, 6:10 pm, thebiggestbangthe...@gmail.com wrote: > > hello everyone :-), > > I am a newbie to python. I am trying to run a > > bash script from within a python program. I would greatly appreciate > > any pointers/comments about how to get around the problem I am facing. > > > > I want to run bash script: code.sh from within a python program. > > code.sh needs to be run like so from the command line > > [code] > > $ sudo code.sh arg1 arg2 > > [/code] > > > > I read up on some documentation but am not very clear about how to use > > popen. I want to relegate the shell to a background process, but it > > needs to accept the sudo passwd too! > > > > I have tried > > [code] > > p = subprocess.Popen(['/bin/bash', 'sudo '+mypath+'code.sh '+arg1+' > > '+arg2], > > stdout=subprocess.PIPE, > > stderr=subprocess.STDOUT) > > [/code] > > I tried some code from stackoverflow.com/questions/694000/why-doesnt- > > subprocess-popen-always-return > > > > nothing really happens when this executes, the PIPE option pshes it to > > the background and I can't push in the sudo passwd. Can someone please > > give me an idea of how to go about this. > > > > To recap, I want to run a shell script, which needs to be started with > > sudo, and then push it into the background. > > > > Thanks, > > -A > > Your best bet is to make sudo not ask for a password. :) If you > don't have the rights, then you can use pexpect to do what you want to > do. http://pexpect.sourceforge.net/pexpect.html > Whoah there. Pexpect, yes. Making sudo not ask for a password? Only if you tell sudo to only not ask for a password for _this_ file. Telling sudo to not require a password at all is asking for trouble. Also, modifying sudo to allow this script to run without a password would require that to be done on every machine that the OP wants to run on. OP: use pexpect. -- http://mail.python.org/mailman/listinfo/python-list
Re: nntplib.NNTPTemporaryError: 441 Article has no body -- just headers
Dennis Lee Bieber wrote: > On Wed, 27 May 2009 14:25:58 +0200, Jon Bendtsen > declaimed the following in gmane.comp.python.general: > >> 'From: r...@laerdal.dk\nsubject: testing\nNewsgroups: test\nBody: >> \n\n\nfoobar\n\n\n.\n\n\n' >> > I believe NNTP, like SMTP, requires \r\n line termination. I will try it, but why does it then work when it posts the file? The file is a std. unix file, so it should also only have \n line termination. -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
In message <0039e83c$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano wrote: > A good UI standard should mean that: > > * all functionality should be discoverable without reading the manual; Which means no scripting languages are allowed? -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On May 26, 9:07 am, Lacrima wrote: > I am new to python. > And now I am using trial version of Wing IDE. > But nobody mentioned it as a favourite editor. > So should I buy it when trial is expired or there are better choices? I use nothing but Wing. Their support is great as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, May 28, 2009 at 12:06:25AM EDT, Steven D'Aprano wrote: > On Wed, 27 May 2009 22:34:45 -0400, Chris Jones wrote: > > I'm unsure about a python editor for everyone but since acquiring > > habits takes time, I'm in favor of sticking to one editor for > > everything. > > Or use an editor which follows user interface standards, rather than > invents its own conventions for everything. That way you can trivially > swap from one compliant application to another compliant application. > > A good UI standard should mean that: > > * common tasks should use the same interface in any application that > supports that task; > > * all functionality should be discoverable without reading the manual; > > * the most common functions should be _trivially_ discoverable; > > * don't penalise the user for mistakes: as few actions as possible > should be irreversible, and those which are irreversible should > _effectively_ warn the user that they are irreversible; > > * simple interfaces are better than complicated interfaces (easy tasks > should be easy to perform); > > * but dumbing-down is not the same as simplifying (complicated tasks > should be possible); > > * if possible, all functionality should be capable of being performed > by either the mouse or keyboard. All valid points on the face of it, but doesn't the above rule out both vim and emacs? CJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Tkinter and popen problem
norseman wrote: > Peter Otten wrote: >> norseman wrote: >> >>> This was sent 5/19/09 and as yet has received no comments. >> >>> I'm resending just in case a new reader might have an answer. >> >> If you had posted two tiny scripts demonstrating your problem instead of >> the longwinded explanation I might have tinkered. > That's one of the problems - with Tkinter you don't get tiny files. :) Nonsense. The minimal Tkinter program is from Tkinter import Tk root = Tk() root.mainloop() The idea is that you remove everything but the parts relevant to your problem (or build a toy example from scratch). This makes it easier for a non-guru to verify a potential answer. That non-guru might even be yourself, by the way. > NOTE: program runs perfectly on both Linux and Windows XP Pro when run > from the keyboard. But not from another python program that wants the > phone line connected. (stdin/stdout) Gee... There is never a County > Lineman when needed is there Glen? :) It's not clear why you need to start the GUI at all as you seem to have control over boths scripts. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Steven D'Aprano writes: > * if possible, all functionality should be capable of being performed by > either the mouse or keyboard. I'd imagine that the requirement that *all* functionality can be performed with the mouse rules out many text editors. Almost the defining feature of a text editor is the ability to type text... which mostly happens with a keyboard. -- http://mail.python.org/mailman/listinfo/python-list
Unpack less values from function's return values
Hi, I'm using Python 2.5.2. I'm getting this error whenever I try to unpack less values from a function. ValueError: too many values to unpack I want to know if there is a way I can unpack less values returning from a function? Thanks, Rajat -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Esmail wrote: > LittleGrasshopper wrote: >> >> So what do you guys use, and why? Hopefully we can keep this civil. > > I use Emacs, just because I have been using this editor for > all sorts of things in the last 20+ years. > > I haven't been able to get the python mode to work for Windows A bug-report would be fine... :) In case you use python-mode.el, please refer to https://launchpad.net/python-mode Thanks Andreas Röhler -- https://code.launchpad.net/s-x-emacs-werkstatt/ > (do most of my work under Linux anyway), but other than that I'm > pretty happy with it :-) > > HTH, > Esmail > -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance and Design Question
imageguy wrote: I have an object the I would like to use as a base class. Some of the methods I would like to override completely, but others I would simply like to call the base class method and use the return value in the child method. The purpose here is to eliminate the duplication of valuable code in the parent, when I really just need the child to operate of a results of the parent. Consider the following two classes; class Parent(object): def process(self, value): retval = "Parent.result('%s')" % value return retval class Child(Parent): def __init__(self): Parent.__init__(self) def process(self, value): retval = "Child.result('%s')" % super(Child, self).process (value) return retval So foo = Child() print foo.process('the value') Child.result('Parent.result('the value')') Try this class Parent(object): def process(self, value): retval = "%s.result('%s')" % (self.__class__.__name__, value) return retval class Child(Parent): def __init__(self): Parent.__init__(self) foo = Child() print foo.process('the value') Child.result('the value'') Of course you cannot see the inheritance in the result, but I'm assuming you wanted only the instance class to be displayed. Jean-Michel -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Rhodri James wrote: > On Tue, 26 May 2009 14:22:29 +0100, Roy Smith wrote: > >> My pet peeve is syntax-aware editors which get things wrong. For >> example, >> the version of emacs I'm using now doesn't parse this properly: >> >> '''A triple-quoted string. Some editors won't get this right''' >> >> The solution is to change the outer quotes to double-quotes, but it >> annoys me when I have to change my code to appease a tool. > > It's the separate python-mode that gets this (and much else) wrong. > The Python mode that Ubuntu packages with emacs 22.2.1 works just > fine. > As it should do python-mode.el from https://launchpad.net/python-mode -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I sample randomly based on some probability(wightage)?
Op 2009-05-26, Arnaud Delobelle schreef : > Sumitava Mukherjee writes: > >> On May 26, 11:39 pm, Sumitava Mukherjee wrote: >>> Hi all, >>> I need to randomly sample from a list where all choices have weights >>> attached to them. The probability of them being choosen is dependent >>> on the weights. >>> If say Sample list of choices are [A,B,C,D,E] and weights of the same >>> are [0.895,0.567,0.765,0.890,0.60] when I draw (say 2) samples then I >>> want the likeliness of them being chosen be in the order : D>A>C>E>B > > You mean A > D > C > E > B > >>> In short I mean if prob of a H is .9 and probability of T be 0.1 then >>> if I draw 10 samples, 9 should be H and 1 should be T. >>> >>> I coudn't find a function in the module random that does so. >>> Please can someone guide me how the above could be implemented [either >>> through some function which exists and I don't know or pointers to >>> some code snippets which does so]? >> >> [Oh, I forgot to mention. I am looking for sampling without replacement.] > > If you do sampling without replacement, you need to know the exact > number of each of A, B, C, D, E in the sample, not just their relative > frequency. As far as I understand, you are given the exact number of each. It is one. The numbers given are not relative frequencies of appearance but weights to be attributed for picking them. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Rhodri James wrote: > On Wed, 27 May 2009 16:56:12 +0100, Bruno Desthuilliers > wrote: > >> Rhodri James a écrit : >>> On Tue, 26 May 2009 14:22:29 +0100, Roy Smith wrote: >>> My pet peeve is syntax-aware editors which get things wrong. For example, the version of emacs I'm using now doesn't parse this properly: '''A triple-quoted string. Some editors won't get this right''' The solution is to change the outer quotes to double-quotes, but it annoys me when I have to change my code to appease a tool. >>> It's the separate python-mode that gets this (and much else) wrong. >>> The Python mode that Ubuntu packages with emacs 22.2.1 works just >>> fine. >> >> On this point, indeed. But it also lacks almost every nice feature of >> the One True python-mode (or at least did last time I had to update >> this ... ubuntu box at work). > > That rather depends on your definition of "nice". The only feature of > python-mode.el that I miss in python.el is the ability to run pylint from > the menu, Thanks mentioning it, I'll cc this to python-m...@python.org and I'll get over that. The feature that caused me to uninstall > python-mode.el was its bloody-minded determination to regard '_' as a word > character, something which caused me more typing that it ever saved. > Its just one line to comment in python-mode.el, like this: ;; (modify-syntax-entry ?\_ "w" py-mode-syntax-table) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question in VB DLL COM event in Delphi Programming
Tan, Yih Hung wrote: I have a question regarding Delphi COM programming. I have a VB DLL (ActiveX COM DLL) and this DLL contain 2 classes, one is for normal client function calling, and the other one is events raised by this DLL to notify the client. Now, I would like to incorporate this DLL into Delphi (bind the DLL into Delphi program) so that when the events raised by this DLL, it can be capture in the Delphi program. I am new in Delphi and I would like to need your help or advice on this integration. I could send you the sample code in VB and the VB DLL if you need. Thanks in advance. This newsgroup is for the Python programming language. You'll have a better chance of help with Delphi from a Delphi newsgroup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiprocessing problem with producer/consumer
Wu Zhe wrote: I am writing a server program with one producer and multiple consumers, what confuses me is only the first task producer put into the queue gets consumed, after which tasks enqueued no longer get consumed, they remain in the queue forever. from multiprocessing import Process, Pool, Queue, cpu_count from http import httpserv def work(queue): while True: task = queue.get() if task is None: break time.sleep(5) The 'time' module hasn't been imported, so the worker raises an exception when it gets to this line and then terminates. print "task done:", task queue.put(None) class Manager: def __init__(self): self.queue = Queue() self.NUMBER_OF_PROCESSES = cpu_count() def start(self): self.workers = [Process(target=work, args=(self.queue,)) for i in xrange(self.NUMBER_OF_PROCESSES)] for w in self.workers Missing ":" on the end of the line. w.start() httpserv(self.queue) def reload(self): print "RELOAD" def stop(self): self.queue.put(None) for i in range(self.NUMBER_OF_PROCESS): Should be "self.NUMBER_OF_PROCESSES". self.workers[i].join() queue.close() Manager().start() The producer is a HTTP server which put a task in the queue once receive a request from the user. It seems that consumer processes are still blocked when there are new tasks in the queue, which is weird. P.S. Another two questions not relating to the above, I am not sure if it's better to put HTTP server in its own process other than the main process, if yes how can I make the main process keep running before all children processes end. Second question, what's the best way to stop the HTTP server gracefully? -- http://mail.python.org/mailman/listinfo/python-list
Re: download all mib files from a web page
On Wed, May 27, 2009 at 9:29 AM, powah wrote: > I want to download all mib files from the web page: > http://www.juniper.net/techpubs/software/junos/junos94/swconfig-net-mgmt/juniper-specific-mibs-junos-nm.html#jN18E19 > > All mib filenames are of this format: > www.juniper.net/techpubs ... .txt > > I write this program but has the following error. > Please help. > Thanks. > > [code] > #!/usr/bin/env python > import urllib2,os,urlparse > url="http://www.juniper.net/techpubs/software/junos/junos94/swconfig- > net-mgmt/juniper-specific-mibs-junos-nm.html#jN18E19" > page=urllib2.urlopen(url) > f=0 > links=[] > data=page.read().split("\n") > for item in data: > if "www.juniper.net/techpubs" in item: > httpind=item.index("www.juniper.net/techpubs") > item=item[httpind:] > #print "item " + item > ind=item.index("<") > links.append(item[:ind]) #grab all links > # download all links > for link in links: > print "link " + link > filename=link.split("/")[-1] > print "downloading ... " + filename > u=urllib2.urlopen(link) > p=u.read() > open(filename,"w").write(p) > [/code] > > $ ~/python/downloadjuniper.py > link > www.juniper.net/techpubs/software/junos/junos94/swconfig-net-mgmt/mib-jnx-user-aaa.txt > downloading ... mib-jnx-user-aaa.txt > Traceback (most recent call last): > File "/home/powah/python/downloadjuniper.py", line 20, in ? > u=urllib2.urlopen(link) > File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen > return _opener.open(url, data) > File "/usr/lib/python2.4/urllib2.py", line 350, in open > protocol = req.get_type() > File "/usr/lib/python2.4/urllib2.py", line 233, in get_type > raise ValueError, "unknown url type: %s" % self.__original > ValueError: unknown url type: > www.juniper.net/techpubs/software/junos/junos94/swconfig-net-mgmt/mib-jnx-user-aaa.txt You need to ensure that all URL strings include the protocol to use, i.e. "http://"; Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: download all mib files from a web page
On Wed, May 27, 2009 at 11:06 AM, powah wrote: > On May 27, 12:29 pm, powah wrote: >> I want to download all mib files from the web >> page:http://www.juniper.net/techpubs/software/junos/junos94/swconfig-net-m... >> >> All mib filenames are of this format:www.juniper.net/techpubs... .txt >> >> I write this program but has the following error. >> Please help. >> Thanks. >> >> [code] >> #!/usr/bin/env python >> import urllib2,os,urlparse >> url="http://www.juniper.net/techpubs/software/junos/junos94/swconfig- >> net-mgmt/juniper-specific-mibs-junos-nm.html#jN18E19" >> page=urllib2.urlopen(url) >> f=0 >> links=[] >> data=page.read().split("\n") >> for item in data: >> if "www.juniper.net/techpubs" in item: >> httpind=item.index("www.juniper.net/techpubs") >> item=item[httpind:] >> #print "item " + item >> ind=item.index("<") >> links.append(item[:ind]) #grab all links >> # download all links >> for link in links: >> print "link " + link >> filename=link.split("/")[-1] >> print "downloading ... " + filename >> u=urllib2.urlopen(link) >> p=u.read() >> open(filename,"w").write(p) >> [/code] >> >> $ ~/python/downloadjuniper.py >> linkwww.juniper.net/techpubs/software/junos/junos94/swconfig-net-mgmt/mib... >> downloading ... mib-jnx-user-aaa.txt >> Traceback (most recent call last): >> File "/home/powah/python/downloadjuniper.py", line 20, in ? >> u=urllib2.urlopen(link) >> File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen >> return _opener.open(url, data) >> File "/usr/lib/python2.4/urllib2.py", line 350, in open >> protocol = req.get_type() >> File "/usr/lib/python2.4/urllib2.py", line 233, in get_type >> raise ValueError, "unknown url type: %s" % self.__original >> ValueError: unknown url >> type:www.juniper.net/techpubs/software/junos/junos94/swconfig-net-mgmt/mib... >> >> $ python >> Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >> [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >> >> >> My computer is FC6 linux. > > I fixed one error, now if the filename is misspelled, how to ignore > the error and continue? Read the fine tutorial: http://docs.python.org/tutorial/errors.html Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Tkinter and popen problem
norseman wrote: Peter Otten wrote: norseman wrote: This was sent 5/19/09 and as yet has received no comments. I'm resending just in case a new reader might have an answer. If you had posted two tiny scripts demonstrating your problem instead of the longwinded explanation I might have tinkered. Peter -- Since it got lost: Python 2.5.2 with Tkinter in the download package Linux Slackware 10.2 That's one of the problems - with Tkinter you don't get tiny files. :) [snip] You're more likely to get help if you provide the minimum code that demonstrates the problem. Anyway, your original post said that you're running the child with os.popen. The documentation says: """Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.""" In other words, it's one-way. Are you really using os.popen and not, say, os.popen2? (Providing actual code would make this clear.) -- http://mail.python.org/mailman/listinfo/python-list
Resize ctypes array
I'd like to resize a ctypes array. As you can see, ctypes.resize doesn't work like it could. I can write a function to resize an array, but I wanted to know some other solutions to this. Maybe I'm missing some ctypes trick or maybe I simply used resize wrong. The name c_long_Array_0 seems to tell me this may not work like I want. What is resize meant for? >>> from ctypes import * >>> c_int * 0 >>> intType = c_int * 0 >>> foo = intType() >>> foo <__main__.c_long_Array_0 object at 0xb7ed9e84> >>> foo[0] Traceback (most recent call last): File "", line 1, in IndexError: invalid index >>> resize(foo, sizeof(c_int * 1)) >>> foo[0] Traceback (most recent call last): File "", line 1, in IndexError: invalid index >>> foo <__main__.c_long_Array_0 object at 0xb7ed9e84> Maybe go with something like: >>> ctypes_resize = resize >>> def resize(arr, type): ... tmp = type() ... for i in range(len(arr)): ... tmp[i] = arr[i] ... return tmp ... ... >>> listType = c_int * 0 >>> list = listType() >>> list = resize(list, c_int * 1) >>> list[0] 0 >>> But that's ugly passing the type instead of the size. It works for its purpose and that's it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Resize ctypes array
I found an answer to this over on Stackoverflow. http://stackoverflow.com/questions/919369/resize-ctypes-array On Thu, May 28, 2009 at 1:25 AM, Scott Sibley wrote: > I'd like to resize a ctypes array. As you can see, ctypes.resize doesn't > work like it could. I can write a function to resize an array, but I wanted > to know some other solutions to this. Maybe I'm missing some ctypes trick or > maybe I simply used resize wrong. The name c_long_Array_0 seems to tell me > this may not work like I want. What is resize meant for? > > >>> from ctypes import * > >>> c_int * 0 > > > >>> intType = c_int * 0 > >>> foo = intType() > >>> foo > <__main__.c_long_Array_0 object at 0xb7ed9e84> > >>> foo[0] > Traceback (most recent call last): > > > File "", line 1, in > > IndexError: invalid index > >>> resize(foo, sizeof(c_int * 1)) > > >>> foo[0] > Traceback (most recent call last): > > > File "", line 1, in > > IndexError: invalid index > >>> foo > <__main__.c_long_Array_0 object at 0xb7ed9e84> > > > Maybe go with something like: > > >>> ctypes_resize = resize > >>> def resize(arr, type): > > ... tmp = type() > ... for i in range(len(arr)): > > ... tmp[i] = arr[i] > ... return tmp > ... > ... > >>> listType = c_int * 0 > >>> list = listType() > >>> list = resize(list, c_int * 1) > > >>> list[0] > 0 > >>> > > > But that's ugly passing the type instead of the size. It works for its > purpose and that's it. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpack less values from function's return values
On Thu, May 28, 2009 at 3:19 AM, wrote: > Hi, > > I'm using Python 2.5.2. I'm getting this error whenever I try to unpack less > values from a function. > > ValueError: too many values to unpack > > > I want to know if there is a way I can unpack less values returning from a > function? Unpack them into throwaway variables: def foo(): return 1,2,3,4 a, b, _, _ = foo() In very new Python, you can also do: a, b, *_ = foo() Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance and Design Question
On Wed, 27 May 2009 17:21:23 -0400, Terry Reedy wrote: > super() was designed for multiple inheritance. Surely you mean that super() was designed for *inheritance*, multiple or singular? Working with single inheritance is part of the design, not an accident of implementation. > The only reason I know > to use it with single inheritance it to save a > global-search-and-replace_with_confirmation if you change the name of > the parent or change parents. How about these reasons? (1) If you're subclassing something you didn't write, you might not know whether it uses multiple or single inheritance. (2) Even if you do know, you shouldn't care what the implementation of the parent is. Using super() allows you to be agnostic about the implementation, while calling Parent.method() directly ties you to a specific implementation. (3) Your callers may want to inherit from your class, and if you fail to use super, you are condemning them to potentially buggy code if they use multiple inheritance. (4) Using super() is no harder than avoiding super(). It takes a few extra characters to type, at worst: super(MyClass, self).method(args) Parent.method(self, args) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: DB-API execute params, am I missing something?
In message , Dennis Lee Bieber wrote: > On Thu, 28 May 2009 13:12:57 +1200, Lawrence D'Oliveiro > declaimed the following in > gmane.comp.python.general: > >> >> What if the string you're searching for includes a "%" or "_" character? > >>>> db.literal((... "%wildcard%" ...)) >(... "'%wildcard%'" ...) Doesn't look like it worked, does it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Building Python with icc on 64-bit Linux
Konrad Hinsen wrote: /home/shr/khinsen/tmp/Python-2.6.2/Modules/_ctypes/libffi/src/x86/ffi64.c(43): \ error: identifier "__int128_t" is undefined __int128_t sse[MAX_SSE_REGS]; ^ compilation aborted for /home/shr/khinsen/tmp/Python-2.6.2/Modules/_ctypes/libf\ fi/src/x86/ffi64.c (code 2) That seems like a libffi configure failure (not properly handling 128bit integers on this compiler/platform). and failed test: test test_cmath failed -- Traceback (most recent call last): File "/home/shr/khinsen/tmp/Python-2.6.2/Lib/test/test_cmath.py", line 366, i\ n test_specific_values self.fail(error_message) AssertionError: acos: acos(complex(0.0, 0.0)) Expected: complex(1.5707963267948966, -0.0) Received: complex(1.5707963267948966, 0.0) Received value insufficiently close to expected value. I've seen this on other compilers/platforms. The floating point support in 2.6 is being more rigorously tested. This compiler/platform/math lib doesn't seem to be explicitly handling -0.0 as different from 0.0. test_math has other similar failures. Adding optimization yields even more failed tests. My configuration options are: configure --prefix=$HOME CC=icc CXX=icc OPT=-O0 Did anyone encounter these problems before? Any solutions? For the FP issues I wonder whether there's a compiler option that affects how -0.0 is handled, or possibly a different math library? The libffi issue would require delving into the libffi source and adjusting its configure script to properly handle the problematic case. Unless you need ctypes, this may be something you can skip over... -- - Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andy...@bullseye.apana.org.au (pref) | Snail: PO Box 370 andy...@pcug.org.au (alt) |Belconnen ACT 2616 Web:http://www.andymac.org/ |Australia -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI Programming
On Sunday 12 April 2009 15:07:11 Gabriel wrote: > I'm python newbie and i need to write gui for my school work in python. > I need to write it really quick, because i haven't much time .) Try Tkinter, which is included by default with most Python installations. Writing simple programs is easy like: from Tkinter import * root=Tk() w=Label(root, text="Hello, world!") w.pack() root.mainloop() See the tutorial at http://www.pythonware.com/library/tkinter/introduction/hello-tkinter.htm Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, 28 May 2009 05:44:07 -0400, Chris Jones wrote: >> * if possible, all functionality should be capable of being performed >> by either the mouse or keyboard. > > All valid points on the face of it, but doesn't the above rule out both > vim and emacs? Your point is? *ducks and runs* -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, 28 May 2009 11:08:08 +0100, Paul Rudin wrote: > Steven D'Aprano writes: > > >> * if possible, all functionality should be capable of being performed >> by either the mouse or keyboard. > > I'd imagine that the requirement that *all* functionality can be > performed with the mouse rules out many text editors. Almost the > defining feature of a text editor is the ability to type text... which > mostly happens with a keyboard. Likewise graphics editors -- it's difficult if not impossible to edit an image pixel by pixel using the keyboard. Hence the "if possible". (Aside: It's really discouraging that, even on a technical newsgroup where most of the people are relatively intelligent, the provisos and qualifications I give seem to be ignored in favour of an unrealistically extreme interpretation.) I do recall once in the mid 1980s, using a Macintosh with a broken keyboard. I was actually able to get useful work done by clicking letters on a virtual keyboard (the "Keyboard" desk accessory for those who remember it) and copying and pasting the text into the editor. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, 28 May 2009 20:58:07 +1200, Lawrence D'Oliveiro wrote: > In message <0039e83c$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano > wrote: > >> A good UI standard should mean that: >> >> * all functionality should be discoverable without reading the manual; > > Which means no scripting languages are allowed? "Should", not "must". In any case, once you've scripted some particular piece of functionality, the application should allow you to discover the existence of that script. Does the application have a "Scripts" or "Plugins" menu (or equivalent)? Or do you have to rummage around in the file system, looking for secret scripts in undocumented locations? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, May 28, 2009 at 7:09 AM, Andreas Roehler wrote: > Rhodri James wrote: >> and I'll get over that. The feature that caused me to uninstall >> python-mode.el was its bloody-minded determination to regard '_' as a word >> character, something which caused me more typing that it ever saved. > > Its just one line to comment in python-mode.el, like this: > > ;; (modify-syntax-entry ?\_ "w" py-mode-syntax-table) > Not really a good idea to make minor changes to distributed elisp. You'll have to keep redoing the change every time a new version comes out. Better to put something like this in your .emacs file. (eval-after-load "python-mode" '(modify-syntax-entry ?\_ " " py-mode-syntax-table)) -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, May 28, 2009 at 07:38:33AM EDT, Steven D'Aprano wrote: > Your point is? notepad, otoh.. > *ducks and runs* .. likewise. -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Thu, 28 May 2009 06:24:56 +0100, Paul Rudin wrote: "Rhodri James" writes: The feature that caused me to uninstall python-mode.el was its bloody-minded determination to regard '_' as a word character, something which caused me more typing that it ever saved. Probably you could have changed this in a few minutes. Or does fiddling with emacs lisp invalidate your python programmer's licence? ;-) I probably could, but uninstalling didn't even require that much brain-power, and as I said I only missed one feature (and that not much). -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: popen question
> Your best bet is to make sudo not ask for a password. :) If you > don't have the rights, then you can use pexpect to do what you want to > do. http://pexpect.sourceforge.net/pexpect.html > > See the second example on that page. > > child = pexpect.spawn('scp foo myn...@host.example.com:.') > child.expect ('Password:') > child.sendline (mypassword) The sudo password prompt is very configurable, so changing the configuration to allow execution without password input is really the best option. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Andreas Roehler wrote: Esmail wrote: LittleGrasshopper wrote: So what do you guys use, and why? Hopefully we can keep this civil. I use Emacs, just because I have been using this editor for all sorts of things in the last 20+ years. I haven't been able to get the python mode to work for Windows A bug-report would be fine... :) In case you use python-mode.el, please refer to https://launchpad.net/python-mode Hi, This got me to waste a bunch of time first with (add-to-list) unsuccessfully before I checked to see if there was an update to emacs distribution/bundle I use under Windows, which is http://vgoulet.act.ulaval.ca/en/ressources/emacs/windows Using its default .emacs I was able to get the python mode to work fine. (I suspect there was something off in my ancient .emacs file which I had been porting from system to system in the last 10 years or so). Glad this thread motivated me to upgrade/check on this. Regards, Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
I use Eclipse (www.eclipse.org) with the PyDev plugin (pydev.sourceforge.net). -- http://mail.python.org/mailman/listinfo/python-list
[pyunit] Only run one specific test
Hi, Consider these two files: , mytest.py - | #!/usr/bin/env python | import unittest | | class myTestCase(unittest.TestCase): | def test_foo(self): | pass | | # Somehow important according to pyunit documentation | def suite(): | return unittest.makeSuite(myTestCase) ` , runtest --- | #!/usr/bin/env python | import unittest | | # Find and import tests | modules_to_test = [ "mytest" ] | map(__import__, modules_to_test) | | # Runs all tests in test/ directory | def suite(): | alltests = unittest.TestSuite() | for name in modules_to_test: | alltests.addTest(unittest.findTestCases(sys.modules[name])) | return alltests | | if __name__ == '__main__': | unittest.main(defaultTest='suite') ` if I run runtest without arguments, it works. But according to runtest --help, I should also be able to do , | $ ./runtest mytest | Traceback (most recent call last): | File "./runtest", line 20, in | unittest.main() | File "/usr/lib/python2.6/unittest.py", line 816, in __init__ | self.parseArgs(argv) | File "/usr/lib/python2.6/unittest.py", line 843, in parseArgs | self.createTests() | File "/usr/lib/python2.6/unittest.py", line 849, in createTests | self.module) | File "/usr/lib/python2.6/unittest.py", line 613, in loadTestsFromNames | suites = [self.loadTestsFromName(name, module) for name in names] | File "/usr/lib/python2.6/unittest.py", line 584, in loadTestsFromName | parent, obj = obj, getattr(obj, part) | AttributeError: 'module' object has no attribute 'mytest' ` Why doesn't this work? Best, -Nikolaus -- »Time flies like an arrow, fruit flies like a Banana.« PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Or you can try pyscripter http://code.google.com/p/pyscripter/ Very fast, lightwieght and powerfull python editor. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to reuse TCP listening socket immediately after it was connected at least once?
Roy Smith wrote: > In article , > Lawrence D'Oliveiro wrote: >> The right thing to do is try to ensure that all your connections are >> properly closed at shutdown. That may not be enough (if your server crashes >> due to bugs), so the other thing you need to do is retry the socket open, >> say, at 30-second intervals, until it succeeds. > That may be a reasonable thing to do for production code, but when you're > building and debugging a server, it's a real pain to not be able to restart > it quickly whenever you want (or need) to. Speaking as a sysadmin, running applications for production, programs not using SO_REUSEADDR should be taken out and shot. You *can't* ensure that TCP connections are "properly closed". For example, a *client* crashing, or otherwise becoming unreachable, will leave TCP connections unclosed, no matter what you do. Not using SO_REUSEADDR means forcing a service interruption of half an hour (IIRC) if for some reason the service must be restarted, or having to reboot the entire machine. No thanks. I have been in that situation. -- Thomas Bellman, Lysator Academic Computer Club, Linköping University "Never let your sense of morals prevent you! Sweden ; +46-13 177780 from doing what is right." -- Salvor Hardin ! bell...@lysator.liu.se -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpack less values from function's return values
On May 28, 5:40 am, Chris Rebert wrote: > On Thu, May 28, 2009 at 3:19 AM, wrote: > > Hi, > > > I'm using Python 2.5.2. I'm getting this error whenever I try to unpack less > > values from a function. > > > ValueError: too many values to unpack > > > I want to know if there is a way I can unpack less values returning from a > > function? > > Unpack them into throwaway variables: > > def foo(): return 1,2,3,4 > > a, b, _, _ = foo() > > In very new Python, you can also do: > > a, b, *_ = foo() > > Cheers, > Chris > --http://blog.rebertia.com You could also do something like a,b = foo()[:2] -- http://mail.python.org/mailman/listinfo/python-list
Re: 4 hundred quadrillonth?
In article <4a1da210$0$90265$14726...@news.sunsite.dk>, Mark Dickinson wrote: > >This is getting rather long. Perhaps I should put the above comments >together into a 'post-PEP' document. Yes, you should. Better explanation of floating point benefits everyone when widely available. I even learned a little bit here and I've been following this stuff for a while (though by no means any kind of numerical expert). -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 1993 -- http://mail.python.org/mailman/listinfo/python-list
Most pythonic way to truncate unicode?
I need to ... 1) Truncate long unicode (UTF-8) strings based on their length in BYTES. For example, u'\u4000\u4001\u4002 abc' has a length of 7 but takes up 13 bytes. Since u'\u4000' takes up 3 bytes, I want truncate (u'\u4000\u4001\u4002 abc',3) == u'\u4000' -- as compared to u'\u4000\u4001\u4002 abc'[:3] == u'\u4000\u4001\u4002'. 2) I don't want to accidentally chop any unicode characters in half. If the byte truncate length would normally cut a unicode character in 2, then I just want to drop the whole character, not leave an orphaned byte. So truncate(u'\u4000\u4001\u4002 abc',4) == u'\u4000' ... as opposed to getting UnicodeDecodeError. I'm using Python2.6, so I have access to things like bytearray. Are there any built-in ways to do something like this already? Or do I just have to iterate over the unicode string? -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
I use Emacs, as for the other editing activities. I like it for it is very powerfull. -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Re: Most pythonic way to truncate unicode?
Andrew Fong wrote: > I need to ... > > 1) Truncate long unicode (UTF-8) strings based on their length in > BYTES. For example, u'\u4000\u4001\u4002 abc' has a length of 7 but > takes up 13 bytes. Since u'\u4000' takes up 3 bytes, I want truncate > (u'\u4000\u4001\u4002 abc',3) == u'\u4000' -- as compared to > u'\u4000\u4001\u4002 abc'[:3] == u'\u4000\u4001\u4002'. > > 2) I don't want to accidentally chop any unicode characters in half. > If the byte truncate length would normally cut a unicode character in > 2, then I just want to drop the whole character, not leave an orphaned > byte. So truncate(u'\u4000\u4001\u4002 abc',4) == u'\u4000' ... as > opposed to getting UnicodeDecodeError. > > I'm using Python2.6, so I have access to things like bytearray. Are > there any built-in ways to do something like this already? Or do I > just have to iterate over the unicode string? How about >>> u"äöü".encode("utf8")[:5].decode("utf8", "ignore") u'\xe4\xf6' >>> print _ äö Peter -- http://mail.python.org/mailman/listinfo/python-list
Deletion/record visibility error in PG with Python...
Hi! PGSQL makes me crazy... I port my apps to PGSQL, and I near to finish - but I got this problem... Params: PGSQL 8.3, Windows, Pylons, PGDB, DBUTILS... I opened the connection with DBUTILS. I have one thread (the test thread), possible it have more in the background, I don't know... See this pseudocode: start trs ("rollback; begin;") delete old recs insert new recs commit I delete all of old records with: "delete from levelfo where level = :level" This I do in one transaction that protect the next sequences to. Later I want to insert the records, BUT: def GetCodes(reks): l = [] for rek in reks: l.append(str(rek['KOD'])) return str(l) def LogInsertedReks(Index): csql = "select * from levelfo where level=%d" % self.LevelRek['KOD'] self.Cur.execute(csql) reks = dwdb.FetchAll(self.Cur) self.log.info(Index + ' INSERTED REKS ') self.log.info('%s' % GetCodes(reks)) for levelforek in self.LevelFoReks: LogInsertedReks('Start1') LogInsertedReks('Start2') LogInsertedReks('Start3') LogInsertedReks('Start4') LogInsertedReks('Start5') LogInsertedReks('Start6') kod = levelforek['KOD'] self.log.info(' INSERT ') self.log.info('%s' % levelforek['KOD']) LogInsertedReks('Start7') LogInsertedReks('Start8') LogInsertedReks('Start9') See this log: 18:07:02,276 INFO [xxx] Start1 INSERTED REKS 18:07:02,276 INFO [xxx] [] 18:07:02,292 INFO [xxx] Start2 INSERTED REKS 18:07:02,292 INFO [xxx] [] 18:07:02,292 INFO [xxx] Start3 INSERTED REKS 18:07:02,292 INFO [xxx] [] 18:07:02,306 INFO [xxx] Start4 INSERTED REKS 18:07:02,306 INFO [xxx] [] 18:07:02,306 INFO [xxx] Start5 INSERTED REKS 18:07:02,306 INFO [xxx] [] 18:07:02,306 INFO [xxx] Start6 INSERTED REKS 18:07:02,306 INFO [xxx] [] 18:07:02,306 INFO [xxx] INSERT 18:07:02,306 INFO [xxx] 11551 18:07:02,306 INFO [xxx] Start7 INSERTED REKS 18:07:02,306 INFO [xxx] [] 18:07:02,619 INFO [xxx] Start8 INSERTED REKS 18:07:02,619 INFO [xxx] ['11555', '11556', '11557', '11558'] 18:07:02,634 INFO [xxx] Start9 INSERTED REKS 18:07:02,634 INFO [xxx] ['11555', '11556', '11557', '11558'] 18:07:02,697 INFO [xxx] After UID INSERTED REKS 18:07:02,697 INFO [xxx] ['11555', '11556', '11557', '11558'] As you see, I don't do anything (like db operations), and deleted records are appearing... H... possible is it a cursor changing? When I change my logger to see the object ids, I can see the cursor changing (in the background): 18:21:29,134 INFO [xxx] Start7 INSERTED REKS 18:21:29,134 INFO [xxx] [] 18:21:29,134 INFO [xxx] Start7 CURSOR INFO 18:21:29,134 INFO [xxx] [] 18:21:29,134 INFO [xxx] [] ** 18:21:29,134 INFO [xxx] [] 18:21:29,431 INFO [xxx] Start8 INSERTED REKS 18:21:29,431 INFO [xxx] ['11555', '11556', '11557', '11558'] 18:21:29,431 INFO [xxx] Start8 CURSOR INFO 18:21:29,431 INFO [xxx] [] 18:21:29,431 INFO [xxx] [] ** 18:21:29,431 INFO [xxx] [] What happened? How I can avoid the cursor changing? How to fix it in my transaction? I never ask for new cursor, I used same variable in all of my context (self.Cur)... :-( So what is the solution? Drop DBUtils? Or what? Thanks for your help: dd -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: popen question
On May 28, 5:31 am, Sebastian Wiesner wrote: > > > > Your best bet is to make sudo not ask for a password. :) If you > > don't have the rights, then you can use pexpect to do what you want to > > do. http://pexpect.sourceforge.net/pexpect.html > > > See the second example on that page. > > > child = pexpect.spawn('scp foo myn...@host.example.com:.') > > child.expect ('Password:') > > child.sendline (mypassword) > > The sudo password prompt is very configurable, so changing the configuration > to allow execution without password input is really the best option. > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) Thanks guys for helping out! very good answers :-) Before I saw your answers, I tried the following, output = subprocess.Popen(["sudo","-b", "code.sh", "arg1"], stdout=subprocess.PIPE).communicate()[0] This seemed to push the shell execution process to the background and because my python program was invoked initially with sudo, it seems I did not need to enter a passwd again. Any comments about this..any issues that you see will crop up? Thanks a ton again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding a Par construct to Python?
On May 27, 11:07 pm, Steven D'Aprano wrote: > On Wed, 27 May 2009 12:58:02 +, Albert van der Horst wrote: > > >>And how is reduce() supposed to know whether or not some arbitrary > >>function is commutative? > > > Why would it or need it? A Python that understands the ``par'' keyword > > is supposed to know it can play some tricks with optimizing reduce() if > > the specific function is commutative. > > Fine. Move the smarts out of reduce() into the compiler. How is the > compiler supposed to know if an arbitrary function is commutative? Unit testing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking old post on developers who like IDEs vs developers who like simple languages
On Mon, May 18, 2009 at 12:31 AM, Ulrich Eckhardt wrote: > Steve Ferg wrote: > > On the one hand, there are developers who love big IDEs with lots of > > features (code generation, error checking, etc.), and rely on them to > > provide the high level of support needed to be reasonably productive > > in heavy-weight languages (e.g. Java). > > > > On the other hand there are developers who much prefer to keep things > > light-weight and simple. They like clean high-level languages (e.g. > > Python) which are compact enough that you can keep the whole language > > in your head, and require only a good text editor to be used > > effectively. > > This distinction is IMHO not correct. If you took a look at Java, you would > notice that the core language syntax is much simpler than Python's. OTOH, > if you add the standard libraries, you would soon see that Python's > libraries are not as consistent (i.e. conformant to PEP8) as Java's. > > What makes up for Python's perceived usability problems though is the > commandline parser that allows you to inspect the type of an object and its > parts of it at runtime, in particular the docstrings are a treasure there. > > That said, an IDE that provides auto-completion (e.g. that gives you a list > of available class members) is a good thing in Java, because you don't have > to browse the documentation as often. With Python, that is impossible > because there are no types bound to parameters, so any type that fits is > allowed (duck typing). > I just downloaded the Aptana IDE which has Python support and I have not tried it yet. But I remebered seeing this thread. Has anyone used the Aptana IDE for Python development ? thanks mohan > > Uli > > -- > Sator Laser GmbH > Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
py2app and OpenGL, "No module named util" in ctypes
I'm trying to use py2app to package an OpenGL app, so first I tried to build the example here http://svn.pythonmac.org/py2app/py2app/trunk/examples/PyOpenGL/ and I get the error: > File > "/opt/local/lib/python2.5/site-packages/PyOpenGL-3.0.0c1-py2.5.egg/OpenGL/platform/darwin.py", > line 24, in >import ctypes, ctypes.util >ImportError: No module named util >2009-05-28 13:55:06.819 lesson5[19965:10b] lesson5 Error >2009-05-28 13:55:06.821 lesson5[19965:10b] lesson5 Error >An unexpected error has occurred during execution of the main script > >ImportError: No module named util But when I open up my python interactive interpreter and "import ctypes.util", it works fine (using lesson5.app/Contents/MacOS/python, too). Thanks for the help. -tom -- http://mail.python.org/mailman/listinfo/python-list
Re: [pyunit] Only run one specific test
Nikolaus Rath wrote: Hi, Consider these two files: , mytest.py - | #!/usr/bin/env python | import unittest | | class myTestCase(unittest.TestCase): | def test_foo(self): | pass | | # Somehow important according to pyunit documentation | def suite(): | return unittest.makeSuite(myTestCase) ` , runtest --- | #!/usr/bin/env python | import unittest | | # Find and import tests | modules_to_test = [ "mytest" ] | map(__import__, modules_to_test) | | # Runs all tests in test/ directory | def suite(): | alltests = unittest.TestSuite() | for name in modules_to_test: | alltests.addTest(unittest.findTestCases(sys.modules[name])) | return alltests | | if __name__ == '__main__': | unittest.main(defaultTest='suite') ` if I run runtest without arguments, it works. But according to runtest --help, I should also be able to do , | $ ./runtest mytest | Traceback (most recent call last): | File "./runtest", line 20, in | unittest.main() | File "/usr/lib/python2.6/unittest.py", line 816, in __init__ | self.parseArgs(argv) | File "/usr/lib/python2.6/unittest.py", line 843, in parseArgs | self.createTests() | File "/usr/lib/python2.6/unittest.py", line 849, in createTests | self.module) | File "/usr/lib/python2.6/unittest.py", line 613, in loadTestsFromNames | suites = [self.loadTestsFromName(name, module) for name in names] | File "/usr/lib/python2.6/unittest.py", line 584, in loadTestsFromName | parent, obj = obj, getattr(obj, part) | AttributeError: 'module' object has no attribute 'mytest' ` Why doesn't this work? Best, -Nikolaus First, you're missing aimport sys in the runtest.py module. Without that, it won't even start. Now, I have no familiarity with unittest, but I took this as a challenge. The way I read the code is that you need an explicit import of mytest if you're going to specify a commandline of runtest mytest So I'd add two lines to the beginning of runtest.py: import sys import mytest -- http://mail.python.org/mailman/listinfo/python-list
What is the purpose of "struct" and "array" modules
I pretty much understand what they do, but what's the case of using these modules by example? Is it something like pickle, to store the data efficiently in files? -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking old post on developers who like IDEs vs developers who like simple languages
On Thu, May 28, 2009 at 2:09 PM, Mohan Parthasarathy wrote: > > > On Mon, May 18, 2009 at 12:31 AM, Ulrich Eckhardt > wrote: > >> Steve Ferg wrote: >> > On the one hand, there are developers who love big IDEs with lots of >> > features (code generation, error checking, etc.), and rely on them to >> > provide the high level of support needed to be reasonably productive >> > in heavy-weight languages (e.g. Java). >> > >> > On the other hand there are developers who much prefer to keep things >> > light-weight and simple. They like clean high-level languages (e.g. >> > Python) which are compact enough that you can keep the whole language >> > in your head, and require only a good text editor to be used >> > effectively. >> >> This distinction is IMHO not correct. If you took a look at Java, you >> would >> notice that the core language syntax is much simpler than Python's. OTOH, >> if you add the standard libraries, you would soon see that Python's >> libraries are not as consistent (i.e. conformant to PEP8) as Java's. >> >> What makes up for Python's perceived usability problems though is the >> commandline parser that allows you to inspect the type of an object and >> its >> parts of it at runtime, in particular the docstrings are a treasure there. >> >> That said, an IDE that provides auto-completion (e.g. that gives you a >> list >> of available class members) is a good thing in Java, because you don't >> have >> to browse the documentation as often. With Python, that is impossible >> because there are no types bound to parameters, so any type that fits is >> allowed (duck typing). >> > > I just downloaded the Aptana IDE which has Python support and I have not > tried it yet. But I remebered seeing this thread. Has anyone used the Aptana > IDE for Python development ? > The "Aptana IDE" is just Eclipse (www.eclipse.org) with Aptana's plugins installed (you can get the plugins using a normal eclipse build too). The Python plugin they use is called PyDev (pydev.sourceforge.net). Look through the archives for all the people using eclipse + pydev. There are lots of them. > > thanks > mohan > > >> >> Uli >> >> -- >> Sator Laser GmbH >> Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
how to change response code in CGIHTTPServer.py
Hello, Python 2.5.2 WinXP I'm using CGIHTTPServer.py and want to return a response code of 400 with a message in the event that the cgi script fails for some reason. I notice that run_cgi(self): executes this line of code, self.send_response(200, "Script output follows") which overwrites any headers that I print in my cgi. Is there some way to modify the response code without having to override CGIHTTPServer.py? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: How does Python's OOP feel?
> The good thing about python is : it 'tastes' like what it was being > advertised +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
AOPython Question
I installed the AOPython module: % easy_install aopython That left an aopython-1.0.3-py2.6.egg at C:\mystuff\python\python_2.6.2\Lib\site-packages. I entered the interpreter: >>> import aopython >>> All is well. But I was uncomfortable, since I was used to seeing directories of Python code for modules in site-packages, so I decided to read about eggs: http://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/ The article told me to run: % easy_install aopython-1.0.3-py2.6.egg The result was a long list of error messages and removal of my egg, and Python could no longer use the AOPython module. So, I'm looking for a better reference for telling me about eggs and modules in site-packages. Roastie roasti...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: download all mib files from a web page
On May 27, 3:37 pm, Scott David Daniels wrote: > powah wrote: > > ... > > I fixed one error, now if the filename is misspelled, how to ignore > > the error and continue? > > You really should go through the tutorial. It will explain this and > other important things well. But, since I'm feeling generous: > > Replace this:> u=urllib2.urlopen(link) > > p=u.read() > > open(filename,"w").write(p) > > with this: > try: > u = urllib2.urlopen(link) > p = u.read() > except urllib2.HTTPError: > pass > else: > dest = open(filename, "w") > dest.write(p) > dest.close() > > --Scott David Daniels > scott.dani...@acm.org Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Tkinter and popen problem
Peter Otten wrote: norseman wrote: Peter Otten wrote: norseman wrote: This was sent 5/19/09 and as yet has received no comments. I'm resending just in case a new reader might have an answer. If you had posted two tiny scripts demonstrating your problem instead of the longwinded explanation I might have tinkered. That's one of the problems - with Tkinter you don't get tiny files. :) Nonsense. The minimal Tkinter program is from Tkinter import Tk root = Tk() root.mainloop() The idea is that you remove everything but the parts relevant to your problem (or build a toy example from scratch). This makes it easier for a non-guru to verify a potential answer. That non-guru might even be yourself, by the way. NOTE: program runs perfectly on both Linux and Windows XP Pro when run from the keyboard. But not from another python program that wants the phone line connected. (stdin/stdout) Gee... There is never a County Lineman when needed is there Glen? :) It's not clear why you need to start the GUI at all as you seem to have control over boths scripts. Peter = To cover two responses at once: Response from MRAB goo...@mrabarnett.plus.com [snip] You're more likely to get help if you provide the minimum code that demonstrates the problem. Anyway, your original post said that you're running the child with os.popen. The documentation says: """Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.""" Yes - that is what the docs say. They also say flush() is supposed to work. The flush() designed for the file type being used. (I think I counted six different flush() in the lib.pdf for python 2.5.2...) In other words, it's one-way. Are you really using os.popen and not, say, os.popen2? (Providing actual code would make this clear. I have tried both and Popen2.popen2(). os.popen runs both way, contrary to docs. # master.py import os #both lines work same #xx= os.popen("/mnt/mass/py/z6.py").readlines() xx= os.popen("/mnt/mass/py/z6.py",'r',1).readlines() #I had hoped small buffer would force a sync (flush()) #No such luck. for i in xx: print "\t"+i[:-1] #""" # end of file The "\t" is to prove where the screen output came from. From Peter __pete...@web.de Nonsense. The minimal Tkinter program is from Tkinter import Tk root = Tk() root.mainloop() Just to be clear, that's as much a minimal program as /* shp2dxfu.c purpose: To convert shp files to dxf files. (GNU C Unix version) */ #ifdef MSDOS #include #include #include #include #include #include #include #include #include #endif #ifdef UNIX #include #include #include #include "stat.h" #include #include #include #define O_BINARY 0x00 #define S_IREAD 0400 #endif int main(argc,argv) int argc; char *argv[]; { /* */ } and both accomplish absolutely nothing :) The idea is that you remove everything but the parts relevant to your problem (or build a toy example from scratch). This makes it easier for a non-guru to verify a potential answer. That non-guru might even be yourself, by the way. # child.py import os import sys import array from array import * import Tkinter from Tkinter import * from Tkconstants import * # def AttPanel(): def PlaceIt(): sys.stdout.write( "Switching to ESRI for placement\n") sys.stdout.flush() sys.stdout.flush() #print "Switching to ESRI for placement" ##zatt= bl_x+bl_y+acrs+c1+c2[2:]+c3[2:]+'\n' zatt='123456\n' #print zatt sys.stdout.write(zatt) sys.stdout.flush() #set system variable to zatt root.withdraw() #root.iconify() while raw_input() != ' ': pass root.deiconify() def CRASH(): print "\nCRASH Initiated\n" exit(1) # root = Tk() LU = Frame(root) LU.pack(fill="both", expand=1) f1 = Frame(LU, relief = GROOVE, bd = 2) f1.grid(row = 0, column = 0) Button(f1, width= 45, state= DISABLED).grid(row= 0, column= 0) Button(f1, text= "Place Attribute", fg= "black", bg= "green", anchor= N, command = PlaceIt).grid(row = 0, column = 1) Button(f1, width= 45, state= DISABLED).grid(row= 0, column= 2) Button(f1, text= "Cancel Attributing", fg= "white", bg= "red", anchor= E, command= CRASH).grid(row = 0, column = 3) f1.pack() # root.mainloop() #---# if __name__ == "__main__": while TRUE: AttPanel() # end of file ...(snip) It's not clear why you need to start the GUI at all as you seem to have control over boths scripts. Peter Because the master has control over the production line and the child (one stop along
Re: Adding a Par construct to Python?
On May 28, 1:53 pm, Aaron Brady wrote: > On May 27, 11:07 pm, Steven D'Aprano > cybersource.com.au> wrote: > > On Wed, 27 May 2009 12:58:02 +, Albert van der Horst wrote: > > > >>And how is reduce() supposed to know whether or not some arbitrary > > >>function is commutative? > > > > Why would it or need it? A Python that understands the ``par'' keyword > > > is supposed to know it can play some tricks with optimizing reduce() if > > > the specific function is commutative. > > > Fine. Move the smarts out of reduce() into the compiler. How is the > > compiler supposed to know if an arbitrary function is commutative? > > Unit testing. I think this kind of gets to the heart of it, here- parallelization is not a toy, runs with scissors, and will eat your dog, but so will everything else if you don't know what you're doing. I just don't see this as being a valid argument- maybe I'm wrong. In the spirit of continuing to be wrong, would it be possible to just fork off and synchronize the passed-in variables at the end of the block via a container in shared memory? That sounds to me like the simple, safe route, if a route must be taken. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: [pyunit] Only run one specific test
Dave Angel writes: > Nikolaus Rath wrote: >> Hi, >> >> Consider these two files: >> >> , mytest.py - >> | #!/usr/bin/env python >> | import unittest >> | | class myTestCase(unittest.TestCase): >> | def test_foo(self): >> |pass >> | | # Somehow important according to pyunit documentation >> | def suite(): >> | return unittest.makeSuite(myTestCase) >> ` >> >> , runtest --- >> | #!/usr/bin/env python >> | import unittest >> | | # Find and import tests >> | modules_to_test = [ "mytest" ] >> | map(__import__, modules_to_test) >> | | # Runs all tests in test/ directory >> | def suite(): >> | alltests = unittest.TestSuite() >> | for name in modules_to_test: >> | alltests.addTest(unittest.findTestCases(sys.modules[name])) >> | return alltests >> | | if __name__ == '__main__': >> | unittest.main(defaultTest='suite') >> ` >> >> >> if I run runtest without arguments, it works. But according to runtest >> --help, I should also be able to do >> >> , >> | $ ./runtest mytest >> | Traceback (most recent call last): >> | File "./runtest", line 20, in >> | unittest.main() >> | File "/usr/lib/python2.6/unittest.py", line 816, in __init__ >> | self.parseArgs(argv) >> | File "/usr/lib/python2.6/unittest.py", line 843, in parseArgs >> | self.createTests() >> | File "/usr/lib/python2.6/unittest.py", line 849, in createTests >> | self.module) >> | File "/usr/lib/python2.6/unittest.py", line 613, in loadTestsFromNames >> | suites = [self.loadTestsFromName(name, module) for name in names] >> | File "/usr/lib/python2.6/unittest.py", line 584, in loadTestsFromName >> | parent, obj = obj, getattr(obj, part) >> | AttributeError: 'module' object has no attribute 'mytest' >> ` >> >> >> Why doesn't this work? >> >> Best, >> >>-Nikolaus >> >> >> > First, you're missing aimport sys in the runtest.py module. > Without that, it won't even start. Sorry, I must have accidentally deleted the line when I deleted empty lines to make the example more compact. > Now, I have no familiarity with unittest, but I took this as a > challenge. The way I read the code is that you need an explicit > import of mytest if you're > going to specify a commandline of >runtest mytest > > So I'd add two lines to the beginning of runtest.py: > > import sys > import mytest Yes, that works indeed. But in practice the modules_to_import list is filled by parsing the contents of a test/*.py directory. That's why I import dynamically with __import__. Nevertheless, you got me on the right track. After I explicitly added the modules to the global namespace (globals()["mytest"] = __import__("mytest")), it works fine. Thx! Best, -Nikolaus -- »Time flies like an arrow, fruit flies like a Banana.« PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list
Re: AOPython Question
On May 28, 1:43 pm, Roastie wrote: > I installed the AOPython module: > > % easy_install aopython > > That left an aopython-1.0.3-py2.6.egg at > C:\mystuff\python\python_2.6.2\Lib\site-packages. > > I entered the interpreter: > > >>> import aopython > > All is well. > > But I was uncomfortable, since I was used to seeing directories > of Python code for modules in site-packages, so I decided > to read about > eggs:http://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/ > > The article told me to run: > % easy_install aopython-1.0.3-py2.6.egg > The result was a long list of error messages and removal > of my egg, and Python could no longer use the AOPython module. > > So, I'm looking for a better reference for telling me about eggs and > modules in site-packages. > > Roastie > roasti...@gmail.com The first way to do it is usually the preferred method. When you do easy_install somePackage the easy_install script will try to find the package on PyPI and download the latest version. If you do the latter, you are telling easy_install to look for that specific version. If you mis-spell the version slightly, then you will probably have issues. I am guessing that is why you received those error messages. See the easy install official docs: http://peak.telecommunity.com/DevCenter/EasyInstall - Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Hendrik van Rooyen wrote: > When ssh- ing I have been using vim, painfully. Must look at nano - sounds > good. > I really miss Brief. Or try 'joe'. -- JanC -- http://mail.python.org/mailman/listinfo/python-list
Re: AOPython Question
On May 28, 3:10 pm, Mike Driscoll wrote: > On May 28, 1:43 pm, Roastie wrote: > > > > > I installed the AOPython module: > > > % easy_install aopython > > > That left an aopython-1.0.3-py2.6.egg at > > C:\mystuff\python\python_2.6.2\Lib\site-packages. > > > I entered the interpreter: > > > >>> import aopython > > > All is well. > > > But I was uncomfortable, since I was used to seeing directories > > of Python code for modules in site-packages, so I decided > > to read about > > eggs:http://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/ > > > The article told me to run: > > % easy_install aopython-1.0.3-py2.6.egg > > The result was a long list of error messages and removal > > of my egg, and Python could no longer use the AOPython module. > > > So, I'm looking for a better reference for telling me about eggs and > > modules in site-packages. > > > Roastie > > roasti...@gmail.com > > The first way to do it is usually the preferred method. When you do > > easy_install somePackage > > the easy_install script will try to find the package on PyPI and > download the latest version. If you do the latter, you are telling > easy_install to look for that specific version. If you mis-spell the > version slightly, then you will probably have issues. I am guessing > that is why you received those error messages. > > See the easy install official docs: > > http://peak.telecommunity.com/DevCenter/EasyInstall > > - Mike I forgot to mention, but I've found that using a virtualenv for testing new modules is very helpful and you don't end up with lots of junk entries in your system path. Check it out too: http://pypi.python.org/pypi/virtualenv - Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: what I would like python.el to do (and maybe it does)
> J Kenneth King (JKK) wrote: >JKK> I find that it does work, but unlike SLIME for lisp, it just imports the >statement. >JKK> It confused me at first, but basically the interpreter doesn't provide >JKK> any feedback to emacs. >JKK> Try opening a python source file (start python-mode if you don't have >JKK> an autoload hook) and do C-c C-z to bring up the Python >JKK> interpreter. Type in a simple assignment statement (like "a = 1 + 2" >JKK> without the quotes) into the source file. Then just C-c C-c as >JKK> usual. I never get any feedback. Just C-x o to the interpreter and >JKK> print out the variable you just defined. It should be there. What kind of feedback do you expect? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: py2app and OpenGL, "No module named util" in ctypes
In article , trhaynes wrote: > I'm trying to use py2app to package an OpenGL app [...] You might try asking on the pythonmac-sig list: more py2app users there most likely. http://mail.python.org/mailman/listinfo/pythonmac-sig [or] http://dir.gmane.org/gmane.comp.python.apple -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Problem building 64-bit python 2.6.2 on Solaris 10
Hi, I'm trying to build python 2.6.2 on Solaris 10 (SPARC 64), using Sun Studio 12, but I'm having a few problems getting a clean build. The python configure options are: with_gcc=no with_universal_archs=64-bit with_cxx_main="CC -m64" The first problem I'm having is _ssl.so not building: cc -m64 -xcode=pic32 -DNDEBUG -g -xs -xtarget=ultraT1 -xarch=sparcvis2 -m64 -mt -xcode=pic32 -xmemalign=8s -xpagesize=default -I. -I/opt/ws/dists/ Python-2.6.2/. /Include -I. -IInclude -I./Include -I/opt/db/include -I/opt/tcl8/ include -I/opt/ openssl/include -I/opt/gnu/include -I/opt/local/include -I/usr/sfw/ include -I/usr/include -I/usr/local/include -I/opt/ws/dists/ Python-2.6.2/Include -I/opt/ws/dists/Python-2.6.2 -c /opt/ws/dists/ Python-2.6.2/Modules/_ssl.c -o build/temp.solaris-2.10-sun4v-2.6/opt/ ws/dists/Python-2.6.2/Modules/_ssl.o "/opt/ws/dists/Python-2.6.2/Modules/_ssl.c", line 1119: warning: statement not reached cc -m64 -G build/temp.solaris-2.10-sun4v-2.6/opt/ws/dists/Python-2.6.2/ Modules/_ssl.o -L/opt/openssl/lib/sparcv9 -L/opt/db/lib/sparcv9 -L/opt/ gnu/lib/sparcv9 -L /opt/local/lib/sparcv9 -L/usr/sfw/lib/sparcv9 -L/usr/lib/sparcv9 -L/ usr/local/lib -L. -R/opt/db/lib/sparcv9 -R/opt/gnu/lib/sparcv9 -R/opt/ local/lib/sparcv9 -R/usr/sfw/lib/sparcv9 -R/usr/lib/sparcv9 -lssl - lcrypto -lpython2.6 -o build/lib.so laris-2.10-sun4v-2.6/_ssl.so *** WARNING: renaming "_ssl" since importing it failed: ld.so.1: python: fatal: libssl.so.0.9.8: open failed: No such file or directory I have the openssl include & 64-bit libraries in the paths shown above, so why this doesn't work? What am I missing? My next problem is building the ctypes module: cc -m64 -xcode=pic32 -DNDEBUG -g -xs -xtarget=ultraT1 -xarch=sparcvis2 -m64 -mt -xcode=pic32 -xmemalign=8s -xpagesize=default -I. -I/opt/ws/dists/ Python-2.6.2/. /Include -Ibuild/temp.solaris-2.10-sun4v-2.6/libffi/include -Ibuild/ temp.solaris -2.10-sun4v-2.6/libffi -I/opt/ws/dists/Python-2.6.2/Modules/_ctypes/ libffi/src - I. -IInclude -I./Include -I/opt/db/include -I/opt/tcl8/include -I/opt/ openssl/include -I/opt/gnu/include -I/opt/local/include -I/usr/sfw/ include -I/usr/include -I/usr/local/include -I/opt/ws/dists/Python-2.6.2/Include -I/opt/ws/ dists/Python -2.6.2 -c /opt/ws/dists/Python-2.6.2/Modules/_ctypes/libffi/src/sparc/ v8.S -o build/temp.solaris-2.10-sun4v-2.6/opt/ws/dists/Python-2.6.2/ Modules/_ctypes/libffi /src/sparc/v8.o /opt/ws/tools/SUNWspro/prod/bin/fbe: "/opt/ws/tmp/dists/cpp0AAA. 19506.DfaqgM", l ine 438: error: detect global register use not covered .register pseudo-op /opt/ws/tools/SUNWspro/prod/bin/fbe: "/opt/ws/tmp/dists/cpp0AAA. 19506.DfaqgM", l ine 456: error: detect global register use not covered .register pseudo-op cc: assembler failed for /opt/ws/dists/Python-2.6.2/Modules/_ctypes/ libffi/src/s parc/v8.S I think the problem is it should be built with v9.S for 64-bit, not v8.S. Is that correct? If so, how do I get it to use the right one? Any help would be greatly appreciated. -John -- http://mail.python.org/mailman/listinfo/python-list
Re: AOPython Question
Roastie writes: > I installed the AOPython module: > >% easy_install aopython > > That left an aopython-1.0.3-py2.6.egg at > C:\mystuff\python\python_2.6.2\Lib\site-packages. An egg is basically a ZIP file with a specific structure (you can inspect it with common ZIP tools). Depending on the package easy_install is installing, it may be considered safe to install as a single file (which Python does support importing files from). I tend to prefer to have an actual unpacked tree myself. If you use the "-Z" option to easy_install, you can force it to always unpack any eggs when installing them. Alternatively, if you've already got the single egg, you can always unzip it yourself. Just rename it temporarily and unzip it into a directory named exactly the same as the single egg file was. -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
In message <003a5518$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano wrote: > On Thu, 28 May 2009 20:58:07 +1200, Lawrence D'Oliveiro wrote: > >> In message <0039e83c$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> A good UI standard should mean that: >>> >>> * all functionality should be discoverable without reading the manual; >> >> Which means no scripting languages are allowed? > > "Should", not "must". If you meant "may or may not", why don't you say "may or may not"? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to reuse TCP listening socket immediately after it was connected at least once?
In message , Thomas Bellman wrote: > Speaking as a sysadmin, running applications for production, > programs not using SO_REUSEADDR should be taken out and shot. > Not using SO_REUSEADDR means forcing a service interruption of > half an hour (IIRC) if for some reason the service must be > restarted, or having to reboot the entire machine. No, you do not recall correctly. And anybody wanting to reboot a machine to work around a "problem" like that should be taken out and shot. -- http://mail.python.org/mailman/listinfo/python-list
Re: py2app and OpenGL, "No module named util" in ctypes
Ned Deily wrote: In article , trhaynes wrote: I'm trying to use py2app to package an OpenGL app [...] You might try asking on the pythonmac-sig list: more py2app users there most likely. http://mail.python.org/mailman/listinfo/pythonmac-sig [or] http://dir.gmane.org/gmane.comp.python.apple = trhaynes; Re: py2app and OpenGL, "No module named util" in ctypes That's funny: import ctypes help(ctypes) --- start screen dump --- Help on package ctypes: NAME ctypes - create and manipulate C data types in Python FILE /usr/local/lib/python2.5/ctypes/__init__.py MODULE DOCS /mnt/mass/py/man/py-chm/module-ctypes.html PACKAGE CONTENTS _endian macholib (package) test (package) util <<<<<- wintypes CLASSES __builtin__.object CDLL PyDLL LibraryLoader --- end screen dump --- I assume py2app can't find/load it??? I wasn't in at the start of this thread. If you do need it, import ctypes from ctypes import util I know the *import ctypes* line is supposed to be *not needed*, but I find Python works more as expected with it. I also assume you have seen .../pythonXX/distutils and dist.pdf? Just in case you have not - take a look. Supposed to be how to package one's stuff for distribution. At least with python 2.5.2 on Linux Slackware 10.2 Today is: 20090528 Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the purpose of "struct" and "array" modules
On May 28, 11:17 am, Igor Katson wrote: > I pretty much understand what they do, but what's the case of using > these modules by example? Is it something like pickle, to store the data > efficiently in files? For one it provides a mechanism for reading and writing arbitrary file formats. For example, suppose you wanted to parse a PNG image using python code. It is likely that that format is described in its specification using C data structures (I've never looked at PNG format specifically). In python you can't just read out some data and copy it directly into a data structure. You could use the struct module though. It really has nothing to do with serializing python data structures. It is (mostly) about data formats and objects defined in other languages. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the purpose of "struct" and "array" modules
Igor Katson wrote: I pretty much understand what they do, but what's the case of using these modules by example? Is it something like pickle, to store the data efficiently in files? Mostly it is for access to specific binary data structures. If you know a particular file format, you can read it with a combination of struct and array, ans similarly can write in that format by such use. So like pickle in a way, but pickle is talking Python-to-Python, while things built with these will be more likely Python-to-wire or wire-to-Python when talking over a TCP/IP connection, or Python-to-file and file-to-Python, where the other user of the file may be a completely different program. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On May 26, 10:07 pm, Lacrima wrote: > I am new to python. > And now I am using trial version of Wing IDE. > But nobody mentioned it as a favourite editor. > So should I buy it when trial is expired or there are better choices? No one mentioned textmate either . a brilliant text editor with python templates, and bundles, syntax highlighting, etc. We use wingIDE for debugging and it seems fine, except for the weird way it corrupts the displayed text. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem building 64-bit python 2.6.2 on Solaris 10
> I think the problem is it should be built with v9.S for 64-bit, not > v8.S. Is that correct? If so, how do I get it to use the right one? The Solaris dynamic loader can't find it. Set LD_LIBRARY_PATH or LD_RUN_PATH appropriately, or use crle(8). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
jeffFromOz wrote: On May 26, 10:07 pm, Lacrima wrote: I am new to python. And now I am using trial version of Wing IDE. But nobody mentioned it as a favourite editor. So should I buy it when trial is expired or there are better choices? No one mentioned textmate either . a brilliant text editor with python templates, and bundles, syntax highlighting, etc. We use wingIDE for debugging and it seems fine, except for the weird way it corrupts the displayed text. === BOTTOM LINES: Whatever they learned on. Whatever they are trying out at the moment (for the adventurous types) Suggestion: Take a look at the top two most used OS you use and learn the default (most often available) text editors that come with them. The deep quiet voice of experience yells: Specialty items are seldom there when you need them! Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: py2app and OpenGL, "No module named util" in ctypes
On May 28, 11:06 am, trhaynes wrote: > I'm trying to use py2app to package an OpenGL app, so first I tried to > build the example here > > http://svn.pythonmac.org/py2app/py2app/trunk/examples/PyOpenGL/ > > and I get the error: > > > File > > "/opt/local/lib/python2.5/site-packages/PyOpenGL-3.0.0c1-py2.5.egg/OpenGL/platform/darwin.py", > > line 24, in > > import ctypes, ctypes.util > >ImportError: No module named util > >2009-05-28 13:55:06.819 lesson5[19965:10b] lesson5 Error > >2009-05-28 13:55:06.821 lesson5[19965:10b] lesson5 Error > >An unexpected error has occurred during execution of the main script > > >ImportError: No module named util > > But when I open up my python interactive interpreter and "import > ctypes.util", it works fine (using lesson5.app/Contents/MacOS/python, > too). > > Thanks for the help. What has happened is that py2app didn't bundle ctypes.util with the app, because py2app failed to detect that it was imported for some reason. A typical workaround is to imported in maually in your main script to make it explicit to py2app that it should be packaged. A word of caution: PyOpenGL uses entry hooks and that can cause a lot of trouble for application builder utilities like py2exe and py2app. In fact, I decided to stop using PyOpenGL in my projects in large part because of that issue (I use my own OpenGL wrapper now). It's possible py2app has learned to deal with entry hooks by now, but these days I refuse to use packages that require entry hooks so I wouldn't know. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Network programming ?
CTO wrote: > There's a book called Foundations of Python Network Programming that > is pretty much as good a book as you could ever ask for on the subject. I > strongly recommend it, and I think you'll find many of the examples > relevant. Yeah, I can recommend that book too. -- JanC -- http://mail.python.org/mailman/listinfo/python-list
python list pattern matching?
I want to do a functional like pattern match to get teh first two elements, and then the rest of an array return value. For example, assume that perms(x) returns a list of values, and I want to do this: seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] Of course I can shorten to: [a,b] = seq[0:2] rest = seq[2:] Can I find use some notation to do this? [a,b,more] = perms(x) or conceptually: [a,b,more..] = perms(x) PROLOG & functional languages do list decomposition so nicely like this! -- http://mail.python.org/mailman/listinfo/python-list
Re: python list pattern matching?
guthrie wrote: I want to do a functional like pattern match to get teh first two elements, and then the rest of an array return value. For example, assume that perms(x) returns a list of values, and I want to do this: seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] Of course I can shorten to: [a,b] = seq[0:2] rest = seq[2:] Can I find use some notation to do this? [a,b,more] = perms(x) or conceptually: [a,b,more..] = perms(x) >>> a,b,*rest = list(range(10)) >>> a,b,rest (0, 1, [2, 3, 4, 5, 6, 7, 8, 9]) >>> a,*rest,b = 'abcdefgh' >>> a,rest,b ('a', ['b', 'c', 'd', 'e', 'f', 'g'], 'h') -- http://mail.python.org/mailman/listinfo/python-list
extract to dictionaries
Hello I have simple text file that I have to parse. It looks something like this: parameters1 key1 value1 key2 value2 end parameters2 key1 value1 key2 value2 end So I want to create two dictionaries parameters1={key1:value1, key2:value2} and the same for parameters2. I woud appreciate any help that could help me solve this. Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: python list pattern matching?
On May 28, 5:43 pm, guthrie wrote: > I want to do a functional like pattern match to get teh first two > elements, and then the rest of an array return value. > > For example, assume that perms(x) returns a list of values, and I want > to do this: > seq=perms(x) > > a = seq[0] > b = seq[1] > rest = seq[2:] > Of course I can shorten to: > [a,b] = seq[0:2] > rest = seq[2:] > > Can I find use some notation to do this? > [a,b,more] = perms(x) > or conceptually: > [a,b,more..] = perms(x) >>> perms = 'abcdefghijklmnopqrstuvwxyz' >>> [a,b],more = perms[0:2],perms[2:] >>> a 'a' >>> b 'b' >>> more 'cdefghijklmnopqrstuvwxyz' > > PROLOG & functional languages do list decomposition so nicely like > this! -- http://mail.python.org/mailman/listinfo/python-list
How can 'type' be an instance of itself?
This is probably trivial, but it's driving me mad somehow. All (new style) classes are instances of 'type' by default, unless a custom metaclass is specified. I take this to mean that when a class declaration is found in the code, an instance of 'type' representing that class is created by calling type.__init__. What really gets me is how can 'type' be an instance of itself. In order to create 'type' we would need to call type.__init__, but it seems at this point it wouldn't exist. Probably a dumb question, which I hope someone can explain in some detail. -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Fri, 29 May 2009 09:04:39 +1200, Lawrence D'Oliveiro wrote: > In message <003a5518$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano > wrote: > >> On Thu, 28 May 2009 20:58:07 +1200, Lawrence D'Oliveiro wrote: >> >>> In message <0039e83c$0$9673$c3e8...@news.astraweb.com>, Steven >>> D'Aprano wrote: >>> A good UI standard should mean that: * all functionality should be discoverable without reading the manual; >>> >>> Which means no scripting languages are allowed? >> >> "Should", not "must". > > If you meant "may or may not", why don't you say "may or may not"? Are you a native English speaker? "Should" does not mean "may or may not". There is an enormous difference in meaning between e.g. "I should feed the dog" and "I may or may not feed the dog". The first case means that you have a need to feed the dog, but you are not obliged to, while the second case means you are indifferent to whether or not you will feed the dog. (Strictly speaking, "may or may not" is redundant, although often used to emphasise the indifference. If you may do something, then by definition you also may not do it.) The distinction between "may", "should" and "must" is also very common in RFCs. As a tech, I would have expected you to have been aware of that. For example, picking one at random, RFC 1866 (literally the first one I looked up!): may A document or user interface is conforming whether this statement applies or not. must Documents or user agents in conflict with this statement are not conforming. should If a document or user agent conflicts with this statement, undesirable results may occur in practice even though it conforms to this specification. http://www.faqs.org/rfcs/rfc1866.html To put it another way: "may" is optional, "should" is recommended, and "must" is compulsory. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: python list pattern matching?
Terry Reedy: > >>> a,b,*rest = list(range(10)) > >>> a,b,rest > (0, 1, [2, 3, 4, 5, 6, 7, 8, 9]) > >>> a,*rest,b = 'abcdefgh' > >>> a,rest,b > ('a', ['b', 'c', 'd', 'e', 'f', 'g'], 'h') For the next few years I generally suggest to specify the Python version too (if it's 2.x or 3.x). This is Python 3.x. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: How can 'type' be an instance of itself?
LittleGrasshopper wrote: > This is probably trivial, but it's driving me mad somehow. All (new > style) classes are instances of 'type' by default, unless a custom > metaclass is specified. I take this to mean that when a class > declaration is found in the code, an instance of 'type' representing > that class is created by calling type.__init__. What really gets me is > how can 'type' be an instance of itself. In order to create 'type' we > would need to call type.__init__, but it seems at this point it > wouldn't exist. Probably a dumb question, which I hope someone can > explain in some detail. The classes 'type' and 'object' are written in C. You can do things in C code that aren't possible from pure Python code. The circular dependencies between 'type' and 'object' are created during the boot strapping phase of the interpreter. >>> type(type) >>> type.__bases__ (,) >>> object.__bases__ () >>> type(object) Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: How can 'type' be an instance of itself?
On May 28, 4:37 pm, Christian Heimes wrote: > LittleGrasshopper wrote: > > This is probably trivial, but it's driving me mad somehow. All (new > > style) classes are instances of 'type' by default, unless a custom > > metaclass is specified. I take this to mean that when a class > > declaration is found in the code, an instance of 'type' representing > > that class is created by calling type.__init__. What really gets me is > > how can 'type' be an instance of itself. In order to create 'type' we > > would need to call type.__init__, but it seems at this point it > > wouldn't exist. Probably a dumb question, which I hope someone can > > explain in some detail. > > The classes 'type' and 'object' are written in C. You can do things in C > code that aren't possible from pure Python code. The circular > dependencies between 'type' and 'object' are created during the boot > strapping phase of the interpreter. > > >>> type(type) > > >>> type.__bases__ > (,) > >>> object.__bases__ > () > >>> type(object) > > > > Christian That puts my mind at ease, thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: extract to dictionaries
Marius Retegan: > > parameters1 > key1 value1 > key2 value2 > end > > parameters2 > key1 value1 > key2 value2 > end > > So I want to create two dictionaries parameters1={key1:value1, > key2:value2} and the same for parameters2. I have wasted some time trying to create a regex for that. But it's better to use normal code. Iterate on the lines, keep a dict, and when you find a string that doesn't start with whitespace, use it to create a new key-value into the dict, where the key is the stripped line and the value is an empty dict. Then you can enter a sub loop or set a "inside" boolean variable, to denote you are in a different part of the state machine. When you find lines that start with a space, you can put add them as key-value into the latest dict (so you have to keep the key name in the superdict, or more efficiently you can keep your subdict on a side, and you can add it only at the end when you see a line "end" with no leading spaces. When you find such "end" you can exit the sub loop or rest the "inside" boolean. Overall if's just few lines of code, much shorter than my description of the algorithm. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: extract to dictionaries
Marius Retegan wrote: Hello I have simple text file that I have to parse. It looks something like this: parameters1 key1 value1 key2 value2 end parameters2 key1 value1 key2 value2 end So I want to create two dictionaries parameters1={key1:value1, key2:value2} and the same for parameters2. I woud appreciate any help that could help me solve this. Thank you This looks like a homework problem. But even if it's not, you are not likely to find someone who is willing to put more work into this problem than you have. So why don't you show us what you've tried, and see if someone is willing to make suggestions or answer specific question about your attempt at a solution? Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: How can 'type' be an instance of itself?
On May 28, 4:37 pm, Christian Heimes wrote: > LittleGrasshopper wrote: > > This is probably trivial, but it's driving me mad somehow. All (new > > style) classes are instances of 'type' by default, unless a custom > > metaclass is specified. I take this to mean that when a class > > declaration is found in the code, an instance of 'type' representing > > that class is created by calling type.__init__. What really gets me is > > how can 'type' be an instance of itself. In order to create 'type' we > > would need to call type.__init__, but it seems at this point it > > wouldn't exist. Probably a dumb question, which I hope someone can > > explain in some detail. > > The classes 'type' and 'object' are written in C. You can do things in C > code that aren't possible from pure Python code. The circular > dependencies between 'type' and 'object' are created during the boot > strapping phase of the interpreter. > > >>> type(type) > > >>> type.__bases__ > (,) > >>> object.__bases__ > () > >>> type(object) > > > > Christian And just to clarify that I do really understand what this means, I gather that what it entails is that 'type' is an instance of itself just from a conceptual point of view. In other words, the code for the (meta)class 'type' is created statically by object code (compiled C code) before the python runtime is initiated (you referred to it as the interpreter bootstrapping phase.) I also guess that this code sets __class__ and __metaclass__ to the 'type' object itself (I am guessing a self-referencial pointer in C.) While I just am hypothesizing on the details, please let me know if you sense that I have misunderstood any essential part of your explanation. Thanks, Lukas -- http://mail.python.org/mailman/listinfo/python-list
Re: python list pattern matching?
On Thu, 28 May 2009 18:57:42 -0400, Terry Reedy wrote: > >>> a,b,*rest = list(range(10)) That fails in Python 2.5 and 2.6. >>> a,b,*rest = list(range(10)) File "", line 1 a,b,*rest = list(range(10)) ^ SyntaxError: invalid syntax -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding a Par construct to Python?
On Thu, 28 May 2009 10:53:17 -0700, Aaron Brady wrote: > On May 27, 11:07 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 27 May 2009 12:58:02 +, Albert van der Horst wrote: >> >> >>And how is reduce() supposed to know whether or not some arbitrary >> >>function is commutative? >> >> > Why would it or need it? A Python that understands the ``par'' >> > keyword is supposed to know it can play some tricks with optimizing >> > reduce() if the specific function is commutative. >> >> Fine. Move the smarts out of reduce() into the compiler. How is the >> compiler supposed to know if an arbitrary function is commutative? > > Unit testing. (Correction: the characteristic we really care about is associativity, not commutativity.) I really shouldn't reply to this, because I fear this is just going to drag me down into a bottomless pit, but here goes... I don't see how unit tests can possibly help. There's an infinite number of possible functions that could be passed to parallel reduce(), and you can't test them all. Even if you lower your sights and just aim to recognise a tiny subset of associative functions, you end up with code like this: def par_reduce(func, *args): if func in (operator.add, operator.mul): if isinstance(args[0], (int, long)): return _associative_par_reduce(func, *args) return _nonassociative_par_reduce(func, *args) You can't even recognise functions like lambda x,y: x+y. In case you're thinking you can, no, "if func == lambda x,y: x+y" won't work: >>> (lambda x,y: x+y) == (lambda x,y: x+y) False I suppose if you're willing to special case a tiny handful of functions, that's a solution of sorts, but I did ask about arbitrary functions. Perhaps you're thinking of another approach: put the unit tests inside the par_reduce() function, and use them to determine at runtime whether or not the argument func is associative. def par_reduce(func, *args): try: # a mass of unittests except Exception: # are we catching too much? are we masking bugs in the tests? return _nonassociative_par_reduce(func, *args) return _associative_par_reduce(func, *args) This would be impractical, because the cost would be enormous. But even putting that aside, it still wouldn't work. I don't see how you could know what is a valid unittest for an arbitrary function, but suppose you could, somehow. Then what? True enough, if you run lots of tests, and it fails one, then you know that func is not associative. But having passed all those tests, you can't know if your tests covered all the possible cases. E.g. for floats, you can run some tests and decide that addition looks associative: >>> 0.1 + (0.1 + 0.1) == (0.1 + 0.1) + 0.1 True >>> 0.1 + (0.9 + 0.1) == (0.1 + 0.9) + 0.1 True >>> 0.1e67 + (0.9 + 0.3) == (0.1e67 + 0.9) + 0.3 True >>> 0.1e54 + (0.9 + 0.1) == (0.1e54 + 0.9) + 0.1 True but you'd be wrong: >>> 1e54 + (-1e54 + 0.1) == (1e54 + -1e54) + 0.1 False No, you can't expect to discover experimentally whether an arbitrary function is associative. You would need to analyse what the function does, which means in practice the *programmer* needs to decide what to do, not reduce(). -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Most pythonic way to truncate unicode?
On Thu, 28 May 2009 08:50:00 -0700, Andrew Fong wrote: > I need to ... > > 1) Truncate long unicode (UTF-8) strings based on their length in BYTES. Out of curiosity, why do you need to do this? > For example, u'\u4000\u4001\u4002 abc' has a length of 7 but takes up 13 > bytes. No, that's wrong. The number of bytes depends on the encoding, it's not a property of the unicode string itself. >>> s = u'\u4000\u4001\u4002 abc' >>> len(s) # characters 7 >>> len(s.encode('utf-8')) # bytes 13 >>> len(s.encode('utf-16')) # bytes 16 >>> len(s.encode('U32')) # bytes 32 > Since u'\u4000' takes up 3 bytes But it doesn't. The *encoded* unicode character *may* take up three bytes, or four, or possibly more, depending on what encoding you use. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
problems with Cheetah base class being in templates directory
*How do we setup Cheetah so it runs with all templates in the templates directory and all code in the .. directory code.py* production=True if not production: try:web.render('mafbase.tmpl', None, True, 'mafbase') except:pass else: from templates import mafbase templates/mafbase.tmpl templates/mafbase.py try:web.render('mafbase.tmpl', None, True, 'mafbase') This works but is very slow to load and causes timeout errors from templates import mafbase This doesnt work return self._delegate(fn, self.fvars, args) File "/home/mark/work/common/web/application.py", line 411, in _delegate return handle_class(cls) File "/home/mark/work/common/web/application.py", line 386, in handle_class return tocall(*args) File "user.py", line 262, in proxyfunc return func(self, *args, **kw) File "/home/mark/work/pop/code.py", line 1796, in GET return web.render('subclass.html') File "/home/mark/work/common/web/cheetah.py", line 104, in render return str(compiled_tmpl) File "/usr/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-i686.egg/Cheetah/Template.py", line 982, in __str__ def __str__(self): return getattr(self, mainMethName)() File "mafbase.py", line 634, in respond File "/usr/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-i686.egg/Cheetah/Template.py", line 1512, in _handleCheetahInclude nestedTemplateClass = compiler.compile(source=source,file=file) File "/usr/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-i686.egg/Cheetah/Template.py", line 693, in compile fileHash = str(hash(file))+str(os.path.getmtime(file)) File "/usr/lib/python2.5/posixpath.py", line 143, in getmtime return os.stat(filename).st_mtime OSError: [Errno 2] No such file or directory: '/home/mark/work/pop/widgetbox.html' -- Bidegg worlds best auction site http://bidegg.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python list pattern matching?
Many thanks to all; perfect solution! -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
In message <003af57e$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 29 May 2009 09:04:39 +1200, Lawrence D'Oliveiro wrote: > >> In message <003a5518$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> On Thu, 28 May 2009 20:58:07 +1200, Lawrence D'Oliveiro wrote: >>> In message <0039e83c$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano wrote: > A good UI standard should mean that: > > * all functionality should be discoverable without reading the > manual; Which means no scripting languages are allowed? >>> >>> "Should", not "must". >> >> If you meant "may or may not", why don't you say "may or may not"? > > "Should" does not mean "may or may not". I'm not sure how there is supposed to be a difference in this context. "All people should fly by flapping their arms, except where this is physically impossible". You're asking for something that is infeasible with most current editors, if not all of them. -- http://mail.python.org/mailman/listinfo/python-list
Re: extract to dictionaries
You can create this modularly by : 1. parse the file and cut this into different chunks ( look for 'end' ) then you have two chunks for param 1 & 2 2. once you have those chunks then process each chunk with your own processing based on your parameters ( 1 or 2 ) 3. then based on your individual param, create a process to populate your dict 4. done hint: "pydoc string" ( I'm assuming that you already know about regex, if not then use this : "pydoc re" ) BTW: I've used this methods to parse cisco/contivity configs HTH On Fri, May 29, 2009 at 9:03 AM, Marius Retegan wrote: > Hello > I have simple text file that I have to parse. It looks something like > this: > > parameters1 > key1 value1 > key2 value2 > end > > parameters2 > key1 value1 > key2 value2 > end > > So I want to create two dictionaries parameters1={key1:value1, > key2:value2} and the same for parameters2. > > I woud appreciate any help that could help me solve this. > Thank you > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Tkinter file dialog
I'm using Tkinter file selector to get a direcotry path. I'm using: self.file = tkFileDialog.askdirectory(title="Please select your directory") print file but all it prints out is: How would I print the directory path? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Most pythonic way to truncate unicode?
Andrew Fong gmail.com> writes: > I need to ... > 1) Truncate long unicode (UTF-8) strings based on their length in > BYTES. > 2) I don't want to accidentally chop any unicode characters in half. > If the byte truncate length would normally cut a unicode character in > 2, then I just want to drop the whole character, not leave an orphaned > byte. > I'm using Python2.6, so I have access to things like bytearray. Using bytearray saves you from using ord() but runs the risk of accidental mutation. > Are > there any built-in ways to do something like this already? Or do I > just have to iterate over the unicode string? Converting each character to utf8 and checking the total number of bytes so far? Ooooh, slww! The whole concept of "truncating unicode" you mean "truncating utf8") seems rather unpythonic to me. Another alternative is to iterate backwards over the utf8 string looking for a character-starting byte. It leads to a candidate for Unpythonic Code of the Year: def utf8trunc(u8s, maxlen): assert maxlen >= 1 alen = len(u8s) if alen <= maxlen: return u8s pos = maxlen - 1 while pos >= 0: val = ord(u8s[pos]) if val & 0xC0 != 0x80: # found an initial byte break pos -= 1 else: # no initial byte found raise ValueError("malformed UTF-8 [1]") if maxlen - pos > 4: raise ValueError("malformed UTF-8 [2]") if val & 0x80: charlen = (2, 2, 3, 4)[(val >> 4) & 3] else: charlen = 1 nextpos = pos + charlen assert nextpos >= maxlen if nextpos == maxlen: return u8s[:nextpos] return u8s[:pos] if __name__ == "__main__": tests = [u"", u"\u", u"\u007f", u"\u0080", u"\u07ff", u"\u0800", u"\u" ] for testx in tests: test = u"abcde" + testx + u"pqrst" u8 = test.encode('utf8') print repr(test), repr(u8), len(u8) for mlen in range(4, 8 + len(testx.encode('utf8'))): u8t = utf8trunc(u8, mlen) print "", mlen, len(u8t), repr(u8t) Tested to the extent shown. Doesn't pretend to check for all cases of UTF-8 malformation, just easy ones :-) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Most pythonic way to truncate unicode?
John Machin lexicon.net> writes: > Andrew Fong gmail.com> writes: > Are > > there any built-in ways to do something like this already? Or do I > > just have to iterate over the unicode string? > > Converting each character to utf8 and checking the > total number of bytes so far? > Ooooh, slww! > Somewhat faster: u8len = 0 for u in unicode_string: if u <= u'\u007f': u8len += 1 elif u <= u'\u07ff': u8len += 2 elif u <= u'\u': u8len += 3 else: u8len += 4 Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On Fri, 29 May 2009 14:00:19 +1200, Lawrence D'Oliveiro wrote: > In message <003af57e$0$9673$c3e8...@news.astraweb.com>, Steven D'Aprano > wrote: > >> On Fri, 29 May 2009 09:04:39 +1200, Lawrence D'Oliveiro wrote: >> >>> In message <003a5518$0$9673$c3e8...@news.astraweb.com>, Steven >>> D'Aprano wrote: >>> On Thu, 28 May 2009 20:58:07 +1200, Lawrence D'Oliveiro wrote: > In message <0039e83c$0$9673$c3e8...@news.astraweb.com>, Steven > D'Aprano wrote: > >> A good UI standard should mean that: >> >> * all functionality should be discoverable without reading the >> manual; > > Which means no scripting languages are allowed? "Should", not "must". >>> >>> If you meant "may or may not", why don't you say "may or may not"? >> >> "Should" does not mean "may or may not". > > I'm not sure how there is supposed to be a difference in this context. > "All people should fly by flapping their arms, except where this is > physically impossible". You're asking for something that is infeasible > with most current editors, if not all of them. On the remote chance that you're not trolling, I deny that discoverablity is "infeasible", for editors or other applications. Making a UI discoverable is not a hard problem that is difficult to solve. Discoverablity isn't radical new concept in UI design, it has been around since the 1970s, at least. The concept is simple: e.g. in the editor I'm using to compose this message, I have a toolbar which includes a button "Wrap Text". That's discoverable, because even if I didn't know the command existed, I could discover it by looking at the toolbar. There's a keyboard command to do the same thing: Alt-E-W. Without reading the manual, I'm unlikely to discover that command. Here's a couple of screenshots of Wordstar: http://www.kantl.be/ctb/vanhoutte/teach/slides/graphics/wstar.gif http://www.iee.et.tu-dresden.de/~kc-club/08/PCX/WORDSTAR.GIF Wordstar's commands are discoverable, because they are listed in a menu you can choose from. Wordstar dates back to 1978, so this isn't precisely the cutting edge of UI design. As a general rule, menus are discoverable, while keyboard commands aren't. There's nothing inherent to text editing functions which makes then inherently undiscoverable, and KDE apps like kate and kwrite do a reasonable job of making them so. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Most pythonic way to truncate unicode?
On Fri, 29 May 2009 04:09:53 +, John Machin wrote: > John Machin lexicon.net> writes: > >> Andrew Fong gmail.com> writes: > > > Are >> > there any built-in ways to do something like this already? Or do I >> > just have to iterate over the unicode string? >> >> Converting each character to utf8 and checking the total number of >> bytes so far? >> Ooooh, slww! >> >> > Somewhat faster: What's wrong with Peter Otten's solution? >>> u"äöü".encode("utf8")[:5].decode("utf8", "ignore") u'\xe4\xf6' At most, you should have one error, at the very end. If you ignore it, you get the unicode characters that have length <= 5 in *bytes* when encoded as UTF-8. (If you encode using a different codec, you will likely get a different number of bytes.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list