Using Python to get push notifications from an RSS feed?
As a little project for myself (and to help get immediate player notes for my fantasy baseball team), I'm wondering what modules I might need to do this. Basically, I'd like to get immediate notification when a new player note has been added to an RSS feed. Since it will only be for specified players, I suppose I would use something like ElementTree to read the data and figure out if the update is about a relevant player, but how do I check the RSS feed (constantly) in the first place? I was reading a little about Universal Feed Parser, but I'm still not sure about how to do the push notification aspect. I'd like immediate notifications if possible, or will I have to settle for periodically checking the feed? If the latter, how do I ensure I only check the newest updates since the last time, and not everything? Thanks! John -- https://mail.python.org/mailman/listinfo/python-list
What's the best way to parse this HTML tag?
I'm using Beautiful Soup to extract some song information from a radio station's website that lists the songs it plays as it plays them. Getting the time that the song is played is easy, because the time is wrapped in a div tag all by itself with a class attribute that has a specific value I can search for. But the actual song title and artist information is harder, because the HTML isn't quite as precise. Here's a sample: div class=cmPlaylistContent strong a href=/lsp/t2995/ Love Without End, Amen /a /strong br/ a href=/lsp/a436/ George Strait /a br/ span class=sprite iconDownload /span Download Song: a href=http://itunes.apple.com/us/album/love-without-end-amen/ id71416?i=71404amp;uo=4 iTunes /a | a href=http://www.amazon.com/Love-Without-End-Amen/dp/B000V638BQ? SubscriptionId=1NXYFBZST44V8CCDK182amp;tag=coxradiointer-20amp;linkCode=xm2amp;camp=2025amp;creative=165953amp;creativeASIN=B000V638BQ Amazon MP3 /a br/ span class=sprite iconComments Comments (1) /span span class=sprite iconVoteUp Votes (1) /span /div This is about as far as I can drill down without getting TOO specific. I simply find the div tags with the cmPlaylistContent class. This tag contains both the song title and the artist name, and sometimes miscellaneous other information as well, like a way to vote for the song or links to purchase it from iTunes or Amazon. So my question is, given the above HTML, how can I best extract the song title and artist name? It SEEMS like they are always the first two pieces of information in the tag, such that: for item in div.stripped_strings: print(item) Love Without End, Amen George Strait Download Song: iTunes | Amazon MP3 Comments (1) Votes (1) and I could simply get the first two items returned by that generator. It's not quite as clean as I'd like, because I have no idea if anything could ever be inserted before either of these items, thus messing it all up. I also don't want to rely on the strong tag, which makes me shudder, or the a tag, because I don't know if they will always have an href. Ideall, the a tag would have also had an attribute that labeled the title as the title, and the artist as the artist, but alas. Therefore, I appeal to your greater wisdom in these matters. Given this HTML, is there a best practice for how to refer to the song title and artist? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to parse this HTML tag?
On Mar 11, 7:28 pm, Roy Smith r...@panix.com wrote: In article 239c4ad7-ac93-45c5-98d6-71a434e1c...@r21g2000yqa.googlegroups.com, John Salerno johnj...@gmail.com wrote: Getting the time that the song is played is easy, because the time is wrapped in a div tag all by itself with a class attribute that has a specific value I can search for. But the actual song title and artist information is harder, because the HTML isn't quite as precise. Here's a sample: div class=cmPlaylistContent strong a href=/lsp/t2995/ Love Without End, Amen /a /strong br/ a href=/lsp/a436/ George Strait /a [...] Therefore, I appeal to your greater wisdom in these matters. Given this HTML, is there a best practice for how to refer to the song title and artist? Obviously, any attempt at screen scraping is fraught with peril. Beautiful Soup is a great tool but it doesn't negate the fact that you've made a pact with the devil. That being said, if I had to guess, here's your puppy: a href=/lsp/t2995/ Love Without End, Amen /a the thing to look for is an a element with an href that starts with /lsp/t, where t is for track. Likewise: a href=/lsp/a436/ George Strait /a an href starting with /lsp/a is probably an artist link. You owe the Oracle three helpings of tag soup. Well, I had considered exactly that method, but I don't know for sure if the titles and names will always have links like that, so I didn't want to tie my programming to something so specific. But perhaps it's still better than just taking the first two strings. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
Alright, I'm simply lost about how to install these modules. I extracted the folders from the .tar.gz files and then went into those folders in my command prompt. I typed: C:\Python32\python setup.py install and for a while something was happening (I was doing the lxml one) and then it stopped with an error that it couldn't find a file. So I have no idea. Next I installed the distribute module, which seemed to install okay. But now I don't understand how to use easy_install. Where do I call it from? What do I do with the .tar.gz files at this point? The instructions for lxml say to run this command: easy_install --allow-hosts=lxml.de,*.python.org lxml but WHERE do I run it? I tried it in the Python directory, and then further in the lxml site-packages directory, but it doesn't work. What do I do with it? Where do I put the .tar files? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Mar 8, 3:33 pm, John Salerno johnj...@gmail.com wrote: Alright, I'm simply lost about how to install these modules. I extracted the folders from the .tar.gz files and then went into those folders in my command prompt. I typed: C:\Python32\python setup.py install and for a while something was happening (I was doing the lxml one) and then it stopped with an error that it couldn't find a file. So I have no idea. Next I installed the distribute module, which seemed to install okay. But now I don't understand how to use easy_install. Where do I call it from? What do I do with the .tar.gz files at this point? The instructions for lxml say to run this command: easy_install --allow-hosts=lxml.de,*.python.org lxml but WHERE do I run it? I tried it in the Python directory, and then further in the lxml site-packages directory, but it doesn't work. What do I do with it? Where do I put the .tar files? Well, after a bit of experimentation, I got it to run, but I seem to have run into the same error as when I used setup.py: http://i271.photobucket.com/albums/jj138/JohnJSal/lxml_error.png Now I have no idea what to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Mar 8, 3:40 pm, John Salerno johnj...@gmail.com wrote: Now I have no idea what to do. Hmph, I suppose I should have more patience. I realized that the easy_install for lxml only tried to install a binary version, which doesn't exist for the version it found (the latest, 2.3.3). I just had to look through the previous versions and find the one with a binary installation for Windows (2.3) and it was as simple as a single click to install! And the easy_install method did work for Beautiful Soup, so I should be all set now! -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
Thanks, I had no idea about either option, since I don't use the command prompt very much. Needless to say, the Linux console is much nicer :) On Thu, Mar 8, 2012 at 4:19 PM, Dave Angel d...@davea.name wrote: On 03/08/2012 04:40 PM, John Salerno wrote: SNIP http://i271.photobucket.com/albums/jj138/JohnJSal/lxml_error.png Nothing to do with Python, but you'd save us all a lot of space and bandwidth if you learned how to copy/paste from a Windows cmd window. If you're just doing it rarely, you can right click on the top bar to get a menu. I think you want mark. Then you select the text you'd like to put in the clipboard. Alternatively, you can put the console in quick-edit mode (I think it's called, it's been a long time since I ran Windows). That's an option you set on one cmd window, and it sticks for future windows. In quick-edit, you just right-click-drag on the cmd window to select a rectangle of text. Then you can Ctrl-V to paste it into email, or into a text editor, or wherever else you need it. Hard to imagine not using this mode, or its Linux equivalent, which is always available. If that wasn't clear enough, or it doesn't work for you, somebody will explain it better. Or ask me, and I'll launch a VirtualBox with Windows to get you going. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Thursday, March 8, 2012 9:38:51 PM UTC-6, alex23 wrote: John Salerno johnj...@gmail.com wrote: So much work just to get a 3rd party module installed! New! Try out the beta release of Beautiful Soup 4. (Last updated February 28, 2012) easy_install beautifulsoup4 or pip install beautifulsoup4 or download a tarball. http://www.crummy.com/software/BeautifulSoup/ Worked fine under both Python 2.7 3.2 using pip. Yeah, but first I had to figure out how to install easy_install :) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
Ok, first major roadblock. I have no idea how to install Beautiful Soup or lxml on Windows! All I can find are .tar files. Based on what I've read, I can use the easy_setup module to install these types of files, but when I went to download the setuptools package, it only seemed to support Python 2.7. I'm using 3.2. Is 2.7 just the minimum version it requires? It didn't say something like 2.7+, so I wasn't sure, and I don't want to start installing a bunch of stuff that will clog up my directories and not even work. What's the best way for me to install these two packages? I've also seen a reference to using setup.py...is that a separate package too, or is that something that comes with Python by default? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Wed, Mar 7, 2012 at 3:01 PM, Ian Kelly ian.g.ke...@gmail.com wrote: There is a fork of setuptools called distribute that supports Python 3. Thanks, I guess I'll give this a try tonight! setup.py is a file that should be included at the top-level of the .tar files you downloaded. Generally, to install something in that manner, you would navigate to that top-level folder and run python setup.py install. If you have multiple Python versions installed and want to install the package for a specific version, then you would use that version of Python to run the setup.py file. The only files included in the .tar.gz file is a .tar file of the same name. So I guess the setup option doesn't exist for these particular packages. I'll try distribute tonight when I have some time to mess with all of this. So much work just to get a 3rd party module installed! -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Wed, Mar 7, 2012 at 3:34 PM, Ian Kelly ian.g.ke...@gmail.com wrote: The setup.py file (as well as the other files) would be inside the .tar file. Unlike a Windows zip file, which does both archival and compression, Unix files are typically archived and compressed in two separate steps: tar denotes the archival format, and gz denotes the compression format. Some decompression programs are smart enough to recognize the .tar file and automatically extract it when decompressing. Others require you to decompress the .gz and extract the .tar separately -- it sounds like yours is one of the latter. Ah, I see now. After opening the gz file, there was a tar file inside, and then I just opened that file (I use 7zip for these types) and there was a whole host of stuff inside. I didn't realize the tar file itself was an archive, I thought it was the module! ::blush:: Maybe I don't need to mess with the distribute utility then, if I can just run the setup file. I'll try that first and see what happens. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Mar 7, 11:03 pm, Chris Angelico ros...@gmail.com wrote: On Thu, Mar 8, 2012 at 7:39 AM, John Salerno johnj...@gmail.com wrote: it only seemed to support Python 2.7. I'm using 3.2. Is 2.7 just the minimum version it requires? It didn't say something like 2.7+, so I wasn't sure, and I don't want to start installing a bunch of stuff that will clog up my directories and not even work. Just to clarify: Python 2 and Python 3 are quite different. If something requires Python 2.7, you cannot assume that it will work with Python 3.2; anything that supports both branches will usually list the minimum version of each (eg 2.7 or 3.3). ChrisA That's why I asked first, because I got the feeling it did NOT support Python 3 :) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Mar 7, 4:02 pm, Evan Driscoll drisc...@cs.wisc.edu wrote: On 01/-10/-28163 01:59 PM, Prasad, Ramit wrote: gz stands for gzip and is a form of compression (like rar/zip ). tar stands for a tape archive. It is basically a box that holds the files. So you need to unzip and then open the box. Normally programs like WinZip / WinRar / 7-zip will do both in one step so you do not need to. Not sure what program you are using... I'm not sure what 7-zip you're referring to, because I use 7-zip and it's always been a two-step process for me... (Though I can't say I've looked through the preferences dialog for a extract .tar.gz files in one go setting.) Evan Same here, because that's what I used. I looked through the settings but didn't see anything. What seems to happen is that 7-Zip recognizes the .gz extension and opens that automatically. But then that simply opens up another window with the .tar file in it, which you have to then open again. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Tuesday, March 6, 2012 4:52:10 PM UTC-6, Chris Rebert wrote: On Tue, Mar 6, 2012 at 2:43 PM, John Salerno johnj...@gmail.com wrote: I sort of have to work with what the website gives me (as you'll see below), but today I encountered an exception to my RE. Let me just give all the specific information first. The point of my script is to go to the specified URL and extract song information from it. This is my RE: song_pattern = re.compile(r'([0-9]{1,2}:[0-9]{2} [a|p].m.).*?a.*?(.*?)/a.*?a.*?(.*?)/a', re.DOTALL) I would advise against using regular expressions to parse HTML: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags lxml is a popular choice for parsing HTML in Python: http://lxml.de Cheers, Chris Thanks, that was an interesting read :) Anything that allows me NOT to use REs is welcome news, so I look forward to learning about something new! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
Anything that allows me NOT to use REs is welcome news, so I look forward to learning about something new! :) I should ask though...are there alternatives already bundled with Python that I could use? Now that you mention it, I remember something called HTMLParser (or something like that) and I have no idea why I never looked into that before I messed with REs. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Tuesday, March 6, 2012 5:05:39 PM UTC-6, John Salerno wrote: Anything that allows me NOT to use REs is welcome news, so I look forward to learning about something new! :) I should ask though...are there alternatives already bundled with Python that I could use? Now that you mention it, I remember something called HTMLParser (or something like that) and I have no idea why I never looked into that before I messed with REs. Thanks. ::sigh:: I'm having some trouble with the new Google Groups interface. It seems to double post, and in this case didn't post at all. If it did already, I apologize. I'll try to figure out what's happening, or just switch to a real newsgroup program. Anyway, my question was about Beautiful Soup. I read on the doc page that BS uses a parser, which html.parser and lxml are. So I'm guessing the difference between them is that the parser is a little more low level, whereas BS offers a higher level approach to using them? Is BS easier to write code with, while still using the power of lxml? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
On Tuesday, March 6, 2012 5:05:39 PM UTC-6, John Salerno wrote: Anything that allows me NOT to use REs is welcome news, so I look forward to learning about something new! :) I should ask though...are there alternatives already bundled with Python that I could use? Now that you mention it, I remember something called HTMLParser (or something like that) and I have no idea why I never looked into that before I messed with REs. Thanks. Also, I just noticed Beautiful Soup, which seems appropriate. I suppose any will do, but knowing the pros and cons would help with a decision. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
Thanks. I'm thinking the choice might be between lxml and Beautiful Soup, but since BS uses lxml as a parser, I'm trying to figure out the difference between them. I don't necessarily need the simplest (html.parser), but I want to choose one that is simple enough yet powerful enough that I won't have to learn another method later. On Tue, Mar 6, 2012 at 5:35 PM, Ian Kelly ian.g.ke...@gmail.com wrote: On Tue, Mar 6, 2012 at 4:05 PM, John Salerno johnj...@gmail.com wrote: Anything that allows me NOT to use REs is welcome news, so I look forward to learning about something new! :) I should ask though...are there alternatives already bundled with Python that I could use? Now that you mention it, I remember something called HTMLParser (or something like that) and I have no idea why I never looked into that before I messed with REs. HTMLParser is pretty basic, although it may be sufficient for your needs. It just converts an html document into a stream of start tags, end tags, and text, with no guarantee that the tags will actually correspond in any meaningful way. lxml can be used to output an actual hierarchical structure that may be easier to manipulate and extract data from. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
Also, you're still double-posting. Grr. I just reported it to Google, but I think if I start to frequent the newsgroup again I'll have to switch to Thunderbird, or perhaps I'll just try switching back to the old Google Groups interface. I think the issue is the new interface. Sorry. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
After a bit of reading, I've decided to use Beautiful Soup 4, with lxml as the parser. I considered simply using lxml to do all the work, but I just got lost in the documentation and tutorials. I couldn't find a clear explanation of how to parse an HTML file and then navigate its structure. The Beautiful Soup 4 documentation was very clear, and BS4 itself is so simple and Pythonic. And best of all, since version 4 no longer does the parsing itself, you can choose your own parser, and it works with lxml, so I'll still be using lxml, but with a nice, clean overlay for navigating the tree structure. Thanks for the advice! -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: Why aren't my widgets expanding when I resize the window?
You will need to configure the root columns and rows also because the configurations DO NOT propagate up the widget hierarchy! Actually, for this example, I would recommend using the pack geometry manager on the frame. Only use grid when you need to use grid. Never use any functionality superfluously! Also, you should explicitly pack the frame from OUTSIDE frame.__init__()! Ok, so use pack when putting the frame into the root, since that's all that goes into the root directly. But just out of curiosity, what did I do wrong with using grid? How would it work with grid? from tkinter.constants import BOTH, YES I always use either: sticky='nswe' sticky=N+S+W+E This is something I'm not too thrilled with. I don't like importing things piecemeal. I suppose I could do: import tkinter.constants as tkc (or something like that) and qualify each constant. Seems like more work, but it just seems better than having to manage each constant that I need in the import list. Also, N+S+E+W and (N, S, E, W) don't seem to work unless qualified, so that's four more constants I'd have to explicitly import. And (tk.N, tk.S, tk.E, tk.W) is just horrible to look at. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: Why aren't my widgets expanding when I resize the window?
I don't like importing things piecemeal. I suppose I could do: So you prefer to pollute? How bout we just auto import the whole Python stdlib so you can save a few keystrokes? so that's four more constants I'd have to explicitly import. And (tk.N, tk.S, tk.E, tk.W) is just horrible to look at. Wah! Stop whining and act like a professional! You complain about qualifying constants but you happily type self until your fingers bleed without even a whimper??? Look, either import ONLY the constants you need, or qualify each constant with a module name/variable; that is the choices available to a professional. Or, just be lazy and pollute your namespace. FYI: Lazy coders get what they deserve in the end. How exactly am I being lazy and polluting the namespace? I never said I wanted to use the * import method, if that's what you are (wrongly) assuming. I said it seems cleaner and, to me, LESS lazy to import the whole module as import tkinter.constants as tkc and qualify everything. It's certainly more explicit than importing constants on an as-needed basis, having an ever-increasing list of constants, and referring to them unqualified in the code. Yes, I complain that tk.N, tk.S, etc. is ugly to look at, but I'm saying it seems like a better way than using them unqualified, unless maybe there is yet another, better way. As far as using self all the time, how do you know I never whimpered about it? The first time I learned about it I DIDN'T like it, because it seemed like a lot of unnecessary typing, but eventually I came to accept it because 1) you HAVE to do it, unlike the various options for referring to these constants, and 2) I began to like the explicitness of qualifying everything with self. You are very helpful, but you sure like to throw around the term lazy a little too unabashedly. I never said I wanted to import with *, which you seem to think I want to do. I LIKE qualifying things, which is the reason I didn't care so much for your method of importing the constants by name. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: Why aren't my widgets expanding when I resize the window?
On Monday, March 5, 2012 7:10:50 PM UTC-6, Steven D#39;Aprano wrote: On Mon, 05 Mar 2012 14:07:05 -0800, John Salerno quoted: Wah! Stop whining and act like a professional! You complain about qualifying constants but you happily type self until your fingers bleed without even a whimper??? John, it is polite to leave attributions in place when you quote somebody. I don't know who you are quoting above, but given the obnoxious tone and the fact that this is about Tkinter, I'm guessing it is RantingRick, a.k.a. Rick Johnson. Rick is a notorious troll, and you'll probably save yourself a lot of grief if you pay no attention to him. It's not so much that his advice is *always* bad, but that you'll spend so many hours sifting through the piles of bad advice, unprofessional language, and annoying self- aggrandisement for the occasional nugget of gold that it just isn't worth it. Which is a pity, because I gather that Rick actually does know Tkinter well. But dealing with him is like wrestling with a pig: I learned long ago, never to wrestle with a pig. You get dirty, and besides, the pig likes it. -- George Bernard Shaw -- Steven Thank you. Sorry about the attribution. That was my fault because I was trying to cite just the relevant bits, and I cut off the header too. -- http://mail.python.org/mailman/listinfo/python-list
Is this the right location to launch IDLE?
I'm trying to get Notepad++ to launch IDLE and run the currently open file in IDLE, but all my attempts have failed so far. I'm wondering, am I even using the IDLE path correctly? I'm using this: C:\Python32\Lib\idlelib\idle.pyw $(FULL_CURRENT_PATH) (That last part puts in the full path to the open file.) Is this not the proper way to launch IDLE with an argument? It actually does open up IDLE, but the file doesn't seem to have been loaded, because when I try to use variables or functions from the file, IDLE acts as if it doesn't know what I'm referring to. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this the right location to launch IDLE?
Unfortunately neither method worked. Adding -r to the path created this error when I tried it: *** Error in script or command! Traceback (most recent call last): File C:\Users\John\Documents\Python Scripts\chess_pieces.py, line 1 class ChessPiece: ^ SyntaxError: invalid character in identifier Although there really is no error in the file, and running it directly from within IDLE doesn't cause this problem. Adding the pythonw.exe part to the beginning also gave this error, but when I remove the -r, then it just opens IDLE as normal, but without having loaded the Notepad++ file. I just know there has to be a way to do this, but perhaps it's more of an NP++ problem. I posted on their forums but no one responded. I thought I might see if the problem lies with calling IDLE, but apparently it's a Windows/NP++ thing... -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this the right location to launch IDLE?
That would be a Notepad++ problem. That  gibberish is what you get when a Unicode BOM (Byte Order Mark) character is encoded as UTF-8 but decoded as ISO-8859-1 or CP-1252. A BOM is not recommended for UTF-8 text; there should be some setting in Notepad++ to suppress it. You are my new hero! :) It works perfectly now! I set the default for files to be UTF-8 without BOM, and I also checked the option that said Apply to opened ANSI files. Is that okay? Thank you!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you use the widgets in tkinter.ttk if you want to import tkinter as tk?
On Sunday, March 4, 2012 7:39:27 PM UTC-6, Rick Johnson wrote: On Mar 2, 11:06 pm, John Salerno johnj...@gmail.com wrote: I'm tempted just to go back to wxPython. Two sets of widgets in Tkinter is a little annoying. Your complaint is justified. The Tkinter API is a disgrace. IDLE's source is just as bad. Luckily i have not made the jump to py3000 full- time yet, but when i do, i think the first item on my to-do list will be to hack this hideous tk+ttk+blah+blah into something more friendly. Heck, maybe i'll even release it! Well, after reading about the themed widgets and using them a bit, they definitely seem a lot cleaner than the old ones. Just comparing the attributes of the new and old widgets is a big difference. Much more streamlined. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter: Why aren't my widgets expanding when I resize the window?
I can't seem to wrap my head around all the necessary arguments for making a widget expand when a window is resized. I've been following along with a tutorial and I feel like I'm doing everything it said, but I must be missing something. Here's what I have. What I expect is that when I resize the main window, I should be able to see the AppFrame's border stretch out, but it remains in the original position. Is there something wrong with the sticky argument, maybe? The tutorial I'm reading says they can be strings, but it also uses what appears to be a tuple of constants like this: sticky=(N, S, E, W) -- but that didn't work either. import tkinter as tk import tkinter.ttk as ttk class AppFrame(ttk.Frame): def __init__(self, parent, **kwargs): super().__init__(parent, **kwargs) self.grid(row=0, column=0, sticky='nsew') self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.create_widgets() def create_widgets(self): entry = ttk.Entry(self) entry.grid(row=0, column=1, sticky='nsew') #entry.columnconfigure(0, weight=1) #entry.rowconfigure(0, weight=1) label = ttk.Label(self, text='Name:') label.grid(row=0, column=0, sticky='nsew') root = tk.Tk() root.title('Test Application') frame = AppFrame(root, borderwidth=15, relief='sunken') root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this the proper way to use a class method?
Oh, but it does get passed, just implicitly. `super()` basically grabs `self` magically from its caller, and uses it to bind method calls on the magical object returned by `super()`. Thanks again, now I understand :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
Indeed. One of the things that motivated me to write the tutorial at http://www.tkdocs.com is the rather poor state (in terms of being out of date, incorrect, or demonstrating poor practices) of most Tkinter documentation. Call it self-serving, but I think the Tkinter world would be a happier place if everyone just pointed to TkDocs. ;-) To your point about explicit root, etc. I'll make the general observation that lots of different things work in a given situation, which is just fine for quick little hacky things. If people are doing anything more than a throwaway however, they'd be better served by spending a bit of time learning the conceptual underpinnings (e.g. http://www.tkdocs.com/tutorial/concepts.html) after which the right thing to do will be more obvious. Mark Nice. I shall be spending some time at your website. I actually like wxPython, but I decided to learn a little Tkinter because it's already included and would be an easier and quicker option for small interfaces. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
After that, you can nest as many frames, toplevels, and blah widgets under that root window as you so desire. Actually you don't even need a frame, you can pack widgets directly into a Toplevel or Tk widget. This is interesting. I completely understand your point about always calling (and using) the instance of Tk as the root. Given that, what is the point of creating a Frame object at all? I tried NOT doing it, like you said, and it seemed to work fine with my simple example. But is there a benefit to using a Frame object to group the widgets together? Or is it cleaner to just use the Tk object? -- http://mail.python.org/mailman/listinfo/python-list
How do you use the widgets in tkinter.ttk if you want to import tkinter as tk?
According to the Python docs, the way to use tkinter.ttk is this: from tkinter import * from tkinter.ttk import * But what if I don't like this import method and prefer to do: import tkinter as tk How then do I utilize tkinter.ttk using the same name? Or is that not possible? Will I have to use to separate names, like this: import tkinter as tk import tkinter.ttk as ttk Is that the only way? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you use the widgets in tkinter.ttk if you want to import tkinter as tk?
I suppose the 'advantage' of this is that it will replace tk widgets with equivalent ttk widgets, if they exist and have the same name. I believe one has to program them differently, however, so the replacement cannot be transparent and one mush know anyway what gets replaced and what not. Grr, sounds like a pain if I want to use the new widgets. Does this cause conflict with someone who isn't running 8.5, or will they still see the older widgets as normal? I'm tempted just to go back to wxPython. Two sets of widgets in Tkinter is a little annoying. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
On Thursday, March 1, 2012 1:38:08 AM UTC-6, Steven D#39;Aprano wrote: On Wed, 29 Feb 2012 22:41:53 -0800, John Salerno wrote: Yes. You must leave it out. Now I'm reading a Tkinter reference at http://infohost.nmt.edu/tcc/help/pubs/tkinter/minimal-app.html and it has this example: [...] Could you please stop posting the same message twice? It's very annoying. There is no need to C.C. python-list because comp.lang.python is the mirror of the mailing list. Thank you. -- Steven I'm sorry, it's unintentional. The new interface for Google Groups keeps doing weird things and makes double and triple posts. I deleted them from my end, but I guess they are still showing up for everyone else. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
EXAMPLE 1: (this works, but is flawed!) root = tk.Tk() b = tk.Button(master=None, text='Sloppy Coder') b.pack() root.mainloop() EXAMPLE 2: (This is how to write code!) root = tk.Tk() widgetframe = tk.Frame(root) b = tk.Button(master=None, text='Sloppy Coder') b.pack() root.mainloop() EXAMPLE 3: (OOP style) class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) # something should happen here to justify using OOP # or here class AppFrame(tk.Frame): def __init__(self, master, **kw): tk.Frame.__init__(self, master, **kw) self.createWidgets() def createWidgets(self): b = tk.Button(master=None, text='Push Me') b.pack() if __name__ == '__main__': app = App() frame = AppFrame(app) frame.pack() app.mainloop() Why is the master argument for Button set to None? Shouldn't it be the Frame object? And shouldn't it also have self as the first argument? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
Hmm, it seems as though i am the latest victim of the copy/paste error! Oh well, if you were going to absorb my teachings, you would have absorbed them by now. I am moving on unless a new subject needs explaining. Well, I've certainly absorbed your recommendation to always create the root explicitly, but you still haven't really explained WHY. Telling me that I will eventually find out as I become more proficient isn't very helpful. I like being explicit, so I will create the Tk option like you suggest (although I don't see the need to subclass it first), but I also like knowing WHY I do what I do, so it would help to have some reason why it's better to create the root explicitly rather than allow Tkinter to do it. -- http://mail.python.org/mailman/listinfo/python-list
Is this the proper way to use a class method?
This is purely for fun and learning, so I know there are probably better ways of creating a chess program. Right now I'm just curious about my specific question, but I'd love to hear any other advice as well. Basically, I'm wondering if I'm using the class method properly with the move method. The reason I did it this way is because every chess piece will obviously have its own move method, yet they will all need to mark the piece as moved, so I figure that's best written once in the superclass. This works, but doing it this way seems weird, since the point of a class method is that it can be called by the class itself, even before instances have been created. Yet the way I've implemented it, it is necessarily tied to being called on an instance. Is this wrong? Is there a better way to do what I'm doing with move? Also, do I need the @classmethod decorator? The book I'm reading says to use it (and @staticmethod), but the following code works without it. Thanks. class ChessPiece: def __init__(self, position, label, has_moved): try: self.position = (position[0], int(position[1])) except TypeError: self.position = position self.label = label self.has_moved = has_moved def move(cls, self): self.has_moved = True class Pawn(ChessPiece): def __init__(self, position=None, label=1, has_moved=False): super().__init__(position, label, has_moved) def move(self): super().move(self) self.position = (chr(ord(self.position[0]) + 1), self.position[1] + 1) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this the proper way to use a class method?
That's just a coincidence. Your supercall is ought to be: super().move() In contrast, super().move(self) calls the superclass instance method `move` with 2 arguments, both `self`, which just happens to work given your move() method, inside which `cls` isn't actually a class like it ought to be. Thank you! This is the whole reason I tried using a class method in the first place. I was getting an error that said my move method only takes one argument, but I was passing in two. But if I make the super call as super().move(), how does that work? The move method in the superclass takes an argument, and if I just do super().move(), isn't it the subclass that's getting passed to it? How does the superclass move method know what 'self' is if it doesn't get passed to it as I did originally? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
It is not necessarily to call Tk explicitly, which i think is a bug BTW. Sure, for simple scripts you can save one line of code but only at the expense of explicitness and intuitiveness. Observe ## START CODE ## import Tkinter as tk root = tk.Tk() root.title('Explicit Root') root.mainloop() f = tk.Frame(master=None, width=100, height=100, bg='red') f.pack() f.mainloop() b = tk.Button(master=None, text='Sloppy Coder') b.pack() b.mainloop() ## END CODE ## as you can see all three examples work even though the last two don't explicitly create a master. The master is still there however Tkinter just created magically for you. Talk about laziness! I'm not sure I understand which method you are advocating. It sounded like you said calling Tk() explicitly is a bug. I certainly would never create widgets without first creating a master frame, but is creating a Frame object enough, or should I create a Tk object and *then* a Frame object? Also, at what point do you include the destroy method in your program, assuming you do not have a widget that will close the window? If you only want the Windows X button to close the window, then is it okay to leave out any call to destroy()? Or should always explicitly destroy it just as I explicitly created a Tk instance? If the latter, then where in the code do you put the call to destroy so it won't conflict with the user closing the window with the X button? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
Yes, but i think the REAL problem is faulty code logic. Remove the last line root.destroy() and the problem is solved. Obviously the author does not have an in-depth knowledge of Tkinter. The faulty code is not my own, which is part of the reason I asked the question. The book I'm reading (The Quick Python Book) does not use it, but I saw in the Python docs that it is there, under tkinter in the Global Module Docs, 24.1.2.2. A Simple Hello World Program: from tkinter import * class Application(Frame): def say_hi(self): print(hi there, everyone!) def createWidgets(self): self.QUIT = Button(self) self.QUIT[text] = QUIT self.QUIT[fg] = red self.QUIT[command] = self.quit self.QUIT.pack({side: left}) self.hi_there = Button(self) self.hi_there[text] = Hello, self.hi_there[command] = self.say_hi self.hi_there.pack({side: left}) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy() -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
On Wednesday, February 29, 2012 11:40:45 PM UTC-6, Terry Reedy wrote: On 2/29/2012 11:41 PM, John Salerno wrote: window? If you only want the Windows X button to close the window, then is it okay to leave out any call to destroy()? Yes. You must leave it out. the latter, then where in the code do you put the call to destroy so it won't conflict with the user closing the window with the X button? See my other post of a few minutes ago for an example that now works. -- Terry Jan Reedy When you suggested I create the root frame explicitly, you mean create a Tk object explicitly, as in your example, and then pass that as an argument to the Frame instance? What exactly is the purpose of doing that? Does Tk do some extra work that a simple call to Frame won't do? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
What exactly is the purpose of doing that? Does Tk do some extra work that a simple call to Frame won't do? More specifically, what is the benefit of doing: root = tk.Tk() app = Application(master=root) app.mainloop() as opposed to: app = Application() app.mainloop() Also, in the first example, what is the difference between calling app.mainloop() and root.mainloop()? They both seemed to work when I ran them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?
Yes. You must leave it out. Now I'm reading a Tkinter reference at http://infohost.nmt.edu/tcc/help/pubs/tkinter/minimal-app.html and it has this example: #!/usr/local/bin/python from Tkinter import * class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createWidgets() def createWidgets(self): self.quitButton = Button ( self, text='Quit', command=self.quit ) self.quitButton.grid() app = Application() app.master.title(Sample application) app.mainloop() Is this just outdated? I don't understand why it uses quit() instead of destroy(). When I try this in IDLE, quit() just causes the application to hang (I assume because it ends the mainloop without actually closing the application). Or is this just a problem when using IDLE? If the latter, which is preferable, quit or destroy? -- http://mail.python.org/mailman/listinfo/python-list
Is it necessary to call Tk() when writing a GUI app with Tkinter?
The book I'm reading about using Tkinter only does this when creating the top-level window: app = Application() app.mainloop() and of course the Application class has subclassed the tkinter.Frame class. However, in the Python documentation, I see this: root = Tk() app = Application(master=root) app.mainloop() root.destroy() Is it necessary to explicitly call Tk(), then pass that result as an argument for the Application call? Is it also necessary to call destroy() on the root frame? I tried the above and I got the following error: Traceback (most recent call last): File C:\Users\John\Desktop\gui.py, line 12, in module root.destroy() File C:\Python32\lib\tkinter\__init__.py, line 1714, in destroy self.tk.call('destroy', self._w) _tkinter.TclError: can't invoke destroy command: application has been destroyed So apparently closing the window with the X button (on Windows) implicitly calls the destroy() method of the root frame. If that's the case, why does the documentation explicitly call it? Furthermore, I pasted the exact example from the documentation into IDLE and ran it, and I also go the same error, so the example in the documentation doesn't even work. So is it sufficient simply to create an Application instance, use mainloop, and then handle the closing of the window elsewhere in the program (such as a widget calling the destroy method on-click, or just letting the X button do it)? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I make an instance of a class act like a dictionary?
On Feb 27, 1:39 am, Chris Rebert c...@rebertia.com wrote: On Sun, Feb 26, 2012 at 11:24 PM, John Salerno johnj...@gmail.com wrote: Hi everyone. I created a custom class and had it inherit from the dict class, and then I have an __init__ method like this: def __init__(self): self = create() The create function creates and returns a dictionary object. Needless to say, this is not working. When I create an instance of the above class, it is simply an empty dictionary rather than the populated dictionary being created by the create function. Am I doing the inheritance wrong, or am I getting the above syntax wrong by assigning the return value to self? Assignment to `self` has no effect outside the method in question; Python uses call-by-object (http://effbot.org/zone/call-by-object.htm ) for argument passing. Even in something like C++, I believe assignment to `this` doesn't work. I know I could do self.variable = create() and that works fine, but I thought it would be better (and cleaner) simply to use the instance itself as the dictionary, rather than have to go through an instance variable. Call the superclass (i.e. dict's) initializer (which you ought to be doing anyway): super(YourClass, self).__init__(create()) Cheers, Chris --http://rebertia.com Thanks. This ended up working: def __init__(self): self = super().__init__(create_board()) Is that what you meant for me to do? Why did assigning to self work in this case, but not the original case? -- http://mail.python.org/mailman/listinfo/python-list
How can I make an instance of a class act like a dictionary?
Hi everyone. I created a custom class and had it inherit from the dict class, and then I have an __init__ method like this: def __init__(self): self = create() The create function creates and returns a dictionary object. Needless to say, this is not working. When I create an instance of the above class, it is simply an empty dictionary rather than the populated dictionary being created by the create function. Am I doing the inheritance wrong, or am I getting the above syntax wrong by assigning the return value to self? I know I could do self.variable = create() and that works fine, but I thought it would be better (and cleaner) simply to use the instance itself as the dictionary, rather than have to go through an instance variable. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I make a program automatically run once per day?
On Jul 27, 7:58 am, Billy Mays 81282ed9a88799d21e77957df2d84bd6514d9...@myhashismyemail.com wrote: On 07/27/2011 08:35 AM, Chris Angelico wrote: On Wed, Jul 27, 2011 at 10:27 PM, Dave Angelda...@ieee.org wrote: As Chris pointed out, you probably aren't getting the script's directory right. After all, how can the scheduler guess where you put it? The obvious answer is to use a full path for the script's filename. Another alternative is to fill in the current directory in the appropriate field of the scheduler's entry. I would prefer setting the current directory, as that allows the script to find any data files it needs, but either works. I find it useful to only add batch files to the scheduler. Those batch files can do any setup and cleanup necessary. In this case, the batch file might simply set the current directory to the location of the script. And that is an excellent idea. Definitely recommended. ChrisA If it hasn't been mentioned already: import time while True: t1 = time.time() #your code here t2 = time.time() time.sleep( 86400 - (t2 - t1) ) This doesn't take into account leap seconds, but it doesn't depend on a task scheduler. It is also independent of the time your code takes to execute. This is simpler, but it might drift slightly over time. -- Bill Well, I specified the full path name but it still doesn't seem to work. A DOS prompt flashes for about a second that says taskeng.exe in the title bar, but the script itself still isn't being run. I don't know about batch files but I'll read up on them and see if that will be a better solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I make a program automatically run once per day?
On Jul 9, 9:01 pm, John Salerno johnj...@gmail.com wrote: Thanks everyone! I probably should have said something like Python, if possible and efficient, otherwise any other method ! :) I'll look into the Task Scheduler. Thanks again! Hmm, okay I'm finally trying Task Scheduler, but how do I set it to run a Python script? It seems to not work, I suppose because it's running the script but doesn't know how to find Python to run it properly. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I make a program automatically run once per day?
On Jul 26, 9:22 pm, Andrew Berg bahamutzero8...@gmail.com wrote: On 2011.07.26 08:05 PM,JohnSalernowrote: Hmm, okay I'm finally trying Task Scheduler, but how do I set it to run a Python script? It seems to not work, I suppose because it's running the script but doesn't know how to find Python to run it properly. Tell it to run the Python interpreter and pass the script as an argument. -- CPython 3.2.1 | Windows NT 6.1.7601.17592 | Thunderbird 5.0 PGP/GPG Public Key ID: 0xF88E034060A78FCB Thank you. I changed it as suggested so that now it runs C: \Python32\python.exe extract_songs.py but it still isn't working. A DOS prompt flashes real quick as it runs, but when I check the output file that is supposed to be written to, nothing new has been added. I'm not sure what the problem is now. I know the script itself works because I just ran it manually and the output was fine. -- http://mail.python.org/mailman/listinfo/python-list
How can I make a program automatically run once per day?
I have a script that does some stuff that I want to run every day for maybe a week, or a month. So far I've been good about running it every night, but is there some way (using Python, of course) that I can make it automatically run at a set time each night? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I make a program automatically run once per day?
Thanks everyone! I probably should have said something like Python, if possible and efficient, otherwise any other method ! :) I'll look into the Task Scheduler. Thanks again! -- http://mail.python.org/mailman/listinfo/python-list
Re: Why won't this decorator work?
On Jul 3, 1:01 pm, OKB (not okblacke) brennospamb...@nobrenspambarn.net wrote: subsequent calls to it will behave differently. If you want ALL calls to your method to roll a die to get a random number, and then use that random number, why not just roll the die inside the method itself: I thought maybe it would be cleaner if the roll function was something separate, but I suppose it could go inside the move method. It just seemed like two different things that needed to be separated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone want to critique this program?
On Jul 3, 1:06 pm, OKB (not okblacke) brennospamb...@nobrenspambarn.net wrote: Yeah, I considered that, but I just hate the way it looks when the line wraps around to the left margin. I wanted to line it all up under the opening quotation mark. The wrapping may not be as much of an issue when assigning a variable like this, but I especially don't like triple-quoted strings that wrap around inside function definitions. That seems to completely throw off the indentation. Do people still use triple-quotes in that situation? I do, because I use an editor that intelligently indents wrapped text to the same indent level as the beginning of the line, instead of wrapping it all the way back to the margin. But isn't wrapped text something different than text that is purposely split across multiple lines with a newline character? That's usually the case when I need to split up a long string. -- http://mail.python.org/mailman/listinfo/python-list
Why won't this decorator work?
I thought I had finally grasped decorators, but the error I'm getting ('str' type is not callable) is confusing me. Here is my code. Also, the commented sentence is from the Python docs, which says it doesn't even need to be callable, if that matters. I also commented out a few things in the move method. They were just to see if it would work, but those lines raised even more errors! import random #space = 0 def move(roll): #global space # space += roll return 'You moved to space {0}.'.format(roll) @move def roll_die(): return random.randint(1, 6) # The return value of the decorator need not be callable # roll_die = move(roll_die) I tried running the command roll_die() and I get the error message. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why won't this decorator work?
On Jul 2, 12:33 pm, MRAB pyt...@mrabarnett.plus.com wrote: On 02/07/2011 17:56, John Salerno wrote: I thought I had finally grasped decorators, but the error I'm getting ('str' type is not callable) is confusing me. Here is my code. Also, the commented sentence is from the Python docs, which says it doesn't even need to be callable, if that matters. I also commented out a few things in the move method. They were just to see if it would work, but those lines raised even more errors! import random #space = 0 def move(roll): # global space # space += roll return 'You moved to space {0}.'.format(roll) @move def roll_die(): return random.randint(1, 6) # The return value of the decorator need not be callable # roll_die = move(roll_die) I tried running the command roll_die() and I get the error message. Thanks. A decorator should return a callable. This: @move def roll_die(): return random.randint(1, 6) is equivalent to this: def roll_die(): return random.randint(1, 6) roll_die = move(roll_die) You should be defining a function (a callable) and then passing it to a decorator which returns a callable. As it is, you're defining a function and then passing it to a decorator which is returning a string. Strings aren't callable. But why does the documentation say The return value of the decorator need not be callable? And why, if I remove the decorator and just leave the two functions as if, does the call to move(roll_die()) work? Isn't that what the decorator syntax is essentially doing? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why won't this decorator work?
On Jul 2, 1:45 pm, Tim Chase python.l...@tim.thechases.com wrote: I must not be looking at the same documentation you are...could you provide a link? The only time I know of that the return value of a decorator need not be callable is if you want to totally break the syntax of the function. :-/ http://docs.python.org/py3k/whatsnew/2.4.html?highlight=decorator Sort of around the middle of the PEP 318 section. But I think I understand now. I was thinking the decorator I made was creating move(roll_die()), which I see now that it is not. Perhaps a decorator isn't what I need in my case, although it seems like it might be. Basically what I want to do is this: I first to need to roll a die to get a random number, then pass that number to the move method of a Player class. Can this be done with a decorator, or is it better just to do it like move(roll_die()) and be done with it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why won't this decorator work?
On Jul 2, 9:11 pm, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: John Salerno wrote: But why does the documentation say The return value of the decorator need not be callable? The thing returned by a decorator does not need to be callable, but if you want to call it, then it better be! This is no different from this: my_func = hello world my_func() # fails because strings aren't callable So if I do this: def decorator(func): # ignores the function and returns a string return hello world @decorator def my_func(): x = 1 y = 2 return x+y print(my_func) # prints hello world my_func() # fails because strings aren't callable If that's useful to you, decorator syntax allows it. That is all the documentation means. And why, if I remove the decorator and just leave the two functions as if, does the call to move(roll_die()) work? Isn't that what the decorator syntax is essentially doing? The call move(roll_die()) is similar to this: temp = roll_die() my_string = move(temp) which is perfectly fine, because you never call my_string. If you did, you'd get the same error, because strings aren't callable. The decorator syntax is completely different. It is doing this: # replace the function roll_die with the output of move, which is a string roll_die = move(roll_die) # now try to call roll_die, actually a string roll_die() which is more like: move(roll_die)() See the difference? -- Steven Eesh, ok, I think I *still* don't quite get decorators, but I get it a little more now. Definitely not what I needed to do here. :) -- http://mail.python.org/mailman/listinfo/python-list
Anyone want to critique this program?
Just thought I'd post this in the event anyone has a few spare minutes and feels like tearing apart a fairly simple attempt to write a game. :) I'll paste the exercise I was working on first, although I think it was meant to be an exercise in how to use lists. I went way beyond that, so maybe my program is overly complicated. It works, though, so that's a plus! The main questions I had about it are at the bottom, after the code. -- Snakes and Ladders can be a fun game for kids to play but you realize when you get older that the players actually have no choices at all. To illustrate just how little input the players have I want you to make a computer program that allows two players to play snakes and ladders on the board given. The rules of the game are simple. On each player's turn they roll one six sided die and move ahead that many squares. If they end their move at the base of a ladder then they automatically climb to the top of the ladder. If they end their move at the end of a snake they automatically slide down to its head. To win the game you must be the first player to land on the last square. If you are near the end and your roll would cause you to go past the end square you don't move for that turn. Your computerized version will look something like: Player 1 hit enter to roll You rolled: 3 You are at spot 3 Player 2 hit enter to roll You rolled: 6 You climbed a ladder You are at spot 17 although you can write this program without using lists, you should ask yourself how you can use lists to encode where the snakes and ladders are. - (I changed snakes to chutes, and I didn't paste in the game board picture. Just trust that the dictionary of lists in the beginning of the program is accurate, and that each set of numbers represents first the space you land on, and second the space you slide or climb to, e.g. [30, 35] means you landed on 30, and as a result of landing on a ladder space, you climbed up to space 35.) --- import random game_information = '***Chutes and Ladders***\nUp to four (4) players may play.\n'\ 'There are 90 spaces on the board. '\ 'The player to reach space 90 first wins.' separator = '-' * 20 spaces = [None] * 90 c_l_spaces = {r'slid down a chute \\': [[14, 3], [20, 15], [39, 33], [66, 53], [69, 58], [79, 67], [84, 71], [88, 36]], 'climbed up a ladder |=|': [[6, 17], [24, 26], [30, 44], [49, 62], [82, 86]]} class Player: def __init__(self, number): self.number = number self.space = 0 def move(self, roll): global spaces if (self.space + roll) 90: return (1, 'Your roll would move you off the game board. '\ 'You remain at space {0}.'.format(self.space)) elif (self.space + roll) == 90: return (0, 'You moved to the last space. You won the game!') else: self.space += roll try: space_type = spaces[self.space - 1][0] self.space = spaces[self.space - 1][1] except TypeError: return (1, 'You moved to space {0}.'.format(self.space)) else: return (1, 'You {0} to space {1}!'.format(space_type, self.space)) def roll_die(): roll = random.randint(1, 6) print('You rolled {0}.'.format(roll)) return roll def populate_game_board(): global spaces for key, values in c_l_spaces.items(): for space in values: spaces[space[0] - 1] = [key, space[1]] def initialize_players(): while True: try: num_players = int(input('Enter the number of players (0 to exit): ')) except ValueError: print('You have entered an invalid response.\n') else: if num_players == 0: print('You have quit the game.') return elif 1 = num_players = 4: break elif (num_players 0) or (num_players 4): print('You have entered an invalid number of players. \n') players = [] for num in range(num_players): players.append(Player(num + 1)) return players def start_game(players): game = 1 while game: for player in players: print('\n***Player {0}***'.format(player.number)) print('You are currently on space {0}.'.format(player.space)) game_update = player.move(roll_die()) print(game_update[1]) print(separator, end='') if game_update[0] == 0: game = 0 break if game: input('\nPress Enter for the next turn.') def initialize_game(): global game_information print(game_information) players = initialize_players() if players: populate_game_board() start_game(players) if __name__ == '__main__':
Re: Anyone want to critique this program?
On Jul 2, 10:02 pm, Chris Angelico ros...@gmail.com wrote: game_information = '***Chutes and Ladders***\nUp to four (4) players may play.\n'\ 'There are 90 spaces on the board. '\ 'The player to reach space 90 first wins.' I'd do this with a triple-quoted string - it'll simply go across multiple lines: game_information = ***Chutes and Ladders*** Up to four (4) players may play. There are 90 spaces on the board. The player to reach space 90 first wins. Yeah, I considered that, but I just hate the way it looks when the line wraps around to the left margin. I wanted to line it all up under the opening quotation mark. The wrapping may not be as much of an issue when assigning a variable like this, but I especially don't like triple-quoted strings that wrap around inside function definitions. That seems to completely throw off the indentation. Do people still use triple-quotes in that situation? c_l_spaces = {r'slid down a chute \\': [[14, 3], [20, 15], [39, 33], [66, 53], [69, 58], [79, 67], [84, 71], [88, 36]], 'climbed up a ladder |=|': [[6, 17], [24, 26], [30, 44], [49, 62], [82, 86]]} It strikes me that this plus populate_game_board() is a little redundant; you could simply have the target dictionary as a literal: spaces={14:3, 20:15, 6:17, 24:26} You can get the description climbed up a ladder or slid down a chute by seeing if spaces[space] is more or less than space. Hmm, interesting. I'm not quite sure how I'd implement that yet, but the 14:3 structure seems cleaner (although I admit at first it looked weird, because I'm used to seeing strings as dictionary keywords!). try: space_type = spaces[self.space - 1][0] self.space = spaces[self.space - 1][1] except TypeError: return (1, 'You moved to space {0}.'.format(self.space)) else: return (1, 'You {0} to space {1}!'.format(space_type, self.space)) It strikes me as odd to use try/except/else for what's non-exceptional. I'd either use a regular if block, or possibly something completely different - like having a list like this: spaces=list(range(91)) # get a list [0, 1, 2, 3... 90] And then set the entries that have chutes/ladders, possibly from your original dict of lists (or something like it): for space in values: spaces[space[0]] = space[1] Then to see where you end up, just go: try: space=spaces[space] except ValueError: print(That would take you past the end of the board!) In this instance, except is being used for the exceptional condition, the case where you blow past the edge of the board - rather than the more normal situation of simply not hitting a chute/ladder. Originally I didn't have the try/except at all, I had nested if statements that seemed to be getting out of control. Then I realized if I just attempted to index the list and handle the exception, rather than check first if indexing the list was allowed, the code came out cleaner looking. But I agree with you, my exception is actually the more frequent occurrence, so I'm going to change that. players = [] for num in range(num_players): players.append(Player(num + 1)) Generally, anything that looks like this can become a list comprehension. It'll be faster (which won't matter here), and briefer. players = [Player(num+1) for num in range(num_players)] Now this is the kind of tip I love. Something like list comprehensions just didn't even occur to me, so I'm definitely going to change that. def start_game(players): def initialize_game(): start_game(players) if __name__ == '__main__': initialize_game() start_game() would be more accurately called play_game(), since it doesn't return till the game's over. And it's a little odd that initialize_game() doesn't return till the game's over; I'd be inclined to have initialize_game() return after initializing, and then have the main routine subsequently call start_game() / play_game(). Just a minor naming issue! Minor or not, it makes sense. I'm picky about things like that too, so now that you've pointed it out, I'm compelled to change the names so they make sense! :) 2. Is there a better way to implement the players than as a class? Better way? Hard to know. There are many ways things can be done, but the way you've chosen is as good as any. Certainly it's good enough for the task you're doing. Yeah, I don't need to know 10 different ways to do things. Mainly I asked this question because the original exercise seemed to focus on using lists to write the game, and I just couldn't think of an efficient way to use a list to store the player attributes like what space they were on. It just seemed a natural candidate for a class attribute. 3. Is there a better way to handle all the print calls that the program
How do you print a string after it's been searched for an RE?
After I've run the re.search function on a string and no match was found, how can I access that string? When I try to print it directly, it's an empty string, I assume because it has been consumed. How do I prevent this? It seems to work fine for this 2.x code: import urllib.request import re next_nothing = '12345' pc_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php? nothing=' pattern = re.compile(r'[0-9]+') while True: page = urllib.request.urlopen(pc_url + next_nothing) match_obj = pattern.search(page.read().decode()) if match_obj: next_nothing = match_obj.group() print(next_nothing) else: print(page.read().decode()) break But when I try it with my own code (3.2), it won't print the text of the page: import urllib.request import re next_nothing = '12345' pc_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php? nothing=' pattern = re.compile(r'[0-9]+') while True: page = urllib.request.urlopen(pc_url + next_nothing) match_obj = pattern.search(page.read().decode()) if match_obj: next_nothing = match_obj.group() print(next_nothing) else: print(page.read().decode()) break P.S. I plan to clean up my code, I know it's not great right now. But my immediate goal is to just figure out why the 2.x code can print text, but my own code can't print page, which are basically the same thing, unless something significant has changed with either the urllib.request module, or the way it's decoded, or something, or is it just an RE issue? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you print a string after it's been searched for an RE?
On Jun 23, 3:47 pm, Ian Kelly ian.g.ke...@gmail.com wrote: On Thu, Jun 23, 2011 at 1:58 PM, John Salerno johnj...@gmail.com wrote: After I've run the re.search function on a string and no match was found, how can I access that string? When I try to print it directly, it's an empty string, I assume because it has been consumed. How do I prevent this? This has nothing to do with regular expressions. It would appear that page.read() is letting you read the response body multiple times in 2.x but not in 3.x, probably due to a change in buffering. Just store the string in a variable and avoid calling page.read() multiple times. Thank you. That worked, and as a result I think my code will look cleaner. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you print a string after it's been searched for an RE?
On Jun 23, 4:47 pm, Thomas L. Shinnick tshin...@prismnet.com wrote: There is also print(match_obj.string) which gives you a copy of the string searched. See end of section 6.2.5. Match Objects I tried that, but the only time I wanted the string printed was when there *wasn't* a match, so the match object was a NoneType. -- http://mail.python.org/mailman/listinfo/python-list
How can I speed up a script that iterates over a large range (600 billion)?
I'm working on the Project Euler exercises and I'm stumped on problem 3: What is the largest prime factor of the number 600851475143 ? Now, I've actually written functions to get a list of the factors of any given number, and then another function to get the prime numbers from that list. It works fine with small numbers, but when I try to feed my get_factors function with the above number (600 billion), naturally it takes forever! But according to the Project Euler website: I've written my program but should it take days to get to the answer? Absolutely not! Each problem has been designed according to a one- minute rule, which means that although it may take several hours to design a successful algorithm with more difficult problems, an efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute. But it definitely takes more than a minute, and I still haven't gotten it to end yet without just canceling it myself. Here is what I have so far. Initially the get_factors function just iterated over the entire range(2, n + 1), but since a number can't have a factor greater than half of itself, I tried to shorten the range by doing range(2, n //2), but that still leaves 300 billion numbers to go through. def get_factors(number): factors = [number] for n in range(2, number // 2): if number % n == 0: factors.append(n) return factors def get_primes(number_list): primes = number_list[:] for n in number_list: for x in range(2, n): if n % x == 0: primes.remove(n) break return primes print(max(get_primes(get_factors(600851475143 Also, I want to make it clear that I DO NOT WANT THE ANSWER. I really want to solve this myself, but the reason I'm asking about it is to see if there really is some way to change this code so that it can get an answer in less than one minute, as the website says should be possible. A hint about what I need to do would be nice, but not an answer. I just don't see any way to get the factors without iterating over the entire range of values, though. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?
On Jun 21, 3:22 pm, Irmen de Jong ir...@-nospam-xs4all.nl wrote: On 21-06-11 22:10, Irmen de Jong wrote: [stuff] I didn't read the last paragraph of John's message until just now, and now realize that what I wrote is likely way too much information for what he asked. I'm sorry. Next time I'll read everything until and including the last full stop. Irmen Don't worry, I was still unclear about what to do after reading all the responses, even yours! But one thing that made me feel better was that I wasn't having a Python problem as much as a *math* problem. I changed my get_factors function to only go as far as the square root of the number in question, and that yielded an answer immediately. :) However, even after reading the Wikipedia page about prime numbers and trial division, I'm still a little unclear as to why the square root of the number is the upper bound of the range you need to check. -- http://mail.python.org/mailman/listinfo/python-list
Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?
On Jun 21, 4:41 pm, Ian Kelly ian.g.ke...@gmail.com wrote: On Tue, Jun 21, 2011 at 3:09 PM, John Salerno johnj...@gmail.com wrote: Don't worry, I was still unclear about what to do after reading all the responses, even yours! But one thing that made me feel better was that I wasn't having a Python problem as much as a *math* problem. I changed my get_factors function to only go as far as the square root of the number in question, and that yielded an answer immediately. :) However, even after reading the Wikipedia page about prime numbers and trial division, I'm still a little unclear as to why the square root of the number is the upper bound of the range you need to check. Careful, note that the greatest prime factor may actually be greater than the square root. It's just that it's possible to find it without iterating past the square root. This is because for each p that is a factor of n, q is also a factor of n, where p * q = n. If p sqrt(n), then q sqrt(n). Therefore you can find p by finding q and dividing n / q. Oh! Now it makes sense! That first sentence helped to put it into perspective, too. The Wikipedia page says more or less the same thing, but this paragraph just made more sense to me. :) Thanks for the all the advice everyone. Now I'm on to problem #4, and I'm stumped again, but that's what's fun! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?
::sigh:: Well, I'm stuck again and it has to do with my get_factors function again, I think. Even with the slight optimization, it's taking forever on 20! (factorial, not excitement) :) It's frustrating because I have the Python right, but I'm getting stuck on the math. The problem: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Here's the function (it's in the problem3.py file, hence the import below): import math def get_factors(number): factors = [] for n in range(2, int(math.sqrt(number))): if number % n == 0: factors.append(n) factors.append(number // n) return factors And here's my new script for the new exercise: import math from problem3 import get_factors max_num = 20 n = math.factorial(max_num) factors = get_factors(n) div_all = [] for x in factors: for y in range(2, max_num+1): if x % y != 0: break elif y == max_num: div_all.append(x) print(min(div_all)) It could easily be that I'm simply approaching it all wrong. I just thought that maybe using the factorial of the highest number in the range (in this case, 20) would be an easy way of finding which numbers to test. -- http://mail.python.org/mailman/listinfo/python-list
Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?
On Jun 21, 9:09 pm, Paul Rubin no.em...@nospam.invalid wrote: John Salerno johnj...@gmail.com writes: It's frustrating because I have the Python right, but I'm getting stuck on the math What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? The answer is lcm [1,2,3, ... 20]. You can figure out how to implement lcm. The Euler problems are not really programming exercises. They are exercises in math and algorithms. Quite a lot of them involve thinking clever and fast ways to do stuff that would be trivial (but too slow) by brute force. In general, once you figure out the right algorithm, writing the code is easy. But you have to be fairly mathematically attuned, to have any chance of spotting the algorithm. If you want programming exercises that are less mathematical, there are some nice ones at rubyquiz.com. They are intended for Ruby but of course you can solve them in Python. Thanks. So far they are helping me with Python too, but definitely not as much as more general exercises would, I'm sure. The part about writing the code is fun, but once that's done, I seem to end up stuck with an inefficient implementation because I don't know the math tricks behind the problem. I'll check out rubyquiz.com. I've been searching for some Python exercises to do but haven't found too many sites with them, at least not in such a nice and organized way as Project Euler. -- http://mail.python.org/mailman/listinfo/python-list
Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?
On Jun 21, 10:02 pm, Mel mwil...@the-wire.com wrote: John Salerno wrote: ::sigh:: Well, I'm stuck again and it has to do with my get_factors function again, I think. Even with the slight optimization, it's taking forever on 20! (factorial, not excitement) :) It's frustrating because I have the Python right, but I'm getting stuck on the math. The problem: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Here's the function (it's in the problem3.py file, hence the import below): import math def get_factors(number): factors = [] for n in range(2, int(math.sqrt(number))): if number % n == 0: factors.append(n) factors.append(number // n) return factors And here's my new script for the new exercise: import math from problem3 import get_factors max_num = 20 n = math.factorial(max_num) factors = get_factors(n) div_all = [] for x in factors: for y in range(2, max_num+1): if x % y != 0: break elif y == max_num: div_all.append(x) print(min(div_all)) It could easily be that I'm simply approaching it all wrong. I just thought that maybe using the factorial of the highest number in the range (in this case, 20) would be an easy way of finding which numbers to test. These are almost trick questions in a way, because of the math behind them. If the question were What is the tallest high-school student in Scranton, PA? then searching a population for the property would be the only way to go. BUT you can also build up the answer knowing the factorization of all the numbers up to 20. Mel. I think you're right. I just read the next problem and it is similar in style, i.e. the example solution involves a small set of numbers which I can write a script for and it would execute within a second, but when I expand the script to include the larger set of numbers for the problem, it then takes ages to execute, making me feel like the trick isn't to figure out the right code, but the right math. -- http://mail.python.org/mailman/listinfo/python-list
Do we still need to inherit from object to create new-style classes?
I can't quite seem to find the answer to this anywhere. The book I'm reading right now was written for Python 3.1 and doesn't use (object), so I'm thinking that was just a way to force new-style classes in 2.x and is no longer necessary in 3.x. Is that right? (The documentation doesn't mention object anymore, but elsewhere on the Python website it says the documentation hasn't been updated for new-style classes yet, hence my confusion.) Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do we still need to inherit from object to create new-style classes?
On Jun 20, 8:33 pm, Benjamin Kaplan benjamin.kap...@case.edu wrote: On Mon, Jun 20, 2011 at 6:26 PM, John Salerno johnj...@gmail.com wrote: I can't quite seem to find the answer to this anywhere. The book I'm reading right now was written for Python 3.1 and doesn't use (object), so I'm thinking that was just a way to force new-style classes in 2.x and is no longer necessary in 3.x. Is that right? (The documentation doesn't mention object anymore, but elsewhere on the Python website it says the documentation hasn't been updated for new-style classes yet, hence my confusion.) Thanks. 3.x got rid of old-style classes altogether, so you are correct- there's no need to explicitly subclass object. Thanks! And apologies for having to start a thread to ask just that! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this base class?
On Jun 19, 8:52 pm, Chris Kaynor ckay...@zindagigames.com wrote: Having a character class (along with possibly player character, non-player character, etc), make sense; however you probably want to make stuff like health, resources, damage, and any other attributes not be handles by any classes or inheritance in order to allow you to make such data-driven (ie, read from a file). Doing so makes the game much more extendable: using classes, you are likely limited to 5 or 'combinations and a few developers (plus, any designers need to know programming). A basic way to determine between using subclasses over a data driven approach is: is there significantly different back-end behavior or merely attribute differences. Can you give a basic example of how this data-driven approach would work? You don't have to provide any code, just a description would be helpful. Such as, do I create a data file per character, and then have each character instance read/write to that file? Is it good to have so many files open at once, or would they only need to be read, closed, then opened again at the end to write? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this base class?
Whew, thanks for all the responses! I will think about it carefully and decide on a way. I was leaning toward simply assigning the health, resource, etc. variables in the __init__ method, like this: def __init__(self, name): self.name = name self.health = 50 self.resource = 10 I never did like the idea of using the parameters if I never intended to pass them in...just seems wrong. :) The idea of not using a base Character class at all threw me for a loop though, so I need to think about that too! -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you copy files from one location to another?
On Jun 17, 2:25 am, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: John Salerno wrote: I want it to copy a set of files/directories from a location on my C:\ drive to another directory on my E:\ drive. I don't want to rename or delete the originals, It sounds like shutil.copy() is what you want, or one of the other related functions in the shutil module. -- Greg shutil.copy(src, dst) Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings. This looks promising! But can src be a directory, or does it have to be a file? For my purposes (copying a saved games folder), I don't really need to specify particular files to copy, I just need to copy the entire Saved Games directory, so that's what would be my src argument if allowed. Also, the directory I want to copy also contains a directory. Will the contents of that directory also be copied, or do I have to do some kind of walk-through of the directory manually? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you copy files from one location to another?
On Jun 17, 2:23 pm, Terry Reedy tjre...@udel.edu wrote: If you follow the second part of Greg's suggestion 'or one of the other related function in the shutil module', you will find copytree() Recursively copy an entire directory tree rooted at src. Yeah, but shutil.copytree says: The destination directory, named by dst, must not already exist which again brings me back to the original problem. All I'm looking for is a simple way to copy files from one location to another, overwriting as necessary, but there doesn't seem to be a single function that does just that. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you copy files from one location to another?
On Jun 17, 5:15 pm, Ethan Furman et...@stoneleaf.us wrote: John Salerno wrote: On Jun 17, 2:23 pm, Terry Reedy tjre...@udel.edu wrote: If you follow the second part of Greg's suggestion 'or one of the other related function in the shutil module', you will find copytree() Recursively copy an entire directory tree rooted at src. Yeah, but shutil.copytree says: The destination directory, named by dst, must not already exist which again brings me back to the original problem. All I'm looking for is a simple way to copy files from one location to another, overwriting as necessary, but there doesn't seem to be a single function that does just that. If you don't mind deleting what's already there: shutil.rmtree(...) shutil.copytree(...) If you do mind, roll your own (or borrow ;): 8--- #stripped down and modified version from 2.7 shutil (not tested) def copytree(src, dst): names = os.listdir(src) if not os.path.exists(dst): # no error if already exists os.makedirs(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore) else: copy2(srcname, dstname) except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files except Error, err: errors.extend(err.args[0]) if errors: raise Error(errors) 8--- ~Ethan~ Thanks. Deleting what is already there is not a problem, I was just hoping to have it overwritten without any extra steps, but that's no big deal. -- http://mail.python.org/mailman/listinfo/python-list
What's the best way to write this base class?
Let's say I'm writing a game (really I'm just practicing OOP) and I want to create a Character base class, which more specific classes will subclass, such as Warrior, Wizard, etc. Which of the following ways is better, or is there another way? Note: I have in mind that when a specific subclass (Warrior, Wizard, etc.) is created, the only argument that will ever be passed to the __init__ method is the name. The other variables will never be explicitly passed, but will be set during initialization. With that in mind, here are the ways I've come up with: 1) class Character: def __init__(self, name, base_health=50, base_resource=10): self.name = name self.health = base_health self.resource = base_resource 2) class Character: base_health = 50 base_resource = 10 def __init__(self, name): self.name = name self.health = base_health self.resource = base_resource 3) BASE_HEALTH = 50 BASE_RESOURCE = 10 class Character: def __init__(self, name): self.name = name self.health = BASE_HEALTH self.resource = BASE_RESOURCE -- http://mail.python.org/mailman/listinfo/python-list
How do you copy files from one location to another?
Based on what I've read, it seems os.rename is the proper function to use, but I'm a little confused about the syntax. Basically I just want to write a simple script that will back up my saved game files when I run it. So I want it to copy a set of files/directories from a location on my C:\ drive to another directory on my E:\ drive. I don't want to rename or delete the originals, just move them. I also want them to automatically overwrite whatever already happens to be in the location on the E:\ drive. Is os.rename the proper function for this? Mainly I was because the Module Index says this: On Windows, if dst already exists, OSError will be raised even if it is a file.. so it sounds like I can't move the files to a location where those file names already exist. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using just the Mako part of Pylons?
Bruno Desthuilliers wrote: John Salerno a écrit : I just installed Pylons onto my hosting server so I could try out templating with Mako, but it seems a little more complicated than that. Err... Actually, it's certainly a little less complicated than that. First point: Mako is totally independant from Pylons. Second point: you don't need any web server to use Mako - it's just another Python package. Well, so far I have installed Pylons onto my web server, but a test Mako template isn't rendering, it just prints the text to the browser. There's got to be something more to do to get it all hooked up so that it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mako vs. Cheetah?
Tim Roberts wrote: John Salerno [EMAIL PROTECTED] wrote: Is it correct to say that Mako allows you to embed Python code within HTML, whereas Cheetah requires a certain amount of tweaking of Python code so that it isn't really code you could just run independently in the interpreter? I'm getting that impression from what I see so far. What gives you that impression? I'm just curious. Other than the special characters used, my impression is that the two are far more similar than they are different. Well, that opinion was based mostly on my initial exposure to each one. The main reason was that Cheetah seems to require a lot of $ signs, even in the Pyton code itself, such as: for $thing in $things: etc whereas with Mako you can just write straight Python code. Overall I think I'm liking Mako better, which is fine since I want to learn Pylons and it's the default. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do web templates separate content and logic?
[EMAIL PROTECTED] wrote: For which definitions of content and logic ??? The point of mvc is to keep domain logic separated from presentation logic, not to remove logic from presentation (which just couldn't work). Templating systems are for presentation logic. Whether they work by embedding an existing complete programmation language or by providing they're own specialised mini-language (or a mix of both) is not the point here IMHO. No, I don't mean presentation logic at all. I mean something along the lines of combining HTML (which is what I refer to as content) and Python (which is what I meant by logic). So for example, if you have code like this (and this isn't necessarily proper code, I'm just making this up, but you'll see what I mean): body h1Big Important Topic/h1 pThis is where I say something important about/p ol % for topic in topics: li${topic}/li /ol /body Humph, I just made up that example to make the point that when you no longer have pure HTML, but instead have programmatic logic (Python) mixed in with the HTML, then you are mixing content and logic. However, as soon as I finished typing it out, it occurred to me that even the so-called logic in this example is really only producing more content to display. So maybe my question was a little premature. Or could it just be that this is a *good* way to mix HTML and Python, and there are other ways which may be bad? (For example, connecting to a database, like Sebastian's example. That definitely seems out of place in an HTML file.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple regular expression
python_enthu [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I am trying this.. what is wrong in this.. IDLE 1.2.2 import re a=my name is fname lname p=re.compile('name') m=p.match (a) print p.match(a) None match( string[, pos[, endpos]]) If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match. search( string[, pos[, endpos]]) Scan through string looking for a location where this regular expression produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. -- http://mail.python.org/mailman/listinfo/python-list
How do web templates separate content and logic?
I've been doing some research on web templates, and even though I read that they help enforce the MVC pattern, I don't really understand how they are keeping content and logic separated. Layout is easy, it's just not there as far as I can see, and CSS can be used for that. But when you have a templating system that mixes HTML and Python code, how is this helping to keep things separate? It seems to be the same issue that some people have with PHP (that it is too integrated with the HTML, rather than being separate). Of course, I suppose whether or not any of this matters depends on if you are a web designer or a programmer, but am I missing something about templates, or is it really the case that they, more or less by definition, combine content and logic? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: what is meaning of @ in pyhon program.
Damon Getsman [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Okay, maybe I just didn't understand the websites that were given as examples as to 'decoration'. I first came across the unusual '@' when I was browsing through some extreme beginner's information on os.x method descriptions. I asked some other people about it and they had no idea what it meant. I don't _THINK_ that the decoration definition fits, though, because the examples that I saw it in had it prefixing an if conditional a for loop. The OP's code sample makes sense for decorators, I think. Can you post an actual sample of what it is you saw? Sounds weird. -- http://mail.python.org/mailman/listinfo/python-list
Using just the Mako part of Pylons?
I just installed Pylons onto my hosting server so I could try out templating with Mako, but it seems a little more complicated than that. From the look of it all, the site seems to want a full Pylons application. Is it possible to just use regular HTML files with a bit of the Mako language embedded, or will I actually have to use all aspects of Pylons? In other words, can I use *just* Mako (sort of like as a replacement for PHP) without having to use a framework? For example, I'd like to just test out the %include / tag and see it in action, but the site doesn't seem to be looking for a regular HTML file (like index.html), it seems to want a controller. So is Pylons overkill for just this? How would I try out *just* Mako? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Using just the Mako part of Pylons?
John Salerno wrote: I just installed Pylons onto my hosting server so I could try out templating with Mako, but it seems a little more complicated than that. From the look of it all, the site seems to want a full Pylons application. Is it possible to just use regular HTML files with a bit of the Mako language embedded, or will I actually have to use all aspects of Pylons? In other words, can I use *just* Mako (sort of like as a replacement for PHP) without having to use a framework? For example, I'd like to just test out the %include / tag and see it in action, but the site doesn't seem to be looking for a regular HTML file (like index.html), it seems to want a controller. So is Pylons overkill for just this? How would I try out *just* Mako? Thanks! Ok, I figured out how to get it to just use regular HTML files as if it were a regular, static site. However, the include directive I used didn't seem to work. I used: %include file=separate.html/ And it just shows that text in the browser. Am I missing something? -- http://mail.python.org/mailman/listinfo/python-list
Re: Mako vs. Cheetah?
John Salerno [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I always have the desire to learn one thing well instead of split my attention between several options, so I'm trying to decide which of these two to start learning. Are there any particular things I should look at when deciding between them, in terms of features, for example? Do they do all the same things? Is it correct to say that Mako allows you to embed Python code within HTML, whereas Cheetah requires a certain amount of tweaking of Python code so that it isn't really code you could just run independently in the interpreter? I'm getting that impression from what I see so far. -- http://mail.python.org/mailman/listinfo/python-list
Re: I Need A Placeholder
Joshua Kugler [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] except: pass is the usual technique there. Is there any other? -- http://mail.python.org/mailman/listinfo/python-list
Re: url.encore/quote
zowtar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] urlencode({'page': i, 'order': 'desc', 'style': 'flex power'}) return: page=1order=descstyle=flex+power but I want: page=1order=descstyle=flex%20power and url.quote don't put the 's and ='s any idea guys? urlencode() uses quote_plus() when it creates a URL, which is why you are getting the plus signs. Unfortunately I don't have Python at work, so I can't try this, but maybe do: quote(urlencode({'page': i, 'order': 'desc', 'style': 'flex power'})) and see if that works? I'm not sure if quote() will convert the %20 into +, though, but it may. -- http://mail.python.org/mailman/listinfo/python-list
Re: I Need A Placeholder
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] if 0: 42 How Pythonic. ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: url.encore/quote
ianitux [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] and see if that works? I'm not sure if quote() will convert the %20 into +, though, but it may. This is what quot do. import urllib u = urllib u.quote(u.urlencode({'page': 'i', 'order': 'desc', 'style': 'flex power'})) 'style%3Dflex%2Bpower%26page%3Di%26order%3Ddesc' I know quote will convert spaces to %20, just wasn't sure if it would explicitly convert + to %20. But it seems the output isn't what the OP wants anyway, because he wanted the and = symbols. -- http://mail.python.org/mailman/listinfo/python-list
Mako vs. Cheetah?
I always have the desire to learn one thing well instead of split my attention between several options, so I'm trying to decide which of these two to start learning. Are there any particular things I should look at when deciding between them, in terms of features, for example? Do they do all the same things? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Using Python to run SSH commands on a remote server
Generally speaking, what tools would I use to do this? Is there a built-in module for it? I looked at the telnetlib module, but the documentation wasn't really complete enough for me to get a good idea of it. Is Telnet and SSH even the same thing? Basically, I want to write a script that will automate the process of making all .py files on my web server executable (chmod 755, or something similar). Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python to run SSH commands on a remote server
Jeffrey Froman [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Be careful, this procedure sounds potential risky, security-wise ;-) I guess a blanket process might be a tad risky, but don't you want all CGI files to be executable by all? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python to run SSH commands on a remote server
Jeffrey Froman wrote: Also note that all .py files on my web server is not necessarily restricted to CGI scripts -- and therein lies the real gist of my cautionary note. Yeah, I realized that afterwards. Good point. I was assuming all my executable files would be CGI, but that's not a good assumption to make! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
Dennis Lee Bieber wrote: On Wed, 18 Jun 2008 09:56:29 -0400, John Salerno [EMAIL PROTECTED] declaimed the following in comp.lang.python: Interesting point. I'm not sure if it works that way though. I *think* I tried sending an empty string from the server back to the client, and as expected it exited the loop and closed the client, which doesn't make sense to me, since an empty string could be perfectly valid return data. Okay... I suppose socket could consider a transmission with 0 data bytes as valid data. The main key is that there had to be send of 0 data -- opposed to just not receiving anything.. No, I think you're right. I read elsewhere that when I send() call returns 0 bytes, the connection is automatically closed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
Dennis Lee Bieber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The first if is checking for lack of interactive input -- and, as coded, will never break out as ANY response to the prompt will have a newline attached. Try with raw_input( ).strip() instead Well, I know the first if block works properly. Pressing just ENTER will exit the loop and close the client socket. The second if is checking for empty receive block... And since .recv() blocks until it has something to return (as I recall) it may not be of use... Interesting point. I'm not sure if it works that way though. I *think* I tried sending an empty string from the server back to the client, and as expected it exited the loop and closed the client, which doesn't make sense to me, since an empty string could be perfectly valid return data. I opted to remove the second if statement and see where that takes me. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: One more socket programming question
Tim Roberts [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] John Salerno [EMAIL PROTECTED] wrote: I'm now experimenting with the SocketServer class. Originally I subclassed the StreamRequestHandler to make my own custom handler, but a result of this seems to be that the client socket closes after it has been used, instead of staying open. Right. handle is not called for one REQUEST at a time, it's called for one CONNECTION at a time. If you need a connection to be persistent, then your handle() function needs to sit in a loop making recv calls until you detect that the conversation is complete. Ah, so I need to rewrite my handle method. I was thinking that the specialized setup() and/or finish() calls from StreamRequestHandler were the reason that the connection was closed after one use (which is why I tried BaseRequestHandler instead). Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Both programs say recv(buffer_size) - buffer_size is the maximum number of bytes to be RECEIVED, that is, READ. recv will return at most buffer_size bytes. It may return less than that, even if the other side sent the data in a single operation. Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. http://docs.python.org/lib/socket-objects.html I was wondering about sendall(). The examples I've read in two different books are consistent in their use of send() and don't even mention sendall(), so I thought maybe it was for a more specialized situation. Yes, it is stored in an intermediate buffer until you read it. You typed hello and sent it, the server replied with the string You typed: hello; the OS stores it. You read only 10 bytes You typed:, the remaining are still in the buffer. Next round: you type something, the server replies, you read the remaining bytes from the original reply, and so on... Oh I didn't even count You typed: as part of the 10 bytes! And what a coincidence that it happens to be exactly 10 characters! That really helped to hide the problem from me! (Note that in this particular configuration, the client will fill its buffer at some time: because the server sends at least 11 bytes each round, but the client reads at most 10 bytes, so the client is always behind the server...) How is the server sending back 11 bytes? Is it because it's sending at least the 10 characters, plus the extra space? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
John Salerno [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] from socket import * host = 'localhost' port = 51567 address = (host, port) buffer_size = 1024 client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(address) while True: data = raw_input(' ') if not data: break client_socket.send(data) data = client_socket.recv(buffer_size) if not data: break print data client_socket.close() Also, is that second if not data: break statement necessary? It seems like once you get past the first if, you don't need the second one. Of course, I guses it's possible that the server could return a False value, but even still, would it make sense to break out of the loop and close the connection because of that? It runs fine without the if statement, but I'm wondering if I just haven't encountered the proper problem situation yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. http://docs.python.org/lib/socket-objects.html If I use sendall(), am I still recv'ing data with a given buffer size? What if I send more data than the buffer size. Is my code as written not prepared to handle that case? It seems like I might need to continue receiving data until there is no more to receive (in a loop?)...is that right? -- http://mail.python.org/mailman/listinfo/python-list