Re: [Tutor] My First Program
Hi! My first ever program that I've created is a simple game called State Capitals. It's straight forward; 5 simple questions about state capitals ina non-GUI format. Can someone look over my code and offer tips, suggestions,criticism? Also, I'd like to be able to end the program if the user misses 3 questions (i.e., kick them out after the 3rd wrong answer). How can I dothis? Thanks!print \nState Capitals! Answer a or b to the following questions.\nquestion = raw_input(Question 1 - What is the capital of NC, a: Raleigh or b: Atlanta? )if question == a:print Yes\nelse:print WRONG\nquestion = raw_input(Question 2 - What is the capital of SC, a: Greenville or b: Columbia? )if question == b:print Yes\nelse:print WRONG\nquestion = raw_input(Question 3 - What is the capital of NY, a: Albany or b: Buffalo?)if question == a:print Yes\nelse:print WRONG\nquestion = raw_input(Question 4 - What is the capital of OH, a: Cleveland or b: Columbus? )if question == b:print Yes\nelse:print WRONG\nquestion = raw_input(Question 5 - What is the capital of TX, a: Houston or b: Austin? )if question == b:print Yes\nelse:print WRONG\n Hi! Glad you picked up Python. You'll probably enjoy it. This might be over your head, but I'd use functions for your Yes and WRONG: def yes(): print Yes\n def WRONG(): print WRONG\n # Now for the sample code: question = raw_input(Question 4 - What is the capital of OH, a: Cleveland or b: Columbus? ) if question == b: yes() else: WRONG() Hope this helps. Joe -- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read XML
Joseph Quigley wrote: How do I read xml? The python documentation doesn't help me. Or, how can I remove the (tags?) stuff in these things?If you want to strip out all the tags and just leave the text,Strip-o-Gram might do it. http://www.zope.org/Members/chrisw/StripOGramThere was a thread here recently about other tools for stripping textout of HTML but I can't find it.Kent Thanks. This looks like it will do the trick. -- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Timer
I'd like to make a 30 minute timer. How an I do that? With time? Thanks, Joe-- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Timer
thanks. I'm also trying time.time() I hope one works. One disadvantage though, now that i think of it is that time.sleep() freezes everything and I don't think I want that but I'll try it anyway.On 12/6/05, Pujo Aji [EMAIL PROTECTED] wrote:Probably the simplest thing is to make the computer sleep in a specific time. Example:def main(): time.sleep(2) # sleeping 2 second print 'finish'Cheers,pujo On 12/6/05, Joseph Quigley [EMAIL PROTECTED] wrote: I'd like to make a 30 minute timer. How an I do that? With time? Thanks, Joe-- There are 10 different types of people in the world.Those who understand binary and those who don't. ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Timer
Sorry, this is a little console project to tell me when there new headlines on slashdot.org using their rss file. All it does is see if there's something different and if there is it will tell you. Here's my timer: while True: if count 1800: break time.sleep(1) count += 1 Or should I just do: time.sleep(1800)? A little context would be helpful. If you are writing a standalone appthat just needs to wait 30 minutes, then do something, use time.sleep().If the program needs to be able to do something else at the same time as the timer is running, you will have to put the sleep() call in aseparate thread. threading.Timer will do this for you, see this recipefor an example of its use: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440476If you are running in a GUI app, the GUI toolkit may have a timer youcan use, for example in Tkinter widgets have an after() method thatschedules a callback for a future time; wxPython has wx.FutureCall.http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm http://www.wxpython.org/docs/api/wx.FutureCall-class.htmlKent-- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] whats the best command to end a program
if int(time.strftime(%H)) 4:some end the program command else:continuewhat would be best used here ? I would use raise SystemExit But another possibility is: import sys then to exit sys.exit()-- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Read XML
How do I read xml? The python documentation doesn't help me. Or, how can I remove the (tags?) stuff in these things? thanks, Joe-- There are 10 different types of people in the world.Those who understand binary and those who don't. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Module Thread
Hi, thanks for the info. I'd like o know if you guys know of any good documentation on the threading module. Or if you could give me a quick intro to it. Or am I asking too much? If so I'll try to work it out on my own for a little. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Module Thread
I'm back to my IRC client. I accidentally found the thread module in the Python 2.3 documentation while looking at the time module. What I can't get ideas or hints from the documentation is: What will i do to receive and send at the same time via console? or: Should I forget the idea of a console and start learning GUI which will do this for me. and lastly: Should I have a program that handles all the sending and receiving and puts it into a file and have to sub programs one that will write to the file that the main program will read and send and one that just reads the file which is received data. I'm interested in python disto threads rather than other modules. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] slide show won't display the images in right order
Hi, Thank you all for your help. I must say that the python mailing list is the most helpfull of any place I've ever asked for help on. A close second comes linuxquestions.org. Somehow sort() got passed me in the Python Documentation and sort() has fixed all my problems. EDIT Sort still didn't work but I found another fault: the direction variable. I took it out and had x += 1 and x += -1 to view the pictures ShowImg(files[x]) (x is the location of the image in the list 0, 4, 100, etc). It works great now. Hey, if you are a Garfield fan or you just want to see the source code, you can download the whole kaboodle (it's cross platform) from: http://www.jqsoftware.com/software/Gacor/gacor-096.py (Released under the GNU GPL) Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] AttributeError: 'str' object has no attribute, 'geturl'
You are welcome. This time I would like to help you but the code is incomplete (import error for Image) and I have never used urllib2 so I don't really know what to do. Again, try to debug it with pdb. Place import pdb; pdb.set_trace() where you want the break point and see what's going on. Javier Hi, I'm embarased to say that I was trying to download an image that doesn't exist (I had the url wrong). Thanks for hte tip on pdb, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] AttributeError: 'str' object has no attribute 'geturl'
Well, I'm back to coding more on my comic downloader and viewer and I keep getting this error: Traceback (most recent call last): File F:\Gacor\getgarf.py, line 244, in ? getImg(Data.todayStrip) File F:\Gacor\getgarf.py, line 127, in getImg Data.f.geturl() AttributeError: 'str' object has no attribute 'geturl' My code is attached (sorry, but it's got lot's of text) #! /usr/bin/env python ## # Created by Joseph Quigley # # This program is under the GNU GPL Licence # # Either version 2 or any higher version. # # Garfield and the Garfield trade mark are # # Copyrighted by Paws Inc. # ## # Import modules import time import urllib2 import os import sys from Tkinter import * import Image import ImageTk import getpass class Data: # Define time and date todays_date = time.localtime(time.time()) todayDay = time.strftime(%d, todays_date) todayMonth = time.strftime(%m, todays_date) todayYear = time.strftime(%y, todays_date) todayYearFull = time.strftime(%Y, todays_date) getDate = '' month = '' day = '' yearFull = '' year = '' # More file location junk stripName =http://images.ucomics.com/comics/ga/%s/; % (yearFull) todayStrip = ga%s%s%s.gif % (todayYear, todayMonth, todayDay) otherStrip = download = f = VERSION = '0.9.3' try: if sys.argv[1] == --version: print \nGacor %s A Garfield Comic Downloader and reader. Copyright (C) 2005 Joseph Quigley This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n % Data.VERSION raise SystemExit except IndexError: print \n * 100 user = getpass.getuser() name = 'gacor' if os.name == 'posix': imgDir = '/home/%s/.gacor/' % user elif os.name == 'nt': if os.path.exists('C:\Documents and Settings'): imgDir = C:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('D:\Documents and Settings'): imgDir = D:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('E:\Documents and Settings'): imgDir = E:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('F:\Documents and Settings'): imgDir = F:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('G:\Documents and Settings'): imgDir = G:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('H:\Documents and Settings'): imgDir = H:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('I:\Documents and Settings'): imgDir = I:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('J:\Documents and Settings'): imgDir = J:\\Documents and Settings\\%s\\.gacor\\ % user if os.path.exists('K:\Documents and Settings'): imgDir = K:\\Documents and Settings\\%s\\.gacor\\ % user else: setImgDir = raw_input(Please specify your Documents and Settings Drive\n(eg: C:\\ not C)\n ) imgDir = %sDocuments and Settings\\%s\\.gacor\\ % user if not os.path.exists(imgDir): os.mkdir(imgDir) # Errors def Connect(): urllib2_URLError = Temporary failure in name resolution. This means that you may not be online or the site is down. You may want to try again later. print Connecting to server... try: Data.f = urllib2.urlopen(%s%s % (Data.stripName, Data.todayStrip)) except urllib2.URLError: print urllib2_URLError print Connected. def Dsp_Image(pic): root = Tk() root.title(GaCoR (Garfield Comic Reader)) app = Frame(root) app.grid() img = Image.open(pic) imgPrep = ImageTk.PhotoImage(img) imgShow = Label(app, image=imgPrep).grid() info = Label(app, text=Displaying a Garfield for %s\%s\%s. % (Data.month, Data.day, Data.year)).grid() app.mainloop() def getImg(pic): print Dowloading Image print Data.f Data.f.geturl() pict_Data = Data.f.read() pict = file(%s%s % (imgDir, pic), 'w') pict.write(pict_Data) pict.close() print Finished Download def ShowImg(pic): Dsp_Image(%s%s % (imgDir, pic)) def comicDate(): while True: print \nEnter comic date in mmdd format (eg: 09122002 Data.getDate = list(raw_input( )) if len(Data.getDate) 8: print
Re: [Tutor] More than one thing at a time?
Hi Michael, You're explanation helped a lot, however, I'm really not good at gui programming and the irc client was supposed to be a console application, but: Would it be hard to just have a send texbox and receive read-only text box? I'll try this, but I think I should mention that I'm using python-irclib from sourceforge. I'll try Kamaelia, thanks a lot. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Embedding
Hi, Ok, I'll try to convince them to try python... but still, would it be best to just: Program in C with Python and Java scripts Program in Python with a little bit of C? The game we're trying to make is a Super Mario type game (or super tux for you like linux games). I suppose pygame would make it a breeze for video, sound and graphics! My only problem is I haven't done any games withy pygame at all and can't find any pygame tutorials (when I google). Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] More than one thing at a time?
Hi, I've got a problem: I've got a semi working IRC client. There's a function that is for receiving and one for sending. How can I have a loop where I can receive messages, yet still have a send prompt? Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Embedding
hi, I'm working on a game with other friends who don't use python. However they'd like to use Java Python and C/C++. I was wondering if I could embedd C in a Python program in Jython and lastly in java (or the other way arround). My goal is: Can these for languages be used to make one program? Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Embedding
From: Kent Johnson [EMAIL PROTECTED] Subject: Re: [Tutor] Embedding Not easily. You can embed C in Java with JNI. Thanks, that just migh be perfect... or is there a program that will embedd Java into C/C++? You can access the result from Jython. But the original requirement seems a bit weird - why Java and C in one program? ISTM you should pick Python/C or Jython/Java but not both. Can you say more about what you are trying to accomplish? Well we are three programmers. I know python, another knows Java and the other C++. We are trying to figure out how to combine all three langauges to make a game. (By Java Python do you mean Java AND Python Yes. Sorry forgot the comma or the Java version of Python e.g. Jython?) No. Thanks. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Binary 2 text text 2 binary
Hi I'm playing with a Binary to text text to binary converter. I can't figure out how to replace the characters (first stage: text to binary). I thought lists would be the best but I really don't know how to use them... here's my code: #! /usr/bin/env python A = 0101 B = 0110 C = 0111 D = 01000100 E = 01000101 F = 01000110 G = 01000111 H = 01001000 I = 01001001 J = 01001010 K = 01001011 L = 01001100 M = 01001101 N = 01001110 O = 0100 P = 0101 Q = 01010001 R = 01010010 S = 01010011 T = 01010100 U = 01010101 V = 01010110 W = 01010111 X = 01011000 Y = 01011001 Z = 01011010 # Symbols exclamationPoint = 0010 0001 hash = 0010 0011 dollar = 001 0100 percent = 0010 0101 _and = 0010 0110 parentheses = 0010 1000 closeParentheses = 0010 1001 comma = 0010 1100 dash = 0010 1101 period = 0010 1110 underline = 0101 # Numbers zero = 0011 one = 00110001 two = 00110010 three = 00110011 four = 00110100 five = 00110101 six = 00110110 seven = 00110111 eight = 00111000 nine = 00111001 ltra = a ltrb = b ltrc = c while True: text = raw_input(Enter text: ) text = list(text) Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to install python on to a remote apache server
Hi, I'd like towrite some internet applications but I don't know how to test them unless I have python on my server. However, It's running Apache 1.3.3 and it's a remote one (I'm in the Americas and it's in Europe) so I don't know how to access it. I also would like to know what platform of python to download. Is there a special server edition? Or do I just use a regular Linux edition? Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IRC Client Trouble -- too many new lines
Hi, Liam Clarke-Hutchinson wrote: Hi Joseph, while (1): buffer = Data.IRC.recv(1024) msg = string.split(buffer) Just a warning, the string module will be removed/deprecated come Py3K. Better to use - buffer.split() nick_name = msg[0][:msg[0].find("!")] filetxt.write(nick_name.lstrip(':') + ' - ' + message.lstrip(':') + '\n') Ok. Thanks for the heads up. As to your printing problem, I'm not sure if you're referring to - print msg[print_msg] Oh, sorry. I'm refering to the print msg[print_msg] And I'm not sure if you want it to print without an additional newline, or with a newline. Well every word is on it's own new line (I get a huge message from the IRC server) and I'd like a word wrap or something to fix that. #Incidentally, it's a bit simpler to maintain this kinda loop #instead of a while loop. for item in msg: item.rstrip() #Will strip whitespace (\t\r\n etc.) by default print item Ah. Thanks If you're wanting to print without the newline that print adds, why not do a join like this one? message = ' '.join(msg[3:]) print ' '.join(msg) ? Thanks again. This is proving very usefull. What output you're expecting I'm expecting a large amount of text without new lines for each word, and possible word wrapping. What output you're getting Example: this is the type of message I'm getting and as you can see , it's really annoying! PS Your code is interesting, I've never dealt with the IRC protocol before,so it's good to see a demonstration of it. I edited the code from a Python Cookbook recipe. I may toddle off and check out that RFC. Yes. Some people on a forum that I hang oput with suggested a chat room. A freind of mine suggested IRC and python. He's doing the server and I'm doing the client. I'm testing the client on freenode.. only thing I could think of at the time. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] IRC Client Trouble -- too many new lines
Hi, My IRC Client can't print the IRC server messages without a newline for each message in a giant list that I recieve... here's my code: import socket, string, sys #some user data, change as per your taste class Data: SERVER = 'irc.freenode.net' CHANNEL = #python NICKNAME = Pythonatic PORT = 6667 #open a socket to handle the connection IRC = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #open a connection with the server def Irc_Conn(): print Connecting to IRC server (%s). % (Data.SERVER) try: Data.IRC.connect((Data.SERVER, Data.PORT)) except socket.gaierror: print Error: Name or service not known. This could mean that you aren't connected to the internet or that the server is down. raise SystemExit #simple function to send data through the socket def Send_Data(command): Data.IRC.send(command + '\n') #join the channel def Join(channel): Send_Data(JOIN %s % channel) #send login data (customizable) def Login(nickname, username='user', password = None, realname='You don\'t need2know', hostname='Slackware', servername='Intelnett'): Send_Data(USER %s %s %s %s % (username, hostname, servername, realname)) Send_Data(NICK + NICKNAME) Irc_Conn() Login(Data.NICKNAME) Join(Data.CHANNEL) while (1): buffer = Data.IRC.recv(1024) msg = string.split(buffer) if msg[0] == PING: #check if server have sent ping command Send_Data(PONG %s % msg[1]) #answer with pong as per RFC 1459 if msg[1] == 'PRIVMSG' and msg[2] == Data.NICKNAME: filetxt = open('%stmp' % (Data.configFileRead[8]), 'a+') #open an arbitrary file to store the messages nick_name = msg[0][:string.find(msg[0],!)] #if a private message is sent to you catch it message = ' '.join(msg[3:]) filetxt.write(string.lstrip(nick_name, ':') + ' - ' + string.lstrip(message, ':') + '\n') #write to the file filetxt.flush() #don't wait for next message, write it now! if msg: msg_length = len(msg) print_msg = 0 while True: if print_msg == msg_length: break else: print msg[print_msg] print_msg = print_msg + 1 continue Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GetGarf (sorry, this time with attachment)
Ismael wrote: Do you know about Dosage? It downloads lots of comics (around 500 - of course, you choose which ones). Among those, there's Garfield. It's catchup option will download past comics for you, and even generate RSS feeds and html pages if you wish to. http://slipgate.za.net/dosage/ Ismael No I didn't.. is is free? If so then great! Just what I was looking for. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting rid of the newline in file
Alan G wrote: f = file(foo, 'w') Using 'w' will destroy the contents of the file, I assume you are really using 'r'? Ah yes.. sorry. Each line will be terminated by a newline, you can use rstrip() to remove it: print fileContents[0].rstrip() + Hi! Thanks a lot! This really helps. Joseph ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] GetGarf
Ok... more probs with my GetGarf program... First I acidently and permanently deleted all versions and now I've improved it but it won't download new images Here's the code (attached... sorry :-( ) More Questions to come later. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] IRC Client documentation
Hi, I've googled, checked out the Python Cookbook but still can't find anything usefull. I need to make python IRC client or find one written in python to start off with. DO you know of anything? thanks, Joseph ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] GetGarf (sorry, this time with attachment)
Ooops Sorry, no attachment. Ok... more probs with my GetGarf program... First I acidently and permanently deleted all versions and now I've improved it but it won't download new images Here's the code (attached... sorry :-( ) More Questions to come later. Thanks, Joe #! /usr/bin/env python ## # Created by Joseph Quigley # # This program is under the GNU GPL Licence # # Either version 2 or any higher version. # # Garfield and the Garfield trade mark are # # Copyrighted by Paws Inc. # ## # Import modules import time import urllib2 import os from Tkinter import * import Image import ImageTk import getpass class Data: # Define time and date todays_date = time.localtime(time.time()) dayNum = time.strftime(%d, todays_date) monthNum = time.strftime(%m, todays_date) yearNum = time.strftime(%y, todays_date) yearNumFull = time.strftime(%Y, todays_date) ocDay = dayNum ocMonth = monthNum ocYear = yearNum ocYearFull = yearNumFull # More file location junk stripName =http://images.ucomics.com/comics/ga/%s/; % (yearNumFull) todayStrip = ga%s%s%s.gif % (yearNum, monthNum, dayNum) configFile = file(/home/%s/.getgarf/config % (getpass.getuser()), 'r') location = configFile.readline() download = f = # Help stuff commands = get today --\tDownload today's (%s/%s/%s) garfield. If it is already downloaed it will read \toff the hard drive cache. get other --\tNot yet available h -- \tDisplay this help exit -- \tClose Program % (monthNum, dayNum, yearNum) help = Config file: GetGarf is picky, the config file must have the exact location of the images and dirctories that GetGarf uses. On Linux the config file is in the user's home directory. def Connect(url): # Errors urllib2_URLError = Temporary failure in name resolution. This means that you may not be online or the site is down. You may want to try again later. print Connecting to server... try: Data.f = urllib2.urlopen(url) except urllib2.URLError: print urllib2_URLError print Connected. def Dsp_Image(pic): root = Tk() root.title(Garfield Comic Reader) app = Frame(root) app.grid() img = Image.open(pic) imgPrep = ImageTk.PhotoImage(img) imgShow = Label(app, image=imgPrep).grid() #imgDate = Label(app, text=Showing a %s/%s/%s strip % (Data.monthNum, Data.dayNum, Data.yearNum)).grid() app.mainloop() def Save_Image(pic): print Dowloading Image pic_data = Data.geturl() pic_Data = Data.f.read() picture = file(pic, 'w') picture.write(pic_Data) picture.close() print Done. # Enough defining lets get our hands dirty. def main(): while True: prompt = raw_input(Type 'h' (no quotes) for help and press Enter (Return).\nGetGarf ) if prompt == get today: try: Dsp_Image(%s/%s % (Data.location, Data.todayStrip)) except IOError: Connect(%s%s % (Data.stripName, Data.todayStrip)) Save_Image(%sga%s%s%s.gif % (Data.location, Data.ocMonth, Data.ocDay, Data.ocYear)) print Displaying Image.\n elif prompt == get old: oldComicDate = raw_input(Type the date in yymmdd format.\nNo /'s please (eg: 010309 for 2001, March 9th)\n ) year = raw_input(Enter the year of the commic you'd like to view: ) try: Dsp_Image(%s/ga%s.gif % (Data.location, oldComicDate)) except IOError: Connect(http://images.ucomics.com/comics/ga/%s/%s; % (year, oldComicDate)) Save_Image(%s/ga%s.gif % (Data.location, oldComicDate)) print Displaying Image.\n Dsp_Image(%s/ga%s.gif % (Data.location, oldComicDate)) elif ((prompt == 'h') or ('H' == prompt)): print Here are the commands you can type: print Data.commands print print Data.help elif prompt == exit: raise SystemExit else: print Data.commands main() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IRC Client documentation
Poor Yorick wrote: Joseph Quigley wrote: You might want to look into Twisted at http://twistedmatrix.com/ A quick google for python twisted irc turned up this: http://sourceforge.net/projects/pynfo/ Thanks, but as I forgot to mention, I can't get the twisted dependencies because of some internet probs. However I found a search box on the Python Cookbook website and found a primitive IRC client... of which I have some problems (in another post). Thanks again.. when I can get twisted working I'll rewrite my IRC client. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Getting rid of the newline in file
Hi. I'm using f = file(foo, 'w') fileContents = f.readlines() print fileContents[0] + Hi! and I get: Foo Hi! How can I get rid of that new line? fileContents[1] has Bar. I wrote the file using Joe (a *nix test editor) and for the new line I pressed Enter to add Bar. This is a pain as I don't want the newline. Thanks, Joe (No coincidence between my fav. text editor and my name!) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
And also, is Python capable of writing an OS? Actually, yes. Google for Python OS and look for Unununium (or something like that. I can never remember). It has no kernel and to booting process may not exactly be in Python... but they say it's an OS written in Python and that it boots to the python interpreter. Just a warning: it's no where near Mac OS (x), Windows (x) and Linux 2.x with a distro that you may be familiar with. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Download an image of a site?
Kent Johnson wrote: I don't think the object returned from urllib2.urlopen() has save() and get() methods. According to the docs urlopen() returns a file-like object with two additional methods: * geturl() -- return the URL of the resource retrieved * info() -- return the meta-information of the page, as a dictionary-like object So you should treat data.f like an open file - use read() to get the contents into a variable. Then open a real (disk) file for writing and write it out. This section of the Python tutorial has a quick intro: http://docs.python.org/tut/node9.html#SECTION00920 Kent Thanks. I will check this out and let you know if I can get it to work. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Download an image of a site?
Hi, I'm a Garfield fan and I thought that I'd make a program that would enable me to read the online comics without opening firefox and typing the url and waiting for all the other junk to load. Here's my code: # import modules import time import urllib2 class data: # Define time and date todays_date = time.localtime(time.time()) dayNum = time.strftime(%d, todays_date) monthNum = time.strftime(%m, todays_date) yearNum = time.strftime(%y, todays_date) yearNumFull = time.strftime(%Y, todays_date) # Define url and it's components stripName =http://images.ucomics.com/comics/ga/%s/ga; % (yearNumFull) c_strip = %s%s%s%s.gif % (stripName, yearNum, monthNum, dayNum) f = # Other info c_strip_download = Downloading Today's Garfield... # Errors urllib2_URLError = Temporary failure in name resolution. This means that you may not be online or the site is down. You may want to try again later. # Enough defining lets get our hands dirty. try: data.f = urllib2.urlopen(data.c_strip) except urllib2.URLError: print urllib2_URLError data.f.save(%s%s%s.gif % (data.yearNum, data.monthNum, data.dayNum)) data.f.get() I would like to know how to save the image to the computer's hard drive. Is it something like f.save(%s%s%s.gif % (yearNum, monthNum, dayNum)) ? thanks, Joseph ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Download an image of a site?
ZIYAD A. M. AL-BATLY wrote: Since you're running some kind of Unix (maybe Linux or FreeBSD), all these command are available for you. By commands I mean: cron, wget, and date. Wow. That's a good idea.. however this is a gift for someone who wants me to make a program to do it ( prefer python) and they use Windows XP (spit) (no offense, that's just my opinion. For me this'll be perfect (till the program works, then I'll see wich is faster). Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Download an image of a site?
ZIYAD A. M. AL-BATLY wrote: Since you're running some kind of Unix (maybe Linux or FreeBSD), all these command are available for you. By commands I mean: cron, wget, and date. Wow. That's a good idea.. however this is a gift for someone who wants me to make a program to do it ( prefer python) and they use Windows XP For me this'll be perfect (till the program works, then I'll see wich is faster). Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Game Engine HowTos?
Byron Wrote: I believe this is what you are looking for: http://www.pygame.org/ Byron --- Pygame? Well I'll take a look... do they have documentation for Game Engine writing? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Game Engine HowTos?
Are there any Game engine tutorials or howto's for Python? Because I googled and can't find any? I'm considering making my own game engine in Python with some C/C++ as well. Or does anyone know of a good Game Engine writing tutorial in another language? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need directions toward programming...
Hi, I sympathize (is that right?) I live in guatemala and the education system here sucks (luckily I'm homeschooled). I picked up Python after a year with Quick BASIC and 5 months later made my own GUI (Graphical User Interface if you don't know already...) program. First off you'll need the python interpreter for your OS (Windows, Linux, Mac OS) from http://www.python.org/download/ then Download these ebooks: A Byte of Python and Learning to Program (sorry I don't know the URL but if you seach google (within qutotes [eg: A Byte of Python]) you'll find them quickly. Then complete Learning to Program First and A Byte of Python second. let's see... I had money so I bought some O'reilly books, although you can find them illegally on the internet. Any help for more good free ebooks for beginners from you people out there? ;-) Hope this helps. The process helped me. Joseph ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IP Address from Python module?
Danny Yoo wrote: Hi Joe, That actually sounds right in a sense. Any internet address with '192.168.x.x' is a "local" IP address, and is commonly allocated to folks on an internal network. For the really dull details about this, see RFC 1918 on "Private Address Space": http://www.faqs.org/rfcs/rfc1918.html So anything with 192.168.x.x is a private, internal address. In the context of the Internet, it's sorta useless, since it's not an address that one can use to connect to an external machine outside of the local area network. In fact, Brian Hammon's comment in: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 does mention that if you're behind a router, then the router itself sets up a small private network, which may explain why you may be seeing '192.168.x.x' as an address. The second comment on the cookbook page shows an alternative technique that should be more robust: use http://checkip.dyndns.org. My internet IP should be IPv6 and I don't think it changes... Are you sure about that? IPv6 has not been widely deployed yet; most folks still connect to the internet through the IPv4 protocol. On the off-chance that you ARE on IPv6, see the getaddrinfo() function, which should accomodate: http://www.python.org/doc/lib/module-socket.html#l2h-2592 For example: ## import socket socket.getaddrinfo('hkn.eecs.berkeley.edu', 80) [(2, 1, 6, '', ('128.32.47.228', 80)), (2, 2, 17, '', ('128.32.47.228', 80))] ## Good luck to you! Thank you. And thank you for the links. Well I remember something on a game I played and it had a IPv6 address (refering to my computer while o nthe internet).. of course I bought my computer parts in October 2004 so there could be a good chance that I do not have IPv6... either way, thanks. :-) Oh and I don't have a router... just a good old-fashioned CAT5 hub. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] XMMS song search
Hi. I have 7.8 GB of music (1808 songs) and I use XMMS to play them. However I can't find some songs. Apparently there is no song search feature in XMMS (something I plan to add whenever I learn C or can incorporate Python into C.. unless someone else has already done this) so I have a hard time finding a song (I have to open kwrite open the playlist and search for a song number or name). I thought I'd write a python program to scan the playlist file for a keyword. I tried: songsearch = raw_input(Enter song name: ) f = file(/home/joe/.xmms/xmms.pls) f.find(songsearch) but got an error: AttributeError: 'file' object has no attribute 'find' what can I do to display several songs that have 'a' in the name? What can I do to search the playlist in the first place? I wouldn't mind some links to tutorials that can show me how to do this. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 18, Issue 37
Hi. I want the program to say You're stupid! When a player fails to guess in 10 tries. But, it's not working.. Very simple fix for bug: elif (guess number): print Higher...\n elif (tires 10): print You're stupid! else: print Error! guess = int(raw_input(Take a guess: )) tries += 1 first off you tries is misspelled (someone probably already caught that). Second you have elif guess ... and then elif tries That's your problem. You need: if tries 10: print You're stupid. instead of elif tries 10 elif is used only when refering to the original if (in this case guess). So you need a new if statement. Hope this helps. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guess my number?
Hi. I want the program to say You're stupid! When a player fails to guess in 10 tries. But, it's not working.. Very simple fix for bug: elif (guess number): print Higher...\n elif (tires 10): print You're stupid! else: print Error! guess = int(raw_input(Take a guess: )) tries += 1 first off you tries is misspelled (someone probably already caught that). Second you have elif guess ... and then elif tries That's your problem. You need: if tries 10: print You're stupid. instead of elif tries 10 elif is used only when refering to the original if (in this case guess). So you need a new if statement. Hope this helps. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IP Address from Python module?
Danny Yoo wrote: On Fri, 5 Aug 2005, Joseph Quigley wrote: Is it possible to get my internet and/or network IP address from Python? Is there any other way to get it? Hi Joe, I think you're looking for socket.gethostbyname(). http://www.python.org/doc/lib/module-socket.html#l2h-2594 Here's an example using the socket.gethostbyname() function: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335890 Oh.. btw I don't think that will work on the internet. Cause a friend of mine has the 192.168.0.2 IP. My internet IP should be IPv6 and I don't think it changes... I'm also looking for my IP address that websites can block. But still I've found a use for the current tutorials, Thanks, JQ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IP Address from Python module?
Thanks.. I hoped python had something like that!!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] IP Address from Python module?
Is it possible to get my internet and/or network IP address from Python? Is there any other way to get it? Oh. If you're wondering what I mean by Internet and/or network IP I'm talking about the 4 sequence IP (IPv4) (used primarily in small networks) and the 6 sequence IP (IPv6) found on the internet. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] More Q's on Socket Programming
Hi, I changed my mind. After I got interested in socket programming I decided to make a bot. But then I got an idea to make a chatting program. It worked nicely on our home network but it had a small problem you can't type anything and send it to the person you are chatting with untill they reply!! I also have one computer as the server and another as the client can I have a dedicated server program that handles two clients instead of having a direct connect? If you have any examples please send them too me.. it would be very much appreciated!! Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Socket Programming
Hi Dan, Danny Yoo wrote: ## clientsocket.recv() ## should work better. Ok well I tried your examples but they didn't work. I still get: TypeError: recv() takes at least 1 argument (0 given) How can I fix this? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re; Socket Programming
Hi Kent, I have Python in a nutshell but I haven't read much. Thanks for tellling me. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Socket Programming
Hi Johan, Johan Geldenhuys wrote: I have more advanced examples if you want them, but start here and look at the socket lib and you can start using select if you want to wait for stuff from the server or client. Johan I'd love to see your examples. Could you send them directly to me as an attachment? I've got a question... how can I add more clients? I'm trying to make a type of bot. Thanks for your help. Your example worked perfectly! Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Socket Programming
Hi, Ok. But what if I wanted to send a 1 mb message? Could I leave .recv(1) in and send 'Hi!' as well or would I have to change it? Thanks, JQ Adam Bark wrote: You have to put in how many bytes of data you want to recieve in clientsocket.recv() eg. clientsocket.recv(1024) for 1kB. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Socket Programming
I've got a little problem with my socket program(s): #Client import socket #create an INET, STREAMing socket s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) s.connect((localhost, 2000)) s.send('hello!'[totalsent:]) #Server import socket #create an INET, STREAMing socket serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) #bind the socket to a public host, # and a well-known port serversocket.bind((socket.gethostname(), 2000)) #become a server socket serversocket.listen(5) while 1: #accept connections from outside clientsocket, address = serversocket.accept() serversocket.recv() I have no idea how to get the server to receive and print a message or for the client to send the message. Does anyone know of some good python networking tutorials designed for newbies? (Not ones on www.awaretek.com. They seem to expect you to know some things that I don't even know about.) Thanks, Joe Q. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I add an argument too...
optparse.. Can I download that as a module or do I have to download epython? Thanks, JQ Hugo González Monteverde wrote: I use optparse wich can take some getting used to in the beginnning, but it help you easily create very powerful command line options. I is shipped with th epython distro. As soon as I get an example I wrote, I will post it to the list... Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How do I add an argument too...
How do I add an argument too my program (with sys.argv) so that at a console I can type: python foo.py -info or python foo.py open /home/joe/foo.txt Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter Q's
Hi, what's the **kw stand for, used for? What does it mean? Some comments --- You create a Frame, but you never use it. You've put a whole lot of code in a class, but it's not in a class method. This is kinda missing the point of using classes in the first place (and it just flat-out wouldn't work in the majority of OO languages). Here's what I would do: class Main(Frame): def __init__(self, master=None, **kw): Frame.__init__(self, master, **kw) showquote = Label(self, text=random.choice(quotes.quote)) showquote.pack() # etc if __name__ == '__main__': root = Tk() main = Main(root) main.pack(fill=BOTH, expand=True) root.mainloop() ### Do you see what I am doing there, and why it is different from your approach? Uh, not really, no. I'm very new to GUI. So you're saying that If I make the class actually do something (I edited and example in: An into to Tkinter, Fredrik Lundh). Once you've got a label, you can change its text attribute by using its .config() method. So, you could do something like this: # ... showquote = Label(self, text=random.choice(quotes.quote)) showquote.pack() def changeQuote(): currQuote = showquote.cget('config') # Get the current quote newQuote = random.choice(quotes.quote) while newQuote == currQuote: # Make sure the new quote differs newQuote = random.choice(quotes.quote) showquote.config(text=newQuote) Button(self, text='Show another quote', command=changeQuote).pack() Aaag. I'm confused... I just tried you changeQuote example with out the above stuff... didn't work. My error message: AttributeError: 'NoneType' object has no attribute 'config' so I edited it a little, still didn't work (same error). I tried the class Main(Frame) and didn't get it to work either. Do you think you could make it a little bit simpler? If you can't that's ok, I'll try to study it more. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter Q's
Hi first off, here's my code: # -*- coding: utf-8 -*- from Tkinter import * import random import time import about import quotes def closeprog(): raise SystemExit class main: root = Tk() frame = Frame() root.title("Quoter %s" % (about.ver)) root.minsize(300, 50) showquote = Label(root, text=random.choice(quotes.quote)) showquote.pack() exit = Button(root, text="Exit", command=closeprog) exit.pack(side=LEFT) aboutprg = Button(root, text="About", command=about.main) aboutprg.pack(side=LEFT) totalq = Label(root, text=quotes.qts) totalq.pack(side=BOTTOM) root.mainloop() (I'd appreciate some suggestions, or notifications on how bad something is) I have a small problem: I don't know how to make a button that would redisplay another quote in the same window, ie I need a button that says: Show Another Quote. (Actually I don't know how to make it show another quote even in a new window!!). I got the interface from Catfood Fortune Cookie. Here's a tid-bit of the quotes module: # Brian Kernighan bk1 = """Controlling complexity is the essence of computer programming. -- Brian Kernighan""" yadayada = """Foo/bar""" quote = [bk1, yadayada] Thanks, Joe -- Unix Love, Linux Pride ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Jimage reader. How to find the pixels?
I've been looking a lot for a mod that will automatically find the pixels in an image but I can't find one. Do you know of one? imageop and imghdr don't have anything like that. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Jimage reader. How to find the pixels?
I have finally made my very first GUI program!! It needs some work before I would ever consider putting it on sourceforge (ha ha ha). I have a problem though. I can't find an image lib that will detect the picture's height and width automatically. I can use wave to detect mono or stereo but that's another story. Oh, one more thing, how can I make it so that I can type: python jimagereader.py /home/joe/pic.jpeg instead of the prompt within the program: Image name: Here's my code: from livewires import games image_nm = raw_input(Image name: ) SCREEN_WIDTH = int(raw_input(Image height: )) SCREEN_HEIGHT = int(raw_input(Image width: )) the_screen = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) bckgrnd_image = games.load_image(image_nm, transparent = False) the_screen.set_background(bckgrnd_image) the_screen.mainloop() Thanks. Joe -- Unix Love, Linux Pride -BEGIN GEEK CODE BLOCK- Version 3.12 GU d- s-:- a C UL P L++ !E W+ N+ !o !K w !O !M V- PS-- !PE Y+ PGP- t- !5 !X !R !tv b+++ DI+ !D G e- h! !r y? k F --END GEEK CODE BLOCK-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Py2exe Problem
Traceback (most recent call last): File NovusExtension.pyw, line 8, in ? File Pmw\__init__.pyc, line 28, in ? WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: this: WindowsError: [Errno 3] El sistema no puede hallar la ruta especificada: is spanish for: WindowsErrorL [Errno 3] The system can not find the file/directory specified. There are better ways of saying that.. but that's simple enough, is it? Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Looking for HOWTO's
Hi, I could use some howto's or tutorials in python, on how to build an image reader (like: Kview, or Kodak's Easy Share Software). I searched Google but can't find anything (I also have pay-by-the-minute dial up so I don't surf much) I know it's reinventing the wheel, but, I just want to learn how to make one may come in handy later on. Thanks, Joe PS I wouldn't mind /any/ Python HOWTO or tutorial ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python won't play .wav file
Hi, I'm replying to you both... At 03:16 PM 5/24/2005, you wrote: Strangely... I do not believe the wave module is meant to actually _play_ a wav file. It looks to me like it is only intended to read and parse the file for meta information. You could try passing the name of the file to another program via os.system, or you could use pygame. Ok drat. I was hoping that it would play the files. -- Lee Harr wrote: If you are on windows try the winsound module. And if I'm on Linux or programing for Mac? Thanks guys, JQ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] __init__.py
I've seen many (python) plugins (some located in site-packages [windows here]) with the name __init__.py. What's their use? class foo: def __init__: print this starts first def foo1(): print this comes later. Init initializes the chain of functions in this class Now, i've never used a program (i can't seem to grasp all the self, and other things in OOP yet) with __init__ but I know what __init__ does in a class, not as a file name. I'm asking this out of curiosity, not for help. JQ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__.py
__init__.py will be executed when a package is imported. Oh. So it will (for instance) compile .py to .pyc after the installation is finished. Nice. Thanks, JQ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding word in file
What are you trying? You could simply read through the file line by line using the string search methods. Store the previous 2 lines then when found print the previous two lines, the current line and then read and print the next two lines. There are more sophisticated methods but that should do... How? Does your tutorial cover that (i don't remember it doing so)? You need to catch the error not state it. OK try: f = file() except IOError: print 'file not' Did that, IO Error handling works great now. Thanks JQ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding word in file
I'm making a program that opens a file and tries to find the word you specify. I can't get it to find the word! I also would like to know how I can get it to print 2 lines above and 2 lines below the line with the word specified. One more thing, the try: IOError won't work... I type the name of a nonexistent file and the except won't kick in and print my error message! Not to mention the program is killed. How can i fix that? Thanks, JQ Full Code: while True: file_name = raw_input(Enter the full file name: ) f = file(file_name, 'r') try: IOError except: print File not found. Directories are not supported while True: line = f.readline() if len(line) == 0: break find_word = raw_input(What word do you want to find (quit() to quit)?\n ) if find_word in file_name: print f.readline(find_word) elif find_word == quit(): break print line, f.close() close = raw_input(\n\nQuit program? (Y/N) ) if ((close == Y) or (y == close)): break else: print ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] YATENJoe
If you intend to make a text editor (something which allows the user to browse through the text and manipulate it at will) using just raw_input and print, I think you've set yourself an impossible task. For a console editor you should probably look at curses (http://www.amk.ca/python/howto/curses/) - which don't work on Windows, so you'll probably need this: http://adamv.com/dev/python/curses/ (but according to the site it's incomplete). Ok. lines = [] while True: lines.append(raw_input('')) (But that offers no way to e.g. save and continue.) Ok again. Text editors are IMO not applications suitable for learning vanilla Python, or OOP for that matter. Text editors are used as example applications in the RAD IDE world (VB, Delphi and such) because in those environments a text editor is literally three clicks away (click on memo component, click on form, click on run). Vanilla Python has no GUI, so no memo component - hence my recommendation for Tkinter or wxPython. PythonCard and Boa provide an experience somewhat similar to commercial RAD IDE's if that's what you're looking for. I got my idea from looking at Nano, Vi, Joe and a few other UNIX text editors. Nano and Joe are console programs. That's why I thought I would try a console ed. in Python. Having one function for each line is a bad idea whether you code it by hand or automatically Ah. A function implements certain behavior. Having the same behavior (raw_input) implemented separately for each line is an extremely wasteful way of programming. Is there a way of telling Python to make a new line after you press Enter (return)? I would suggest that you learn a bit more about Python's facilities before embarking on an ambitious project :) - you won't get very far without knowing how to use lists and dictionaries. So that's one of the ways Dicts, and lists are used for? I never could fully grasp their use. Thanks, JQ --- Proud to be a true hacker (You may have a bad impression of the word hacker. Do some homework, go to: http://catb.org/~esr/faqs/hacker-howto.html and become enlightened) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] YATENJoe
YATENJoe (Yet Another Text Editor, Named Joe) First off, If this isn't the right place to ask, tell me so. That way I won't make this mistake again :-) I want to make a text editor. I know that there are hundreds out there, but practice makes perfect, and I need the practice. My problem is that I have no idea how to make one. I've tried a little already by defining line functions: def line1(): l1 = raw_input() def line2(): l2 = raw_input() line1() line2() Of course, this only allows for 2 lines. What's the trick to an infinite number of lines? Event driven programming is a must, obviously. How can I use 'Ctrl' + 'Q' to quit while still being able to type: Press 'Ctrl' + 'Q' to quit YATENJoe? I'm still a newbie to python (actually OOP programming in general!) so I can't have a lot of complicated stuff thrown in my face. I'd like it to not be platform specific, but if it has to be OS bound to be simple, then that's fine. I thought of a function that would define a function for me. Is this possible? If it is how would I do it? If it possible, here's my idea: def makefunc(): # This is where it defines a function. If line1 = full then # make a new line adding 1 integer do separate it from the first. def l1(): l1 = raw_input() line1 = full l1() makefunc() One other thing, is there a way to call a function that is inside a function? 'Cause makefunc().l1() doesn't work. Thanks in advance, JQ PS: FYI I use Windows XP Pro and Linux PPS. FYI 2: I'm still a newbie to Linux too :-) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No Need To Press Enter
Darn! I get this error: Traceback (most recent call last): File C:/Python24/saved/tmp1.py, line 1, in -toplevel- if event.key == K_q: NameError: name 'event' is not defined Do I need to import something? @ Denise: I would like to the full code if you don't mind. Date: Wed, 4 May 2005 11:33:53 -0700 From: D. Hartley [EMAIL PROTECTED] Subject: [Tutor] Fwd: No Need to press Enter (Joseph Quigley) To: Python tutor tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=ISO-8859-1 I don't know if this is what you're looking for, but in my game I set Running = 1, and then had: if event.key == K_q: running = 0 ... which exits the game as soon as you hit q (i.e., no hitting enter). I can send the full code if it would be more helpful, if this is what you're talking about? ~Denise ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] No Need to press Enter (Joseph Quigley)
What is the secret to have the user press the Q key, and the program exits without pressing the Enter key? Or the Control and Q keys to exit? For the Macintosh, would the same command/s for Control Q keys be the same as the Apple Q key? Thanks, JQ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Psyco (Joseph Quigley)
For those who use Psyco: Is it any good? I'm searching for instructions on how to use it, should I stop? For those who don't know about Psyco: It is supposed to be a Python Compiler. The programs are said to run faster than normal Python and they almost run as fast as C. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] cPickle (Joseph Q.)
Hi all, How could I have the user name his file? I learned that I type file_name = foo.bar How could I make it that the use could name it hello.hi? Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] CLS? (Joseph Quigley)
In QBASIC there was the command CLS this wiped the screen and started printing letters to the screen at the top of the console window. Is there any such command in Python? Would a Python cook book have this (I have pay-by-the-minute dial-up Internet so I can't go online for long)? Thanks in advance, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Installation Routines (Joseph Quigley) (Jay Loden)
Interesting. So several distros use rpms? I though only red hat used 'em. Rpm does in fact have dependency resolution, and rpm-based distributions use a package manager that can download the dependencies and install them for you - urpmi on mandrake, yum or apt4rpm on Fedora and Redhat, Yast on Suse I've used all of these, they are all rpm based, and they all install dependencies. If you use the raw rpm command, even that will tell you missing dependecy foo. That being said, apt-get on debian is still my favorite (for sheer number of available packages), but urpmi on mandrake or Yast on Suse are quite excellent. -Jay On Wednesday 20 April 2005 04:17 pm, Max Noel wrote: emerge and apt-get come to mind. rpm is inferior (no dependency resolution) but still does a good job, and I hear autopackage isn't bad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Error Raising (Joseph Q.)
(here I go again?) Where could I find a nice long list of the errors I can raise? (I mean like EOF errors when some one doesn't fill in their name when they're supposed to). Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Error Raising
Ahh. I really like the ability to make my own exceptions. This info will help alot. Thanks, Joe PS. Would the Tutorial included with IDLE be the same as the site's docs? The standard (built-in) exceptions are documented here: http://docs.python.org/lib/module-exceptions.html If you don't find any that suit you, defining your own is as easy as class MyException(Exception): pass try: raise MyException except MyException: ... Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installation Routines (Joseph Quigley)
Its not hard, but its not easy either to do it right. And given the profusion of installers already available ranging from free to expensive there really is little point in writing something that probably won't be as good as the already available alternative. Remember user expectation, if you write an installer you should also provide an uninstaller, and link it to the Control Panel Add/Remove applet. Its no coincidence that python uses a commercial (Wise) installer for the Windows distro... This isn't a waste of your or my time is it? No, its a valid question even if the answer is that its probably a bad idea! Alan G. My point is for practice and knowledge. Sure, I have Setup 2 Go (the paid version) and Install Creator (not paid) Then again, how many free installers are there for linux? I must get a book on Windows before I make a nice installer. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Installation Routines (Joseph Quigley)
Here I go, hogging the Tutor list again :) I have a friend who recently got a hush-hush contract. He told me that it was for writing an installation program for Windows and that he considered python and Tkinter as an option. I know there are installers written in python for Linux. I suppose they are easier to write, than one for Windows? Now, I'm still new, and can't do GUI yet, but I was wondering how hard would it be to write a simple installer for windows? None of that fancy INI and registry crapp, just a very simple file copier to, oh lets say, My Documents? This isn't a waste of your or my time is it? Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] More Function Questions (Joseph Q.)
Hi all, Another function question. def bar(x, y): return x + y bar(4, 5) So I can put anything I want in there. What good is a function like that? Of course I know about. def foo(): print Hello all you who subscribe to the Python Tutor mailing list! So what do you use the def bar(x, y): return x + y bar(4, 5) functions for? (I just need a simple example) Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Craps, eternal loop (Joseph Q.)
I get an eternal loop on this game that I don't want and can't figure out how to fix. BTW any of you know the rules to craps? I don't remember them all so this game may be different than the casino version. Here's my code: import random # generate random numbers 1 - 6 loop = True def play_again(): play_again = raw_input(Play again? (Y/N)\n ) if play_again == (Y) or (y) or (Yes) or (yes) or (YES): crapps() else: loop = False print \nCome play again. def roll(): raw_input(\nPress the 'Enter' key (Return) to roll.) def crapps(): while loop: die1 = random.randrange(6) + 1 die2 = random.randrange(6) + 1 die1_2 = random.randrange(6) + 1 die2_2 = random.randrange(6) + 1 total_cash = 100 title_ = The fun game of craps. print title_.title() print You have %d dollars on hand. % total_cash print Now you will wager 10 dollars for the game. total = die1 + die2 total_2 = die1_2 + die2_2 roll() print \nYou rolled a, die1, and a, die2, for a total of, total raw_input(\nPress the 'Enter' key (Return) to let your opponent roll) print \nYour opponent rolled a, die1_2, and a, die2_2, for a total of, total_2 if total total_2: total_cash = total_cash + 10 print \nYou won! You now have %d dollars on hand. % total_cash play_again() else: total_cash = total_cash - 10 print You lost. Too bad. Better luck next time. if total_cash 0: print Get out of this casino and work! You're in debt! elif total_cash == 0: print Better stop now before you get into debt. play_again() crapps() I also can't get the counter to save the added or removed money. every time I play again, I always have $100 Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)
if letter == 'O': print letter + 'u' + suffix elif 'Q': print letter + 'u' + suffic else: print letter + suffix Do you see? The == binds more tightly than the or. And, in python, 'Q' is considered True for the purposes of tests. So this is what happens: prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: ... if letter == ('O') or ('Q'): ... print letter + 'u' + suffix ... else: ... print letter + suffix ... Juack Kuack Luack Muack Nuack Ouack Puack Quack What you can do instead is this: for letter in prefixes: if letter in ['O', 'Q']: print letter + 'u' + suffix else: print letter + suffix Oh, ok. Sorry, my bad :) So there is a special use for ==. I must look into this. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] Craps, eternal loop (Joseph Q.)
Thanks a lot. Now I need to find the rules. BTW. What about the counter? If I win I get 110 dollars. On the next round I start out with 100 dollars again, when I should have 110! Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tk code problem (Joseph Q.)
It works if you run from the command line instead of inside IDLE. I thought IDLE was supposed to be able to run Tkinter programs since Python 2.3 but it doesn't seem to work? snip AFAIK IDLE runs on Linux. There are many other possibilities listed here: http://www.python.org/moin/IntegratedDevelopmentEnvironments eric is popular... Kent Thanks for the link and tips. Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining a function (Joseph Q.)
Oh, now I understand def silly(a_name_I_picked_at_random): # well, not quite ... print a_name_I_picked_at_random # at random ;-) ... silly(42) 42 The name a_name_I_picked_at_random is like a placeholder inside the function for whatever input we gave to the function. And *that* can be any object So you can have silly say something serious like: def silly(a_name_I_picked_at_random): # well, not quite print a_name_I_picked_at_random # at random ;-) def silly(this_is_serious): print 'this is serious But I get an error! Traceback (most recent call last): File C:\Python24\saved\tmp1.py, line 7, in -toplevel- silly(this_is_serious) NameError: name 'this_is_serious' is not defined But you can have silly say something silly and also say something serious right? If so how? args has confused me, but I'm slowly picking it up. Thanks Brian, Jeff, Liam for your help. Joseph ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cell Bio Newbie Here (Gary L) (Joseph Q.)
At 02:02 PM 4/11/2005, you wrote: Send Tutor mailing list submissions to tutor@python.org Hey all, Sorry for the bother, thanks for the help #first of all, why does this have to be here? password=foobar count=3 current_count=0 while password !=unicorn: if current_countcount: password=raw_input(Password:) current_count=current_count+1 else: print That must have been complicated print Welcome in Just wondering... would breaking the loop at 3 counts work at all? Or would it screw it up? Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)
Well you did come up with a way that would work sort of and you seem to be ont eh right track. I would make 1 small change if using your approach. prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: if letter == 'O' or letter == 'Q': print letter + 'u' + suffix else: print letter + suffix However there are other methods to solve this problem but following the logic you are using this works. Jeff I also learned an easier way to do that: prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: if letter == ('O') or ('Q'): print letter + 'u' + suffix else: print letter + suffix Joseph Q. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tk code problem (Joseph Q.)
Hi, It seems that whenever I click the QUIT button the TK windows freezes, then I have to CTRL-ALT-DEL to be able to shut it down. Here's the code (its not mine though): from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text=QUIT, fg=red, command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text=Hello, command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print hi there, everyone! root = Tk() app = App(root) root.mainloop() It's probably the command=frame.quit Is there another command to close the Tk program? (like raise SystemExit and sys.exit() for the text based programs) Also could I do something like root and tk = Tk()? Thanks, Joseph. P.S I'm currently looking for an dedicated python IDE (or IDLE, i never can tell the difference between the two) for Linux. I know about emacs and vi (or vim) (but they're not dedicated). I was wondering if any of you know of any. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] import.... (Joseph Q.)
I don't think I have said it already, but I'll say it again just incase :-), I'm new to python. I started Feb. this year. import is handy. But my questions are: is there a type of unimport or something to unload a module? Foo: What's it good for? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Help with classes (Joseph Q.)
class Message: def init(self, p = 'Hello world'): self.text = p def sayIt(self): print self.text m = Message() m.init() m.sayIt() m.init('Hiya fred!') m.sayIt() Well this OOP stuff is realy hard for me as I have never even programmed it took me a while just to understand defs. That's OK, OOP is quite a strange concept for many folks. Its actually easier to learn as a beginner than for folks who have been programming without OOP for a long time! determined to learn how to do it. My biggest problem is with __init__ I still don't understand how to use it. init is simply where you initialise the data attributes of your class. It could be defined as a normal method and you call it explicitly: class Message: def init(self, txt = 'Hello world'): self.text = txt def sayIt(self): print self.text And every time you create a message object you explicitly call it: m = Message() m.init('Hiya fred!') m.sayIt() I was having problems with the __init__ too. class Message: def init(self, txt = 'Hello world'): self.text = txt def sayIt(self): print self.text And every time you create a message object you explicitly call it: m = Message() m.init() m.sayIt() m.init(Hello World is so overdone. It hard to break tradition though :-) m.sayIt() Why did you put 'Hiya fred!' in place of having m.init print Hello World? Now what are dictionaries and the __name__ really used for? A byte of python never got that through my thick skull. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Py2exe (Joseph Q.)
Maybe I shouldn't be posting this... I downloaded py2exe and can't get it to make exe's of my python files. There are a list of instructions: # A very simple setup script to create 2 executables. # # hello.py is a simple hello, world type program, which alse allows # to explore the environment in which the script runs. # # test_wx.py is a simple wxPython program, it will be converted into a # console-less program. # # If you don't have wxPython installed, you should comment out the # windows = [test_wx.py] # line below. # # # Run the build process by entering 'setup.py py2exe' or # 'python setup.py py2exe' in a console prompt. # # If everything works well, you should find a subdirectory named 'dist' # containing some files, among them hello.exe and test_wx.exe. from distutils.core import setup import py2exe setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = 0.5.0, description = py2exe sample script, name = py2exe samples, # targets to build # windows = [test_wx.py], console = [hello.py], ) What does it mean by the 'console prompt'? I tried Command Prompt (Windows XP) but I get errors when I type 'setup.py py2exe' or 'python setup.py py2exe'. I also don't get anything when I run the setup.py in IDLE (or the Python command line). In fact I get an error: Traceback (most recent call last): File C:\Python24\Lib\site-packages\py2exe\samples\simple\setup.py, line 22, in ? import py2exe ImportError: No module named py2exe If you have used or are using py2exe, please tell me what I'm doing wrong! Thanks, Joseph Q. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Py2exe (Joseph Q.)
Joseph Q. (Uspantan, Guatemala) Using Python 2.4 I downloaded py2exe and can't get it to make exe's of my python files. There are a list of instructions: # A very simple setup script to create 2 executables. # # hello.py is a simple hello, world type program, which alse allows # to explore the environment in which the script runs. # # test_wx.py is a simple wxPython program, it will be converted into a # console-less program. # # If you don't have wxPython installed, you should comment out the # windows = [test_wx.py] # line below. # # # Run the build process by entering 'setup.py py2exe' or # 'python setup.py py2exe' in a console prompt. # # If everything works well, you should find a subdirectory named 'dist' # containing some files, among them hello.exe and test_wx.exe. from distutils.core import setup import py2exe setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = 0.5.0, description = py2exe sample script, name = py2exe samples, # targets to build # windows = [test_wx.py], console = [hello.py], ) What does it mean by the 'console prompt'? I tried Command Prompt (Windows XP) but I get errors when I type 'setup.py py2exe' or 'python setup.py py2exe'. I also don't get anything when I run the setup.py in IDLE (or the Python command line). In fact I get an error: Traceback (most recent call last): File C:\Python24\Lib\site-packages\py2exe\samples\simple\setup.py, line 22, in ? import py2exe ImportError: No module named py2exe If you have used or are using py2exe, please tell me what I'm doing wrong! Thanks, Joseph Q. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor