Re: Walking deeply nested lists
On 28/08/2010 14:41, Peter Otten wrote: BTW, I didn't expect it but I get different results on different runs. Clever code. I will give it a go soonest. Elec off for the next 24 hours in my neck of the woods. Urgh. Python can't "import electricity" just yet :) \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Walking deeply nested lists
On 28/08/2010 12:03, Peter Otten wrote: But be warned that if you set the limit too high instead of giving you a RuntimeError your program will segfault. Silly question: is there any way to tell the future in this case? I mean, ask for X recursion limit, and catch an error (or something) if that won't fly. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Walking deeply nested lists
On 28/08/2010 11:17, Carl Banks wrote: It's simple. Copy the object to flatten onto your stack. Pop one item off the stack. If the item you popped is a list, push each item of that list onto the stack. Otherwise yield the value. Loop until stack is empty. Nice. The reversed thing was throwing me, but I think it's so that what comes first in a list will thus come first (on the end) of the stack. So I'm not suggesting that recursion be avoided (I've probably written a dozen recursive functions in the last week), I'm just saying sometimes it makes sense to use iteration even for problems recursion is tailor-made for. Thanks for that. In parsing the XML (using lxml) I actually did my own stack thing with while loops, to build the entire Tag object 'tree' — just because I wanted to see how to do it sans recursion. I still get cold shakes when I scroll past that monster! On the subject of recursion, and looking at my OP object model: the Tag objects that model the tags in an SVG file; how would I 'walk' the object tree without employing recursion? I am stuck on the eventual need to call child.flatwalk() and bang! there's recursion. I get the sense that it would be an external walk() function that does some stackery-trickery and reuturns/yields the tree/branch — all divorced from the actual objects. So, no flatwalk() methods needed at all. This kind of bothers me because it's nice to have objects 'know' what to do and addressing their siblings and children seems a vital part of that. Look at the case of asking a Tag for its XML source: Say g is a G() instance: print g.get_xml(), would have to do some string churning (specific to a g tag) and then start walking its children and ask them to do specific string stuff (in their contexts). This means I have short methods in each Tag instance that "know" how to represent themselves as XML and they can return that value. If I divorce the thing, it becomes a large loop with a lot of switchy-ifs to engage various blocks of string-fu. I hope that made sense. I can post my code if that would help. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Walking deeply nested lists
On 28/08/2010 09:21, Arnaud Delobelle wrote: This flattens the list in the flatwalk method (which IMHO it should do given its name!): Heh, I often name things ahead of my actual capacity to implement them! el is child.flatwalk(): Ah, I see what you mean. I think 'is' is 'in', but I kind of get the idea. This turns it into a generator method: And thanks for the generator versions too. I shall hack them in and poke them with a stick. Of course, for the above to work, "leaf" objects need a modified flatwalk method, e.g.: Yes, My 'stubs' (leaves) do have such, but I will edit to use yield. Thanks a mill. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Walking deeply nested lists
On 28/08/2010 08:43, Peter Otten wrote: If you call functions within functions (or methods, it doesn't matter) they consume stack space Right, got it. Darn, but at least there's that setrecursionlimit call. Thanks, \e -- http://mail.python.org/mailman/listinfo/python-list
Walking deeply nested lists
This is all about walking trees, recursion and generators. None of which fit my brain at all! From an XML tree (an SVG file) I build a bunch of Tag objects. [I use lxml, but I am combining multiple svg files into a 'forest' of trees, so I can't use the lxml walking methods because they all stop at the 'end' of a branch where there is actually a 'link' over to another tree.] Each Tag has a flatwalk() method. The return from that is a list which can be deeply nested. As an example, something like this: L=[1, [2, 3, [4, [5, 6], 7], 8], [9, 10] ] (The numbers in the example would actually be Tag Instances.) Aim 1 --- I'm trying to write a generator around such lists so that I can 'walk' them: for parent, child in mystery_generator(L): print level, item Right now, I am running a 'flatten' function on the entire list (which I don't savvy, I found it online) and then I iterate over that flattened list. This doesn't feel right to me. (Code at end.) Aim 2 --- The Objects that represent the svg tags use that flatwalk() method to build the nested list, I'd far prefer flatwalk() to be directly useable in something like this way: for container, child in some_tag.flatwalk(): print container, child The flatwalk() function is (and this is another puzzle see *) kind of recursive. "For each of my children, tell that child to go flatwalk()". (Code at end.) I am not sure how to turn such a thing into a generator. I keep wondering how os.walk() does its thing. My hierarchy of Tag objects can be thought of as directories (tags:g, symbol, svg), files (path, circle, etc.) and soft-links (use tags). * If an Instance calls a method on *another* Instance of the *same* class, is this still recursion? And how does this 'stack up'? I mean, literally, on the stack. Does each instance get its own stack, or does all the push, call, pop stuff happen in one main stack? (I worry about recursion depth limits because svg trees can get quite deep.) The walking code so far: ## Found code. def flatten(input): output = [] stack = [] stack.extend(reversed(input)) while stack: top = stack.pop() if isinstance(top, list): stack.extend(reversed(top)) else: output.append(top) return output ## My walker def test_walk(e): #lxml Element comes in obj = ebag_get(e)['obj'] #get a tag object l=obj.flatwalk() ll= flatten(l) #No current solution to get 'parent' in this iterator #ie. for parent, child in ... for tag in ll: print tag Here's one of my Tag objects: class Brancher(object): def __init__(self, elem): self.elem = elem self.children = [] def flatwalk(self): l=[self] for child in self.children: l.append( child.flatwalk() ) #recur(ish)ion here return l class G( Brancher ): #Object for tags. pass \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to set a cookie within a python script
On 04/08/2010 20:09, Dotan Cohen wrote: Don't forget that the Euro symbol is outside the Greek character set. I could make some kind of economic joke here, but I'm also broke :D \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?
On 02/08/2010 17:35, Mark Lawrence wrote: aka the colon. :) Ha. This is a case of the colon being the appendix! \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Hello [How to run your code]
On 10/07/2010 13:05, Dani Valverde wrote: It could be a solution. But I am used to work with gEdit using the R statistical programming language plugin, and I am able to send the code to console instead of typing it in. To run your code, save it to a file 'mycode.py' (or whatever), then open a console and cd into that directory, then: python mycode.py That will get you started. Keep the console open and alt-tab to it whenever you want to run your code. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: How to keep effects of image filters going for some seconds?
On 21/03/2010 09:23, Ren Wenshan wrote: I have been learning Panda3D, an open source 3D engine, Ask on the Panda3D forums, you will get good help there. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating formatted output using picture strings
On 10/02/2010 20:36, pyt...@bdurham.com wrote: def picture(s, pic, placeholder='@'): nextchar=iter(s).next return ''.join(nextchar() if i == placeholder else i for i in pic) Hell's teeth - even I understood that! Amazing solution. \d -- Fonty Python and Things! -- http://otherwise.relics.co.za/wiki/Software -- http://mail.python.org/mailman/listinfo/python-list
Re: pyclutter anyone?
No one uses pyClutter? I have some code, it does not work, but maybe this will start to help solve the problem: import clutter from clutter import cogl x,y=0,0 def boo(tl,frame,obj):#,evt): global x,y obj.set_position(x, y) def xy(obj,evt): global x,y x,y = evt.x,evt.y class G(clutter.Group): """ Attempt to make a Group that can clip its children to a path. """ def __init__(self,*args): clutter.Group.__init__(self,*args) #self.set_clip(0,0,10,10) self.connect("paint",self.do_paint) self._color = clutter.Color(255,200,100) def do_paint(self, args): width,height=200,200 cogl.path_move_to(width / 2, 0) cogl.path_line_to(width, height) cogl.path_line_to(0, height) cogl.path_line_to(width / 2, 0) cogl.path_close() #cogl.set_source_color(self._color) #cogl.path_fill() ## Colour me lost from here... cogl.clip_push_from_path() clutter.Group.do_paint(self) cogl.clip_pop() def main(): global group1 stage = clutter.Stage() stage.set_size(500, 500) stage.set_color(clutter.color_from_string("#FFF")) rect1, rect2, rect3 = clutter.Rectangle(), clutter.Rectangle(), clutter.Rectangle() group1, group2, group3 = G(), clutter.Group(), clutter.Group() group1.add(rect1, group2) group2.add(rect2, group3) group3.add(rect3) group1.set_position(100, 100) group2.set_position(100, 100) group3.set_position(100, 100) rect1.set_position(0, 0) rect2.set_position(0, 0) rect3.set_position(0, 0) rect1.set_size(150, 150) rect2.set_size(150, 150) rect3.set_size(150, 150) rect1.set_color(clutter.color_from_string("#FF90")) rect2.set_color(clutter.color_from_string("#00FF0090")) rect3.set_color(clutter.color_from_string("#FF90")) stage.add(group1) stage.show_all() group1.show_all() group2.show_all() group3.show_all() stage.connect("key-press-event", clutter.main_quit) stage.connect('destroy', clutter.main_quit) stage.connect('motion-event', xy) path = clutter.Path('M 0 0 L 300 0 L 300 300 L 0 300z') timeline = clutter.Timeline(4000) timeline.set_loop(True) alpha = clutter.Alpha(timeline,clutter.EASE_OUT_SINE) p_behaviour = clutter.BehaviourPath(alpha, path) path.add_move_to(0, 0) p_behaviour.apply(group3) timeline.add_marker_at_time("foo",2000) timeline.start() t=clutter.Timeline(1000) t.set_loop(True) t.connect('new-frame', boo, group1) t.start() clutter.main() if __name__ == '__main__': main() \d -- Fonty Python and Things! -- http://otherwise.relics.co.za/wiki/Software -- http://mail.python.org/mailman/listinfo/python-list
pyclutter anyone?
Hi, this is a little bit of a cross-post. I posted to the clutter list, but there's little activity there. I am trying to make sense of pyClutter 1.0. Could anyone point me to an example (or post one) that shows clipping from a path applied to child objects? For example: A star shape that contains a bunch of moving rectangles which will travel/size/rotate with the star, but are clipped to the shape of the star. I suspect this will involve a custom clutter.Group class of some kind, with cogl paths and an on_paint() method, but I can find no headway on the web so far. Hope someone can help! \d -- Fonty Python and Things! -- http://otherwise.relics.co.za/wiki/Software -- http://mail.python.org/mailman/listinfo/python-list
Re: Significant whitespace
On Saturday 02 January 2010 00:02:36 Dan Stromberg wrote: > I put together a page about significant whitespace (and the lack thereof). The only thing about Python's style that worries me is that it can't be compressed like javascript can*, and perhaps that will prevent it becoming a browser-side language one day. How I'd love to code PyQuery instead of JQuery! * Or am I wrong? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Thursday 17 December 2009 19:46:41 Terry Reedy wrote: > His idea was for a document rather than > app centric plain. These days I find the notion of monolithic apps to be a pita. The concept of many small black boxes (but open source) that each do a single job and pipe in/out is so much more powerful. I don't see why everything in a gui and down can't be such a box. Then we get to wire them together as needed. We'd still have 'big apps' but they would be constructed more loosely and we could adapt them to fit real life needs. I dunno. I think big apps are dinosaurs. As much as I love Inkscape and Blender and others, they are all islands with vast gulfs between them. And let's have Python glue them all together! > Not clear how one would pipe data from app to app in > his model, though. The picture I have of it is illustrated by Blender's material node system. have a look at this pic: http://upload.wikimedia.org/wikipedia/commons/2/26/Working_with_Nodes_Blender.PNG Just a mental jump-off point. Think bash meets zui with a Python driving. :D \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Thursday 17 December 2009 10:54:59 David Roberts wrote: > Have you seen Eagle Mode[1]? > Yes. It's a strange beast. Good start I think; but addicted to zooming, to the detriment of the managing aspects I think. Still, here I sit writing no code and pontificating! \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Wednesday 16 December 2009 07:03:19 David Roberts wrote: > It involves scaling an image to various resolutions, and partitioning > them into fixed-size tiles. It's roughly the same technique used by > Google Maps/Earth. Thanks. That gives me something to go on. Wikipedia didn't like my search terms. > > ZUIs are useful for particular types of data - images & mapping > > especially - but I'd hate to have to navigate my desktop using its > > approach. Ever since Corel Draw in the 90's zoomed into my life I have been in love with the idea of an endless canvas that makes me feel like a satellite on a bungee cord. I think it would fit the desktop very well. Personally I see a merging of normal app windows and a zui: some kind of new window manager. If I planned it out it would look something like this: Your apps all run as they do now*, but they live on this endless plain. Perhaps it can be divided up into 'zones' or 'galaxies' or something. I would have a 'hyperspace' or 'hyperlink' or 'jump' facility (like alt-tab, I guess) to make transits from one custom-defined area to another quick. I would have a home position for the view -- like Inkscape does in terms of show all, zoom to selected, zoom to last, etc. I would have rules about traversing. Things like file-managers need some kind of static display - like the bread crumbs and up, back, home etc. Each app would only be active when 'locked-in', beyond that it's a bitmap of the last paint. You could drag apps around when you zoom out, and you can resize them at any time too. (Just imagine OOCalc in a zui! Super/Capslock and mouse wheel for scroll/pan) The other cool idea I had was to (handwavium here) graphically convey the notion of pipes and import/export between apps. Also between any nodes across the Universe of the zui. Perhaps a special 'node view' that overlays and shows all the conduits between them -- sharp where your mouse is, faded away from that so the whole thing is not too complex. Imagine the flow from Inkscape to Gimp and back. Instead of File -> Export and then File -> Import, you connect pipes along the side of each app. Inkscape, [save selected as png (properties preset)] goes to Gimp [import to layers by names (a script perhaps)] Now as you work in Inkscape and hit a hotkey, all your selected vectors are sent to Gimp which reacts as if you were there and places the new pngs into layers. This can work both ways and between multiple programs. Mix-in Blender and Scribus and Lyx and some grep and a loop or two and some imagemagick... Ah, I better stop. I can ramble on sometimes :) *I have many issues with the endless variety of re-invented wheels afa gui toolkits go. This is another whole can of shai-Hulud... I wrote some stuff about this a while back, if anyone wants to be put to sleep: http://otherwise.relics.co.za/wiki/Particles/DreamDesignApp/ :) \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Wednesday 16 December 2009 09:42:14 David Roberts wrote: > PyZUI 0.1 has been released: Magic! Grabbed a tarball yesterday. \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Tuesday 15 December 2009 11:12:21 Martijn Arts wrote: > You could do some really awesome stuff with that! I love the webpage > example where you zoom in on the exclamation mark and there's a new page. > It is very cool, but I would inject a note of caution here: I'd a hate a zui to become a case of "hunt-the-zoom." A link is a link. They already work very well, click and it goes to the page. I find the notion of minute "hot" areas to be a little obscure -- Quick! Zoom into the last full-stop, it's a whole word in there! What I would enjoy is when you click a link - it zooms into the sub-page so you get a feeling of traversal. Back buttons would zoom out again. Add to that a kind of birds'-eye view of one's history (like a thumbnails node-graph of some kind) and it would be perfect! \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Tuesday 15 December 2009 04:29:39 David Roberts wrote: > Yes, the toolkit used is PyQt. \me makes note to start learning PyQt asap. > and employs pyramidal tiling for efficiency \me ... time to hit Wikipedia :) > (I haven't used any Qt/KDE voodoo in this regard). Imho, your code should *become* that voodoo -- from what I saw in that vid it's unique and has such promise. > QtWebKit, and PDF with the pdftoppm utility. Ah, thanks. > The project is opensource (GPLv2), but just hasn't been published > yet :) . I'll try to make a release over the next few days, and I'll > post a link here when I do. Can't wait. David, thanks for replying here on the list. Well done on your pyZui and I hope it catches fire in people's imaginations. I think that fire may explain why my socks are missing! :D \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Tuesday 15 December 2009 01:43:52 David Boddie wrote: > I managed to catch his address and sent him a message saying that people > were discussing PyZUI in this thread. > Oooh. Sits,fidgets and waits. I want my socks back! (OP) :D \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Monday 14 December 2009 00:10:52 David Boddie wrote: > Doesn't the author give his e-mail address at the end of the video? > (Maybe I'm thinking of a different video.) > Yes, in a quick and garbled way :) I have yet to try to contact the author or the youtube poster -- been too busy. I was hoping someone on the list may recognize what tools he was using, or have some insight into how they would attack the problem. I have pondered it from a wxPython pov, that being all I am experienced with and I would have no chance of recreating that demo. Is it using some kind of built-in QT/KDE voodoo? \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyZui - anyone know about this?
On Friday 11 December 2009 12:38:46 Daniel Fetchinson wrote: > Youtube has a link 'Send message' on the profile of users, maybe > sending a message to the person who uploaded the video will give you a > useful response. > I'm a Tube-tard so that never crossed my mind. Will give it a go. \d -- http://mail.python.org/mailman/listinfo/python-list
pyZui - anyone know about this?
Hi, I happened upon this youtube link: http://www.youtube.com/watch?v=57nWm984wdY It fairly blew my socks off. In it a fellow by the name of David Roberts demos a zui written in Python. Aside from the zooming (which is impressive enough) it show embedding of images, pdf files, web pages and text. He says nothing about what toolkits were used or how it might have been done. It's Linux-based, but no other info. On some googling, I can only find a few bug reports on pypi related to pyQt. I would really like to find out how that ZUI was done, it's simply amazing. Any clues out there? \d -- \/\/ave: donn.in...@googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & Go
On Saturday 14 November 2009 22:23:40 Paul Rubin wrote: > they'll have to call it Go2 Lol. Or we could fork it and call it Gosub ... and never return! \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is python so sad?
> > def ...(...(: > > ... > > class ...(...(: > I disagree. It looks like one smiley is drooling into the other smiley's > mouth. Two smileys, one function? Yuk! That *def*initely has no *class* ... :P \d -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a unicode string to a file ?
On Friday 16 October 2009 13:08:38 Niklas Norrthon wrote: > that made me think I understand > Lol, I know the feeling! :D I have read that page a few times, and I always emerge thinking 'now I've got it'. Then a week passes... \d -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a unicode string to a file ?
On Friday 16 October 2009 01:59:43 Stephen Hansen wrote: > Just to say, thanks for that post. I am an old ascii dog and this notion of encoding and decoding is taking such a lng time to penetrate my thick skull. Little snippets like your post are valuable insights. I have made a gnote of it! \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Unexpected exit of Python script
On Wednesday 14 October 2009 14:23:11 vicky wrote: > I just want to know that, due to any reason if a script exits, is > their some way to release all the resources acquired by the script > during execution ? Python cleans-up after itself so I would not worry about that until you are an expert and need to split hairs. Just get on with learning and writing code. Look at exceptions (try, except) for this kind of thing -- but it's a basic part of learning Python anyway. About the only thing I ever found I could not catch was a segfault (under Linux) and to get around that I open my main app from a smaller one using the subprocess module. When the main app crashes (which it does sometime) that process dies suddenly, but it falls-back to the original script which then detects the error return code and can continue whatever it needs to do. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: What do I do now?
On Monday 12 October 2009 00:53:42 Someone Something wrote: > 1) What should I start programming (project that takes 1-2 months, not very > short term)? > 2) Whtat are some good open source projects I can start coding for? These kinds of questions amaze me. Surely you are a kid in a candy shop when it comes to things to code? The best place to start a project is to scratch an itch: pick something that really bugs you, or something that is plain missing, or something that you are interested in, and start solving the problem. No O/S or Desktop or App is perfect. There are a thousand gaps between all those things that need solutions or improvements. Find an "itch" and either: 1. Find a project in that direction and try to join. 2. Start your own. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Skeletal animation
On Monday 05 October 2009 18:09:46 Manowar wrote: > just need to know if i can manipulate the bones in > realtime with python. If you are looking for some kind of "from awesome import Bones", then I really don't know of anything. You should look at the various 3D toolkits (like Panda 3D, python-gl etc.) and use what they offer and extend it. see: http://www.panda3d.org/wiki/index.php/Attaching_an_Object_to_a_Joint \d -- http://mail.python.org/mailman/listinfo/python-list
Re: organizing your scripts, with plenty of re-use
Great description - wish the Python docs could be as clear. Thanks. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: SVG PIL decoder
On Thursday 01 October 2009 01:08:28 Patrick Sabin wrote: > Thanks for the tip. Got it work, although it was a bit tricky, as > resizing doesn't seem to be supported by python-rsvg and > cairo.ImageSurface.create_from_png doesn't allow StringIO or My best suggestions are to visit the Cairo website -- inside there somewhere is a recipe page with many samples in Python. Next would be http://www.tortall.net/mu/wiki/CairoTutorial. Third is a tutorial I made (perhaps less useful) on my site http://otherwise.relics.co.za/wiki/Tuts/Python/Cairo/ links at bottom of that page Fourth is to join the ca...@cairographics.org mailing list at http://lists.cairographics.org/mailman/listinfo/cairo they are super helpful. Lastly is my animation API (in sig)which is also Python and may help you with the source. The general idea for scaling is to use matrices (cairo provides all commands) and then output the surface to a file-like object. My animation API brings selected snippets of SVG in from an Inkscape file (tagged by id), animates them by tweening and can output each frame to another SVG or to a PNG. HTH, \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: SVG PIL decoder
On Wednesday 30 September 2009 18:01:50 Patrick Sabin wrote: > I would like to open svg files with PIL, but svg doesn't seem to be > supported. Does anyone know about a svg decoder for the PIL? Have a look at Cairo (python-cairo) in conjunction with librsvg (python-rsvg) -- that'll fix you up. You can go from an SVG to a PNG/array and thence into PIL if you need to. \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Distributing Python-programs to Ubuntu users
On Friday 25 September 2009 08:15:18 Olof Bjarnason wrote: > Does anyone have any hint on a more economic way of creating > single-file distribution packages You could use distutils (setup.py) and include a readme that explains what apt-get commands to use to install pygame, etc. Generally it's better to *not* include the kitchen-sink with your apps; rather expect the user to have those libraries already or be able to fetch them with ease. I did my best at explaining that deeply confusing setup.py process here: http://wiki.python.org/moin/Distutils/Tutorial I have also seen two other approaches: 1. A new app called 'Quickly' which is some kind of magical auto-do- everything-ubuntu connected to Launchpad. From what I hear it sounds very cool. https://wiki.ubuntu.com/DesktopTeam/Specs/Karmic/Quickly 2. The Ubuntu PPA repositories -- google around. (Seems Quickly does this too) hth, \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to truncate to get the 1st 5 chars from a string
On Thursday 24 September 2009 05:05:45 MacRules wrote: > s="1234abcd" print s[0:4] should do it. Not sure it's a function though. \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: arrays in python
On Wednesday 23 September 2009 22:12:24 Ethan Furman wrote: > Works great if you want 4,999,999 elements. ;-) Omit the '1' if you > want all five million. Yes. Fenceposts always get me :) And I was just reminded that one can: l=range(500) \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: arrays in python
On Wednesday 23 September 2009 19:14:20 Rudolf wrote: > I want to allocate an array and then populate it > using a for loop. You don't need to allocate anything, just use the list or dictionary types. l=[] #empty list for x in range(1,500): l.append(x) \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting return code for a Python script invoked from a Linux shell script
On Wednesday 23 September 2009 18:51:29 volcano wrote: > exit_code = !$ I think it's $? to get the code. \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: easy question, how to double a variable
On Monday 21 September 2009 22:49:50 daggerdvm wrote: > you brain needs error checking! try: return response() except Troll,e: raise dontFeed(anymore=True) \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print without spaces?
print "a"+"b" \d -- http://mail.python.org/mailman/listinfo/python-list
Re: ImageFont family mojibake
On Saturday 12 September 2009 17:30:19 garabik- news-2005...@kassiopeia.juls.savba.sk wrote: > apt-get install unicode > unicode 0100.. Nice tip, thanks. > if you see a lot of accented letters (and not squares or question marks), > you can be sure I see the accented chars -- so now I am more certain that the problem is in the font.family function. Something deep in the C code... \d -- http://mail.python.org/mailman/listinfo/python-list
Re: ImageFont family mojibake
On Saturday 12 September 2009 07:55:14 Lie Ryan wrote: > > f=ImageFont.truetype("FGTshgyo.TTF",1,encoding="utf-8") > > print f.font.family > > '?s' > Are you sure that your terminal (Command Prompt/bash/IDLE/etc) supports > utf-8 and that it is properly set up to display utf-8? Fairly sure... It's konsole under Kubuntu Jaunty. My locale it utf-8. To tell the truth I am not sure how to be sure. OTOH - when I pass that family name string to wxPython (unicode version) to be drawn to a DC it displays the exact same string that I see in Python's console. So even if my console is misconfigured, the string is still looking flawed. > Try: > print repr(f.font.family) Same result. Also same for print unicode(...) I wonder about the return result from f.font.family. If it was a unicode object should I not see u"s???" which would show that my terminal can't draw the glyphs, but it knows it's a unicode? print type(f.font.family) Hmmm. This seems wrong.But I could be making a mistake. > > I hope there's some simple encoding="voodoo" that might fix this. The > > problem is, I guess, knowing *what* that voodoo is for arbitrary fonts > > (which can come from any source). > If all else fails, you can simply compare the byte string representation > of the font family name. I don't follow this. What would I compare it to? Thanks for helping. \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
ImageFont family mojibake
Python 2.6 PIL Version: 1.1.6-3ubuntu1 libfreetype6 Version: 2.3.9-4ubuntu0.1 Hello, I have a feeling I've asked this in the distant past, but it's recently emerged as a bug in my app so can anyone point me in the right direction? In Fonty Python, when I draw the family name of a font some* are mojibaked (is that a word?) in the form: s??? etc. The string is drawn to a DC with wxPython, but is fetched from the font via ImageFont, like so: f=ImageFont.truetype("FGTshgyo.TTF",1,encoding="utf-8") print f.font.family '?s' So, the string is plain (not unicode) and wrong from the get-go. *"some" being those fonts that contain family names not in western encodings. The sample font that demonstrates the problem and was sent to me to test is called: BGPENKB.TTF another is FGTshgyo.TTF These are substantial files and I can't attach them to a list. if you need them for testing I can send them to another email address, or upload them somewhere. I have been oft helped in the past on matters unicode, but this does not mean I have grokked. (Alas my formative years were all spend in the fantasy of 8bit ascii :) ) I hope there's some simple encoding="voodoo" that might fix this. The problem is, I guess, knowing *what* that voodoo is for arbitrary fonts (which can come from any source). Any assistance would not go amiss. \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why can't I run this test class?
On Friday 11 September 2009 09:30:42 Kermit Mei wrote: Do this: class Test(object): > t1 = Test And this: t1 = Test() That makes an instance and runs the __init__ \d -- home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple unicode-safe version of str(exception)?
In article <[EMAIL PROTECTED]>, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > >> I have code like this: > >> except Exception, e: > >>self.setState(self.Failed, str(e)) > >> which fails if the exception contains a unicode argument. > > > > Fails how? > > ASCII encoding error, I suppose. It fails only if a) one argument > is a Unicode object, and b) that Unicode object contains non-ASCII > parameters. Seem ironic that this fails even though pretty nearly anything else is a valid input to str() -- socket, dict, whatever? A sort of generic solution might be to follow str's behavior with respect to '__str__', extending it to fall back to repr() whatever goes wrong. def xtr(a): try: return str(a) except: return repr(a) ... self.setState(self.Failed, xtr(e)) Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k concerns. An example
In article <[EMAIL PROTECTED]>, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > > I still think it's a shame > [...] > > pps: I have to note that it would be nice if the > > ad-hominem (sp?) invective would drop out of > > these threads -- it doesn't add a lot, I think. > > shame > 1 a. a painful emotion caused by consciousness of guilt, > shortcoming, or impropriety > 2 a condition of humiliating disgrace or disrepute - [in sing.] a regrettable or unfortunate situation or action: `it is a shame that they are not better known' If English isn't your 1st language, you deserve a lot of credit for your mastery of it, but you need a better dictionary. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
In article <[EMAIL PROTECTED]>, Steve Holden <[EMAIL PROTECTED]> wrote: > Aaron Watters wrote: > > The cost paid for these minor improvements is too high in my > > book. But I suppose if it is going to happen do it sooner > > rather than later. Just *please* *please* don't > > systematically break the pre-existing code base again for a > > very long time, preferable ever. > > I'm pretty sure the 3.0 compatibility breakage is a one-shot deal. If > it's not I won't be the only one looking for Guido with a bog stick in > my hand ... Depending on what you mean, that appears to be either a truism or an absurdity. If you mean, 3.1 won't break code like 3.0 did ... well, of course. If you mean, there won't be a 4.0 that means the same thing for compatibility that 3.0 means, then I can't imagine how you could be convinced of this. Changes to Python in 3.0 won't satisfy the continuing "need" for change thereafter. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
In article <[EMAIL PROTECTED]>, Aaron Watters <[EMAIL PROTECTED]> wrote: > Maybe there is a secret desire in the Python > community to remain a fringe minority underdog > forever? I'm sure anyone who has given it any thought understands that the fringe minority situation is a lot more fun in some ways, but I think if you were to apply a sort of conspiracy analysis to the situation - "who benefits from language change" - this would be a couple items down on the list of motivations. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
In article <[EMAIL PROTECTED]>, Sverker Nilsson <[EMAIL PROTECTED]> wrote: > No one forces me, but sooner or later they will want a Python 3.0 and > then a 3.1 whatever. > > I don't want that fuzz. As about the C versions, I am not that > worried. What's your point? > > I just like want to write a program that will stay working. And maybe > I can go on with something else hopefully than just compatibility > fixes. They take some work afterall. > > It seems hard with Python. Esp. 2 -> 3 Welcome to the world of Python. There was a period of relative stability in the '90s, culminating with version 1.5.2, which just happens to be about the time that people started taking Python seriously. It turns out that this stability was only due to lack of resources, though. I think most of us are working under two imperatives here that really boil down to the same thing: we want a programming language that lets us focus on the goal of the program. On one hand, that means things like automatic memory management that are brought to us by newer languages (i.e., less than 30 years old.) On the other hand it means stability that allows our deployed code to go on working without constant intervention, which usually we find in languages that have become utterly boring and out of fashion (i.e., more than 30 years old.) It's hard to find a good compromise between these two, in an interpreted language. I don't know what the current party line may be on this matter, but some years back it was that you should consider the interpreter part of your application. That is, each application should deploy with its own dedicated Python interpreter, complete with libraries and everything. This naturally relieves some of the maintenance issues, since at least you can upgrade on your own schedule, but of course it has its costs too. Anyone who might be thinking about using Python for an application should seriously think about this. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: pty.spawn directs stderr to stdout
In article <[EMAIL PROTECTED]>, Wilbert Berendsen <[EMAIL PROTECTED]> wrote: > Hi, > > using pty.spawn() it seems that stderr output of the spawned process is > directed to stdout. Is there a way to keep stderr separate and only direct > stdin and stdout to the pty? There is, of course. First, you have to decide where you want unit 2 ("stderr") to go, and then get the spawned process to redirect it there. If a disk file will do, then your question is just "how do I redirect error output to a disk file, in ___" (fill in the blank with language used to implement the spawned process - UNIX shell? Python? C?) More likely, you want the spawned process' error output to go wherever the parent's error output was going. This is a little trickier. Ideally, your spawned shell script can conveniently take a new parameter that identifies the new file descriptor unit number for error output. In this case, use fd2 = os.dup(2) to get a new duplicate, add a parameter like -e str(fd2), and in the spawned process, redirect from that unit - in UNIX shell, exec 2>&$fd2 Or you could use an environment variable to identify the backup error unit, if the command line parameter option isn't available for some reason. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Orphaned child processes
In article <[EMAIL PROTECTED]>, John Nagle <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > I'm using the Python processing module. I've just run into a problem > > though. Actually, it's a more general problem that isn't specific to > > this module, but to the handling of Unix (Linux processes) in general. > > Suppose for instance that for some reason or another, after forking > > several child processes, the main process terminates or gets killed > > (or segfaults or whatever) and the child processes are orphaned. Is > > there any way to automatically arrange things so that they auto- > > terminate or, in other words, is there a way to make the child > > processes terminate when the parent terminates? > > > > Thank you. > > Put a thread in the child which reads stdin, and make stdin > connect to a pipe from the parent. When the parent terminates, > the child will get a SIGPIPE error and raise an exception. > > John Nagle That could work, but not precisely in that manner. You get SIGPIPE when you write to a closed pipe. When you read from one, you get end of file, i.e., a normal return with 0 bytes. When you test it, make sure to try a configuration with more than one child process. Since the parent holds the write end of the pipe, subsequently forked child processes could easily inherit it, and they'll hold it open and spoil the effect. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Summary of threading for experienced non-Python programmers?
In article <[EMAIL PROTECTED]>, Paul Rubin <http://[EMAIL PROTECTED]> wrote: > Select blocks until the data is ready, while with AIO the i/o happens > completely in the background and your process gets an interrupt when > the i/o completes. Also, with select based i/o, usually the kernel > reads data from the external device into a system buffer, and then you > do a read system call that copies the data from the system buffer to > your buffer. AIO can be set up so the i/o happens directly into your > buffer, avoiding the extra copying. You can also initiate a bunch of > different i/o events with a single system call, avoiding some context > switches. > > http://www.ibm.com/developerworks/linux/library/l-async/ > > describes select as "asynchronous, blocking" as opposed to AIO which > is asynchronous and nonblocking. Other descriptions I've seen reserve > "asynchronous i/o" for AIO-like schemes. It's just a terminological > thing. kqueue(2) on MacOS X mentions an EVFILT_AIO option. It isn't supported on that platform, but maybe that's a vestige of some other platform that does support "asynchronous, blocking" with aio -- as VAX/VMS did (and presumably still does), with event flags. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Summary of threading for experienced non-Python programmers?
In article <[EMAIL PROTECTED]>, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > systems. (In theory, file input/output should also be available as > > asynchronous code, but async IO is low-level and not available in > > Python.) While threads shouldn't be considered a replacement for > > I suggest you tell that the twisted-guys. And the ones from the built-in > asyncore-module. > > They will be surprised to hear that their years worth of working code > will evaporate in a rosa cloud. > > Diez I appreciate the droll sense of humor, but do you mean to assert that asyncore.py supports asynchronous disk file I/O? What that means to me is, you queue a disk read, and there's an event flag or something that you can wait for before you come back to find the data in your buffer. (That's how I remember it from the old days, when it mattered a little, though not enough that I ever remember actually doing it, and 20 years later I guess the incentive is even less.) I see MacOS supports an F_RDADVISE that might give you a head start on reading into the system buffer, but that's 3rd rate asynchrony because there's no way to know when the data is ready, and 3rd rate I/O because afterwards you still have the copying to do. I don't see even this much in asyncore.py, but I just gave it a glance. thanks, Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What Programming Languages Should You Learn Next?
In article <[EMAIL PROTECTED]>, Paul Rubin <http://[EMAIL PROTECTED]> wrote: ... > I think it's easier to write complex code in Haskell because: > > 1) it has a powerful static type system that lets you express > important invariants and have them enforced at compile time. This not > only catches errors but helps you understand the program logic almost > like running the code under a debugger does. If you try to fill a gap > by putting in a piece of the wrong shape, it just won't fit and the > compiler will tell you what you really wanted. On the other hand, > most types are inferred by the compiler, so you don't need a lot of > cumbersome declarations like in Java. Worth repeating. One of the perhaps surprising consequences, Haskell code can be very easy to modify. I've been fooling around with computer programs for a couple decades, and I'm just getting used to the idea that I can casually rewrite Haskell code and get the compiler to find what I missed. I have come to feel that the indiscipline of dynamic typing in languages like Python leads to an intuitively surprising rigidity. Ten years ago I would cheerfully accept this, given the meager and clumsy support for static typing in languages like C++, but today, it makes me appreciate Haskell's potential for complex projects. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt should not kill subprocess
In article <[EMAIL PROTECTED]>, Michael Goerz <[EMAIL PROTECTED]> wrote: > But as it seems, a keyboard interrupt will automatically pass down to > the subprocesses, causing them to abort. Is there a way that I can > prevent the subprocesses from being canceled by a keyboard interrupt? You might try posix.setsid(), from the child fork. The object is to get the child fork out of the foreground process group for the Berkeley terminal driver. This defines who gets signals, when they originate in terminal control keys. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Nick Craig-Wood wrote: > This iterates over the lines of all files listed in sys.argv[1:], > defaulting to sys.stdin if the list is empty. If a filename is '-', it > is also replaced by sys.stdin. To specify an alternative list of > filenames, pass it as the first argument to input(). A single file > name is also allowed. Yeah it has been discussed. It seems the one problem with it is that it opens each file. I only want the filenames. Anyway, this has more-or-less been solved now. Thanks, \d -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Hexamorph wrote: > It's a bit clumsy, but seems to do what I guess you want. Hey, thanks for that! I will have a go. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Andrew, Thanks for your tips. I managed to get a working script going. I am sure there will be stdin 'issues' to come, but I hope not. If anyone wants to have a look, it's on the cheese shop at: http://pypi.python.org/pypi/fui \d -- "You know, I've gone to a lot of psychics, and they've told me a lot of different things, but not one of them has ever told me 'You are an undercover policewoman here to arrest me.'" -- New York City undercover policewoman Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Thanks for the tips, I'll decode and try 'em all out. > Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought > each other? Heh ;) I reckon they'd both die laughing. Be fun to watch -- if anyone else survived! \d -- "A computer without Windows is like chocolate cake without mustard." -- Anonymous Coward /. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
> wget -i - > it doesn't do anything, just waits for your input. Your applications > probably should behave the same. Okay, that works for me. > Paddy wrote: > > ls *.a | ./fui.py -f - *.b > It doesn't seem to me that -f parameter is necessary for your > application. Yes and no, I have another option that needs to take a variable number of args. > It should treat all the arguments as the filenames, > shouldn't it? And when one of the filenames is -, just try to read > stdin. I have tested getopt and it strips the lone '-' out. I can get it from sys.argv, but then I am really doing more parsing than I want to. It's a tricky job this. I think I will look in sys.argv, if I find a single dash the I will replace that element in the list with whatever comes from stdin. Then I'll pass all of it to getopt. Thanks for the help. \d -- When you allow legends to rule your life, your world is based on fiction -- Segio Aragones (Groo the Wanderer Number 99) Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Paddy wrote: > fileinput is set to process each file a line at a time unfortunately. Wow. So there seems to be no solution to my OP. I'm amazed, I would have thought a simple list of strings, one from stdin and one from the args, would be easy to get. I *really* don't want to open each file, that would be insane. Perhaps I shall have to forgo the stdin stuff then, after all. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Paddy wrote: > ls *.a | ./fui.py -f - *.b To be sure I grok this: I am seeing the single dash as a placeholder for where all the piped filenames will go, so *.b happens after *.a has been expanded and they all get fed to -f, right? I'm also guessing you mean that I should detect the single dash and then go look for stdin at that point. How do I detect a lack of stdin? Thanks, \d -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
> Try the fileinput module. I did give the fileinput module a go, but I can't find much info on it and the help is ... well, it's python help ;) > in goes to its stdin where it is processed if it has an argument of - > fileinput works that way Okay, I did think of the dash, but did not know how to handle it. Is it a bash thing or will that dash get passed into the args? (I am using getopt to parse the options and args) > which would work for ls and a python program using the fileinput > module. Any examples of fileinput (that do not open each file) would be great! (I'll go searching now anyway) Thanks, \d -- http://mail.python.org/mailman/listinfo/python-list
piping into a python script
Hi, (Gnu/Linux - Python 2.4/5) Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? 2. import fileinput for line in fileinput.input(): print (line) But this opens each file and I don't want that. I have seen a lot of search results that don't quite answer this angle of the question, so I'm trying on the list. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
> You get the full locale name with locale.setlocale(category) (i.e. > without the second argument) Ah. Can one call it after the full call has been done: locale.setlocale(locale.LC_ALL,'') locale.setlocale(locale.LC_ALL) Without any issues? > > I need that two-letter code that's hidden in a > > typical locale like en_ZA.utf8 -- I want that 'en' part. Okay, I need it because I have a tree of dirs: en, it, fr and so on for the help files -- it's to help build a path to the right html file for the language being supported. > Not sure why you want that. Notice that the locale name is fairly system > specific, in particular on non-POSIX systems. It may be > "English_SouthAfrica" on some systems. Wow, another thing I had no idea about. So far all I've seen are the xx_yy.utf8 shaped ones. I will have some trouble then, with the help system. Thanks, \d -- "There may be fairies at the bottom of the garden. There is no evidence for it, but you can't prove that there aren't any, so shouldn't we be agnostic with respect to fairies?" -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Given that getlocale() is not to be used, what's the best way to get the locale later in the app? I need that two-letter code that's hidden in a typical locale like en_ZA.utf8 -- I want that 'en' part. BTW - things are hanging-together much better now, thanks to your info. I have it running in locale 'C' as well as my other test locales. What a relief! \d -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
> Can you please type > paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] > f = open(paf, "r") I think I was getting a ghost error from another try somewhere higher up. You are correct, this does open the file - no matter what the locale is. I have decided to keep the test for a decode error because files created under different locales should not be written-to under the current one. I don't know if one can mix encodings in a single text file, but I don't have time to find out. It is getting messy with my test files created in differing locales, and my code changing so quickly. > See above. The encoding in codecs.open has no effect at all on > the file name; it only talks about the file content. Thanks, I suspected as much but it's a subtle thing. Best, \d -- "It is almost as if the human brain were specifically designed to misunderstand Darwinism, and to find it hard to believe.." -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
> Now you are mixing two important concepts - the *contents* > of the file with the *name* of the file. Then I suspect the error may be due to the contents having been written in utf8 from previous runs. Phew! It's bedtime on my end, so I'll try it again when I get a chance during the week. Thanks muchly. \d -- snappy repartee: What you'd say if you had another chance. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Well, that didn't take me long... Can you help with this situation? I have a file named "MÖgul.pog" in this directory: /home/donn/.fontypython/ I set my LANG=C Now, I want to open that file from Python, and I create a path with os.path.join() and an os.listdir() which results in this byte string: paf = ['/home/donn/.fontypython/M\xc3\x96gul.pog'] I *think* that the situation is impossible because the system cannot resolve the correct filename (due the locale being ANSI and the filename being other) but I am not 100% sure. So, I have been trying combinations of open: 1. f = codecs.open( paf, "r", "utf8" ) I had hopes for this one. 2. f = codecs.open( paf, "r", locale.getpreferredencoding()) 3. f = open( paf, "r") But none will open it - all get a UnicodeDecodeError. This aligns with my suspicions, but I wanted to bounce it off you to be sure. It does not really mesh with our previous words about opening all files as bytestrings, and admits failure to open this file. Also, this codecs.open(filename, "r", ) function: 1. Does it imply that the filename will be opened (with the name as it's type : i.e. bytestring or unicode ) and written *into* as 2. Imply that filename will be encoded via and written into as It's fuzzy, how is the filename handled? \d -- He has Van Gogh's ear for music. -- Billy Wilder Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, I want to thank you for your patience, you have been sterling. I have an overview this evening that I did not have this morning. I have started fixing my code and the repairs may not be that extreme after all. I'll hack-on and get it done. I *might* bug you again, but I'll resist at all costs :) Much appreciated. \d -- "A computer without Windows is like chocolate cake without mustard." -- Anonymous Coward /. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
> No. It may use replacement characters (i.e. a question mark, or an empty > square box), but if you don't see such characters, then the terminal has > successfully decoded the file names. Whether it also correctly decoded > them is something for you to check (i.e. do they look right?) Okay. So, the picture I get is: *If* my locale *happens* to be the right one then the filename will appear properly. If it does not cover that file, then that filename will appear with ? marks in the name. Because I use en_ZA.utf8 it's doing a very good job of decoding a wide variety of filenames and therefore I rarely see ? characters. What happens if there is a filename that cannot be represented in it's entirety? i.e. every character is 'replaced'. Does it simply vanish, or does it appear as "?" ? :) I spent an hour trying to find a single file on the web that did *not* have (what seemed like) ascii characters in it and failed. Even urls on Japanese websites use western characters ( a tcp/ip issue I suspect). I was hoping to find a filename in Kanji (?) ending in .jpg or something so that I could download it and see what my system (and Python) made of it. Thanks again, \d -- "Life results from the non-random survival of randomly varying replicators." -- Richard Dawkins Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
> If you can all ls them, and if the file names come out right, then > they'll have the same encoding. Could it not be that the app doing the output (say konsole) could be displaying a filename as best as it can (doing the ignore/replace) trick and using whatever fonts it can reach) and this would disguise the situation? I don't think one can call any string a plain ascii string anymore. I have been looking for somewhere online that I can download files obviously in a non-ascii set (like japan someplace) but can't find anything easy. I want to see exactly how my system (Kubuntu 7.10) handles things. > I never heard before that font files use non-ASCII file names, They are files, named as any other file - those that are created by people get called whatever they want, under whatever locale they used. Still, I don't fully understand how this is all handled. > don't see the point in doing so - isn't there typically a font name > *inside* the font file as well, so that you'd rather use that for > display than the file name? Yes, but sometimes I can't reach that - segfaults and so forth. I also need to write the filename to a text file for logging. > Of course, *other* files (text files, images etc) will often use > non-ASCII file names. Same as font files - I am talking mainly about TTF files here. Mainly Arrr, pass the rum, matey fonts ;) (Which I don't use in designs, but have kept over the years.) > However, they won't normally have mixed > encodings - most user-created files on a single system should typically > have the same encoding (there are exceptions possible, of course). Well, if I am collecting fonts from all over the place then I get a mixed-bag. > > Meaning, I am led to assume, the LANG variable primarily? > Yes. Thanks. Good to know I'm on the right track. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
> So on *your* system, today: what encoding are the filenames encoded in? > We are not talking about arbitrary files, right, but about font files? > What *actual* file names do these font files have? > > On my system, all font files have ASCII-only file names, even if they > are for non-ASCII characters. I guess I'm confused by that. I can ls them, so they appear and thus have characters displayed. I can open and cat them and thus the O/S can access them, but I don't know whether their characters are strictly in ascii-limits or drawn from a larger set like unicode. I mean, I have seen Japanese characters in filenames on my system, and that can't be ascii. You see, I have a large collection of fonts going back over 10 years and they came from usenet years ago and so have filenames mangled all to hell. I can't always *type* some of their names and have to use copy/paste to, for example, ls one of them. Again, it's working from ignorance (my own) : I assume filenames in different countries will be in character sets that I have never (nor will I ever) see. But I have to cover them somehow. > > Or is that a waste of time because os.listdir() has already tried > > something similar (and prob. better)? > "better" is a difficult notion here. Is it better to produce some > result, possibly incorrect, or is it better to give up? I think I see, combined with your previous advice - I will keep byte strings alongside unicode and where I can't get to the unicode for that string, I will keep an 'ignore' or 'replace' unicode, but I will still have the byte string and will access the file with that anyway. > If the user has set up his machine correctly: yes. Meaning, I am led to assume, the LANG variable primarily? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, > Yes. It does so when it fails to decode the byte string according to the > file system encoding (which, in turn, bases on the locale). That's at least one way I can weed-out filenames that are going to give me trouble; if Python itself can't figure out how to decode it, then I can also fail with honour. > > I will try the technique given > > on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html > >#guessing-the-encoding Perhaps that will help. > I would advise against such a strategy. Instead, you should first > understand what the encodings of the file names actually *are*, on > a real system, and draw conclusions from that. I don't follow you here. The encoding of file names *on* a real system are (for Linux) byte strings of potentially *any* encoding. os.listdir() may even fail to grok some of them. So, I will have a few elements in a list that are not unicode, I can't ask the O/S for any help and therefore I should be able to pass that byte string to a function as suggested in the article to at least take one last stab at identifying it. Or is that a waste of time because os.listdir() has already tried something similar (and prob. better)? > I notice that this doesn't include "to allow the user to enter file > names", so it seems there is no input of file names, only output. I forgot to mention the command-line interface... I actually had trouble with that too. The user can start the app like this: fontypython /some/folder/ or fontypython SomeFileName And that introduces input in some kind of encoding. I hope that locale.getprefferedencoding() will be the right one to handle that. Is such input (passed-in via sys.argv) in byte-strings or unicode? I can find out with type() I guess. As to the rest, no, there's no other keyboard input for filenames. There *is* a 'filter' which is used as a regex to filter 'bold', 'italic' or whatever. I fully expect that to give me a hard time too. > Then I suggest this technique of keeping bytestring/unicode string > pairs. Use the Unicode string for display, and the byte string for > accessing the disc. Thanks, that's a good idea - I think I'll implement a dictionary to keep both and work things that way. > I see no problem with that: > >>> u"M\xd6gul".encode("ascii","ignore") > 'Mgul' > >>> u"M\xd6gul".encode("ascii","replace") > 'M?gul' Well, that was what I expected to see too. I must have been doing something stupid. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, Thanks, food for thought indeed. > On Unix, yes. On Windows, NTFS and VFAT represent file names as Unicode > strings always, independent of locale. POSIX file names are byte > strings, and there isn't any good support for recording what their > encoding is. I get my filenames from two sources: 1. A wxPython treeview control (unicode build) 2. os.listdir() with a unicode path passed to it I have found that os.listdir() does not always return unicode objects when passed a unicode path. Sometimes "byte strings" are returned in the list, mixed-in with unicodes. I will try the technique given on:http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html#guessing-the-encoding Perhaps that will help. Re os.listdir(): > If you think you may have file names with mixed locales, and > the current locale might not match the file name's locale, you should > be using the byte string variant on Unix (which it seems you are already > doing). I gather you mean that I should get a unicode path, encode it to a byte string and then pass that to os.listdir Then, I suppose, I will have to decode each resulting byte string (via the detect routines mentioned in the link above) back into unicode - passing those I simply cannot interpret. > Then, if the locale's encoding cannot decode the file names, you have > several options > a) don't try to interpret the file names as character strings, i.e. >don't decode them. Not sure why you need the file names - if it's >only to open the files, and never to present the file name to the >user, not decoding them might be feasible So, you reckon I should stick to byte-strings for the low-level file open stuff? It's a little complicated by my using Python Imaging to access the font files. It hands it all over to Freetype and really leaves my sphere of savvy. I'll do some testing with PIL and byte-string filenames. I wish my memory was better, I'm pretty sure I've been down that road and all my results kept pushing me to stick to unicode objects as far as possible. > b) guess an encoding. For file names on Linux, UTF-8 is fairly common, >so it might be a reasonable guess. > c) accept lossy decoding, i.e. decode with some encoding, and use >"replace" as the error handler. You'll have to preserve the original >file names along with the decoded versions if you later also want to >operate on the original file. Okay, I'm getting your drift. > That's not true. Try open("\xff","w"), then try interpreting the file > name as UTF-8. Some byte strings are not meaningful UTF-8, hence that > approach cannot work. Okay. > That's correct, and there is no solution (not in Python, not in any > other programming language). You have to made trade-offs. For that, > you need to analyze precisely what your requirements are. I would say the requirements are: 1. To open font files from any source (locale.) 2. To display their filename on the gui and the console. 3. To fetch some text meta-info (family etc.) via PIL/Freetype and display same. 4. To write the path and filename to text files. 5. To make soft links (path + filename) to another path. So, there's a lot of unicode + unicode and os.path.join and so forth going on. > > I went through this exercise recently and had no joy. It seems the string > > I chose to use simply would not render - even under 'ignore' and > > 'replace'. > I don't understand what "would not render" means. I meant it would not print the name, but constantly throws ascii related errors. I don't know if the character will survive this email, but the text I was trying to display (under LANG=C) in a python script (not the immediate-mode interpreter) was: "MÖgul". The second character is a capital O with an umlaut (double-dots I think) above it. For some reason I could not get that to display as "M?gul" or "Mgul". BTW, I just made that up - it means nothing (to me). I hope it's not a swear word in some other language :) > As for font files - I don't know what encoding the family is in, but > I would sure hope that the format specification of the font file format > would also specify what the encoding for the family name is, or that > there are at least established conventions. You'd think. It turns out that font file are anything but simple. I am doing my best to avoid being sucked-into the black hole of complexity they represent. I must stick to what PIL/Freetype can do. The internals of font-files are waay over my head. > >> I would avoid locale.getlocale. It's a pointless function (IMO). > As a consequence, it will return None if it doesn't know better. > If all you want is the charset of the locale, use > locale.getpreferredencoding(). Brilliant summary - thanks a lot for that. > You could just leave out the languages parameter, and trust gettext > to find some message catalog. Right - I'll give that a go. > > This would mean cutting-out a percentage of the external font files that > > can be used by the a
Re: LANG, locale, unicode, setup.py and Debian packaging
Martin, I really appreciate your reply. I have been working in a vacuum on this and without any experience. I hope you don't mind if I ask you a bunch of questions. If I can get over some conceptual 'humps' then I'm sure I can produce a better app. > That's a bug in the app. It shouldn't assume that environment variables > are UTF-8. Instead, it should assume that they are in the locale's > encoding, and compute that encoding with locale.getpreferredencoding. I see what you are saying and agree, and I am confused about files and filenames. My app has to handle font files which can come from anywhere. If the locale (locale.getpreferredencoding) returns something like "ANSI" and I am doing an os.listdir() then I lose the plot a little... It seems to me that filenames are like snapshots of the locales where they originated. If there's a font file from India and I want to open it on my system in South Africa (and I have LANG=C) then it seems that it's impossible to do. If I access the filename it throws a unicodeDecodeError. If I use 'replace' or 'ignore' then I am mangling the filename and I won't be able to open it. The same goes for adding 'foreign' filenames to paths with any kind of string operation. My (admittedly uninformed) conception is that by forcing the app to always use utf8 I can access any filename in any encoding. The problem seems to be that I cannot know *what* encoding (and I get encode/decode mixed up still, very new to it all) that particular filename is in. Am I right? Wrong? Deluded? :) Please fill me in. > If you print non-ASCII strings to the terminal, and you can't be certain > that the terminal supports the encoding in the string, and you can't > reasonably deal with the exceptions, you should accept moji-bake, by > specifying the "replace" error handler when converting strings to the > terminal's encoding. I went through this exercise recently and had no joy. It seems the string I chose to use simply would not render - even under 'ignore' and 'replace'. It's really frustrating because I don't speak a non-ascii language and so can't know if I am testing real-world strings or crazy Tolkein strings. Another aspect of this is wxPython. My app requires the unicode build so that strings have some hope of displaying on the widgets. If I access a font file and fetch the family name - that can be encoded in any way, again unknown, and I want to fetch it as 'unicode' and pass it to the widgets and not worry about what's really going on. Given that, I thought I'd extend the 'utf8' only concept to the app in general. I am sure I am wrong, but I feel cornered at the moment. > > 3. I made the decision to check the locale and stop the app if the return > > from getlocale is (None,None). > I would avoid locale.getlocale. It's a pointless function (IMO). Could you say why? Here's my use of it: locale.setlocale( locale.LC_ALL, "" ) loc = locale.getlocale()[0] if loc == None: loc = locale.getlocale() if loc == (None, None): print localeHelp # not utf-8 (I think) raise SystemExit # Now gettext domain = "all" gettext.install( domain, localedir, unicode = True ) lang = gettext.translation(domain, localedir, languages = [loc] ) lang.install(unicode = True ) So, I am using getlocale to get a tuple/list (easy, no?) to pass to the gettext.install function. > Your program definitely, absolutely must work in the C locale. Of > course, you cannot have any non-ASCII characters in that locale, so > deal with it. This would mean cutting-out a percentage of the external font files that can be used by the app. Is there no modern standard regarding the LANG variable and locales these days? My locale -a reports a bunch of xx_XX.utf8 locales. Does it even make sense to use a non-utf8 locale anymore? > If you have solved that, chances are high that it will work in other > locales as well (but be sure to try Turkish, as that gives a > surprising meaning to "I".lower()). Oh boy, this gives me cold chills. I don't have the resources to start worrying about every single language's edge-cases. This is kind of why I was leaning towards a "use a utf8 locale please" approach. \d -- Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
LANG, locale, unicode, setup.py and Debian packaging
Hello, I hope someone can illuminate this situation for me. Here's the nutshell: 1. On start I call locale.setlocale(locale.LC_ALL,''), the getlocale. 2. If this returns "C" or anything without 'utf8' in it, then things start to go downhill: 2a. The app assumes unicode objects internally. i.e. Whenever there is a "string like this" in a var it's supposed to be unicode. Whenever something comes into the app (from a filename, a file's contents, the command-line) it's assumed to be a byte-string that I decode("utf8") on before placing it into my objects etc. 2b. Because of 2a and if the locale is not 'utf8 aware' (i.e. "C") I start getting all the old 'ascii' unicode decode errors. This happens at every string operation, at every print command and is almost impossible to fix. 3. I made the decision to check the locale and stop the app if the return from getlocale is (None,None). 4. My setup.py (distutils) also tests locale (because it then loads gettext to give localized information to the user during setup). 5. Because it's doing a raise SystemExit if the locale is (None,None) which happens if LANG is set to "C", the setup.py stops. 6. Someone is helping me to package the app for Debian/Ubuntu. During the bizarre amount of Voodoo they invoke to do that, the setup.py is being run and it is breaking out because their LANG is set to "C" 7. I have determined, as best I can, that Python relies on LANG being set to a proper string like en_ZA.utf8 (xx_YY.encoding) and anything else will start Python with the default encoding of 'ascii' thus throwing the entire app into a medieval dustbin as far as i18n goes. 8. Since I can't control the LANG of the user's system, and I am relying on it containing 'utf8' in the locale results.. well I seem to be in a catch-22 here. Does anyone have some ideas? Is there a universal "proper" locale that we could set a system to *before* the Debian build stuff starts? What would that be - en_US.utf8? Any words of wisdom would help. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n questions
Thorsten Kampe wrote: > gettext.textdomain('optparse') > gettext.install('script', unicode = True) They speak of a 'global' domain in the docs, but (as is my usual beef with the Python docs -- see PHP docs for sterling help) there is no clarity. It *sounds* like there can be a .mo file for *everything* and then one can also install others on a per-script/module basis, as your code seems to suggest. All very confusing. I have had an entire day to stew and I spent it combining all my po files into one big file. Now I install that once, and efficiency be damned. Still, I'm interested in what's possible and I'll give your approach a whirl. Don't let the thread die yet, c'mon you i18n boffins! Thanks, \d -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n questions
Is there a group better suited to gettext/i18n questions of this sort? Just wondering because I have little time left to finish my "December" project! > How does one 'merge' gettext.translations objects together? Or is that > insane? > > What's the best way to handle a project with multiple domain.mo files? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n questions
Thanks for taking the time to post those links. I have read most of them before. They don't seem to cover the basic issue in my OP, but i18n on Python is a dark art and maybe there's something I missed. \d -- http://mail.python.org/mailman/listinfo/python-list
i18n questions
Hi, A soon-to-be happy new year to everyone! I'm 100% new to this i18n lark and my approach so far has been to create a .mo file per module in my app. My thinking was, why load one huge .mo file when a single module only needs a few strings? Since then, it seems, I have made the wrong decision. For example I have module A that imports module B. Each one does this: gettext.install( domain, localedir, unicode = True ) lang = gettext.translation(domain, localedir, languages = [ loc ] ) lang.install(unicode = True ) (where doman is the name of the module, so "A" and "B") The problem is that domain "A" loads and then import B happens and so the "lang" reference (I think) gets replaced by domain "B" -- the result is that module A can only translate strings that are in domain "B". How does one 'merge' gettext.translations objects together? Or is that insane? What's the best way to handle a project with multiple domain.mo files? I hope someone can give me some advice. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Objects by property using locale
> Which is even more correct than I hoped for -- in Norwegian, aa is > pronounced the same as å (which is the 29th letter in the Norwegian > alphabet) and is sorted according to pronunciation. Much appreciated bjorn. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Objects by property using locale
In follow-up: I think this should work: # -*- coding: utf8 -*- import locale locale.setlocale( locale.LC_ALL, "" ) class Test(object): def __init__(self,nam): self.name = nam def __cmp__(self, other): return cmp(self.name, other.name) l = [ Test("ABILENE.ttf"), Test("Årgate.ttf"), Test("årse.ttf"), Test("Ärt.ttf"), Test("MomentGothic.ttf"), Test("öggi.ttf"), Test("Öhmygawd.ttf")] l.sort( cmp=locale.strcoll, key=lambda obj:obj.name ) for i in l: print i.name Any bugs? \d -- http://mail.python.org/mailman/listinfo/python-list
Sorting Objects by property using locale
Hi, Well, I'm beat. I can't wrap my head around this stuff. I need to create a list that will contain objects sorted by a "name" property that is in the alphabetical order of the user's locale. I used to have a simple list that I got from os.listdir and I could do this: l = os.listdir(".") l.sort(locale.strcoll) Which would work fine. But now I need to make objects (of different stripes) for each of the filenames returned and then I want to collect them all into a main list and have *that* main list be sorted. I started some test code like this: I hope the odd characters show. # -*- coding: utf8 -*- class Test(object): def __init__(self,nam): self.name = nam def __cmp__(self, other): return cmp(self.name, other.name) l = [ Test("ABILENE.ttf"), Test("Årgate.ttf"), Test("årse.ttf"), Test("Ärt.ttf"), Test("MomentGothic.ttf"), Test("öggi.ttf"), Test("Öhmygawd.ttf")] import locale l.sort() # won't work -> locale.strcoll) for i in l: print i.name Can anyone give me a leg-up? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: import X between submodules in a package
> You guess. When fisrt imported, the module's source is executed, a > module object is created and stored in sys.modules, and the needed names > are inserted into the importing module's namespace. Next times the > module is "served" directly from sys.modules. Peachy, thanks. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: import X between submodules in a package
Chris wrote: > print cli.os.environ['HOME'] I was really confused by your reply until I saw the cli.os part. Okay, I see what you mean. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: import X between submodules in a package
> would be a VeryBadThing(tm). :) > Having explicits imports in each module is good wrt/ readability. Okay, I can accept that. I worry that it's opening the module file over and over again - or does it open it once and kind of re-point to it when it hits a second import of the same thing? > package, you can of course factor them out in a distinct submodule and > just do a 'from myimports import *' at the top of the others submodules... Good point. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Gnu/Linux dialogue boxes in python
> I've now uploaded a new release of the desktop module which is now, in > fact, a package: Thanks Paul, I saw it via the cheese shop rss. I have been too busy to read this list for a week. I will have a look in due course. \d -- http://mail.python.org/mailman/listinfo/python-list
import X between submodules in a package
Hi, I'm sure this is a FAQ, but I have just not found clarity on the web/docs. (using monospaced type to show the tree) trunk:$ tree . fp |-- fontypython | |-- __init__.py | |-- cli.py | |-- config.py (I start it all with ./fp) fp says: import cli cli.py says: import os import config config.py says: print os.environ['HOME'] I get a NameError in config.py If I add 'import os' to config.py all is well. So, I guess I am confused about the 'scope' of what gets imported where. I am thinking that if one module (py file) does *import os* something and *then* imports another module - the second module should have access to os too? I imagine myself "standing" inside cli.py at this point and saying "well I can see os, and I'm bringing config *into* this space, so they should be able to see os too." How do I structure things so that I don't have endless repetitions of import in every py file within my package directory? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: callback confusion
> As far as I can tell, you have a bit more code in boo, and somewhere in > that code (after the print statement), you rebind the name 'kills'. Okay, yes: def boo() kills += 1 print kills > the absence of a global declaration, this makes this name a local > variable. I think I see what you mean: >>> kills=0 >>> def boo(): ... kills += 1 ... print kills ... >>> print kills 0 >>> boo() Traceback (most recent call last): File "", line 1, in File "", line 2, in boo UnboundLocalError: local variable 'kills' referenced before assignment >>> kills=77 >>> def boo(): print kills ... >>> boo() 77 I'm amazed that I've spent so much time with Python and something like that totally stumps me!? > FWIW, this is a FAQ. If you have a link, that'll help. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
Thanks Bruno, I had to keep coding, so I used the long form [Object.subobject.property = blah] anyway. It's long-winded, but unambiguous. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic animation in Python - how to
> Please refer me to some basic Python code for animation like that . You are in for a wild ride! Depending on your platform you can use dozens of different tools. Try wxPython, pyCairo, pyGTK and PIL (Python Imaging Library) for the most capable. Basically you are looking at a fairly complex thing - you need to create a "context" and then draw into it with commands (they vary according to your toolkit) and then display the result. Loop that and change the drawing every time and you have animation. wxPython has very easy widgets for doing something like this (you can use an animated gif for example), and it's cross-platform so that a big plus. It's tricky to get into, but well worth it. hth \d -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
> class Key(object): > def __init__self): > self.__dict__['props'] = KeyProps() Okay - that's weird. Is there another way to spin this? > def __setattr__(self,var,val): > setattr(self.props,var,val) Perhaps by changing this one? \d -- http://mail.python.org/mailman/listinfo/python-list
callback confusion
Hi, I have two modules, the second is imported by the first. Let's call them one.py and two.py (two being my API) In the first I register a function into the second. [in one.py] def boo(): ... ... two.register( boo ) two.startLoop() In two.py it starts a loop (GTK timeout), so processing remains there. At some point it's time to call the callback. [within the loop in two.py] f = getFunc() f() That works, it calls boo( ) in one.py -- all fine. The thing I can't figure out is that it's calling it from the namespace p.o.v of two.py -- For example: [in one.py] kills=0 def boo(): print kills It will abort with: print kills UnboundLocalError: local variable 'kills' referenced before assignment How can I get the 'self' of a module? If I could tell it to [print moduleself.kills] or something like that I'd be in business again. It would be best to have no funny stuff on the user-end of the API; a simple [print kills] would be best. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: pprinting objects
> Define a __repr__ or __str__ method for the class Yes, then I could include the code John Machin suggested in there: for attr, value in sorted(self.__dict__.iteritems()): blah That will do nicely. Thanks all. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
> So you might want to describe your use-case. Um.. I wanted an object with Key to hold other data. I wanted a way to set that *other* data within Key without having to specify the "object in-between" everytime. k1.x = "ni!" should perform: k1.props.x = "ni!" and print k1.x should perform: print k1.props.x I'll go look at your link. Thanks. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: pprinting objects
> AFAIK you have to roll your own. Here is a very rudimentary example: Very cool, thanks. \d -- http://mail.python.org/mailman/listinfo/python-list
setattr getattr confusion
Hi, Here's some code, it's broken: class Key( object ): def __init__(self): self.props = KeyProps() def __getattr__(self, v): return getattr( self.props,v ) def __setattr__(self,var,val): object.__setattr__(self.props,var,val) class KeyProps(object): def __init__(self): self.x="NOT SET YET" k1=Key() It does not run because of the recursion that happens, but I don't know how to lay this out. I am trying to set the x value within props within Key: k1.x="DAMN" print k1.x It seems to work, but it's really making a new 'x' in k1. print k1.props.x Shows "NOT SET YET", thus proving it failed to set x here. I want to change k1.props.x by k1.x="something new" -- can this be done? \d -- http://mail.python.org/mailman/listinfo/python-list
pprinting objects
Hi, Is there a way to get a dump of the insides of an object? I thought pprint would do it. If I had a class like this: class t: def __init__(self): self.x=1 self.y=2 self.obj = SomeOtherObj() Then it could display it as: t, x,1, y,2, obj, Or something like that -- a complete output of the object really, with id()'s and so forth. \d -- http://mail.python.org/mailman/listinfo/python-list