Re: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job
On Thu, 26 Apr 2007 00:33:19 GMT, "Bill Habr" <[EMAIL PROTECTED]> wrote: > ><[EMAIL PROTECTED]> wrote in message >news:[EMAIL PROTECTED] >> Cal Tech is the ELITE of ELITE in physics. >> >> If Feynman were alive, he would point his finger straight at the 911 >> criminal operators, the yank bastards themselves ... >> >> http://www.911blogger.com/node/8101 >> >> No self-respecting scientist should keep his mouth shut. Its a >> fundamental challenge to the method of science, a detective work most >> demanding of INTELLECTUAL HONESTY. >> > >Isn't this the guy who has more conspiracy theories than Carter has pills? > >Whitewater, Vince Foster, moon landing hoax one week - we found a UFO on the >moon the >next, Oklahoma City bombing, a new conspiracy every day ad nauseum? > Maybe the thread title is wrong. Should it perhaps read, "Video Professor took a physic then spewed out some really stinky stuff." -- http://mail.python.org/mailman/listinfo/python-list
compatible image type
hi in my application a file selection by user returns a pathname string like F:/images/png/my.png or F:/docs/text/somedoc.txt etc. I can get the extension using extn=string.split(os.path.basename(pathname),'.' )[1] then later on i want to create a Photoimage using ImageTk.PhotoImage(file=pathname) and display it on a canvas. the extn can be anything ..even zip or bat ,doc whatever depending on user selection...I want to put someway to raise an error message to the user if he selects a file with extension not of a compatible image type for PhotoImage.How should i do this? should i check 'extn' to a list of compatible image type extensions(something like [''jpg','jpeg','png','gif'...] ) or is there a better way? gordon -- http://mail.python.org/mailman/listinfo/python-list
origin of error message
hi i was trying to create an image using user selection of a file in tix fileselection box ..and i check for exception like below ... from string import split from os.path import basename ... #this is done inside __init__method self.imgsel=FileSelectBox(self.imgSelectFrame) ... def button1Click(self): starttime=datetime.now() self.okButton.configure(state=DISABLED) #will clear canvas self.canvorig.delete(ALL) self.canvresult.delete(ALL) self.resultdisplay.delete(ALL) #image file selection by tix widget self.cursel=self.imgsel.selection.cget("value") print "self.cursel:",self.cursel self.imgsel.selection.selection_clear() #here i want to check if anything is selected by user if self.cursel: ext=split(basename(self.cursel),'.')[1] print "image extn:",ext try: self.selimg=ImageTk.PhotoImage(file=self.cursel) except Exception,inst: print "xceptn::",inst.message self.showresult(inst.message,"red") else: self.selimgtag=self.canvorig.create_image(70,100,image=self.selimg) self.canvorig.update_idletasks() . # some other tasks done . else: #no file was selected by user print "self.cursel=",self.cursel self.showresult("nothing selected","red") self.okButton.configure(state=NORMAL) endtime=datetime.now() print "total time:", endtime-starttime,"seconds" user is supposed to select an image to be displayed. when i select some file with a non compatible extension (say .zip) i get the following output >>>> self.cursel: F:/docs/python/gui3.zip image extn: zip xceptn:: cannot identify image file total time: 0:00:00.341000 seconds Exception exceptions.AttributeError: "PhotoImage instance has no attribute '_Pho toImage__photo'" in > ignored My belief was that the message 'total time: 0:00:00.341000 seconds ' should have been the last output message .I don't know where the Exception exceptions.AttributeError: etc comes from. Already i am catching the exception when creating PhotoImage .The message 'xceptn:: cannot identify image file' comes from there Can someone help me find how this error msg happens gordon -- http://mail.python.org/mailman/listinfo/python-list
problem with Tix in Python2.5
hi i have been using some Tix widgets in my gui code in Python2.5 and they used to work without any problems.Now all of a sudden i am getting error messages like "couldn't read file "E:/Python25/tcl/tix8.4/ChkList.tcl": no such file or directory ... This probably means that Tix wasn't installed properly." why is this happening?Do i have to reinstall python2.5? or can i reinstall Tix alone to my existing python installation?Can someone help? thanks gordon -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with Tix in Python2.5
On Aug 26, 11:24 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > > assuming that you installed Python 2.5 on E:, it sure looks as if your > Python installation is broken. reinstalling should fix that. > > thanks i couldn't find any binary distribution of tix8.4.So i think i have to reinstall python. i also have numpy and PIL installed.If i reinstall python on top of the current python directory will i lose them? gordon -- http://mail.python.org/mailman/listinfo/python-list
newbie doubt about MVC,tkinter
hi i am trying to write a controller that creates a Tkinter gui,takes userevents from gui and calls another program to do some calculation and finally returns the results to gui to be displayed. I tried to separate these three like MVC pattern however ,being a newbie i have some doubts sample gui class class MyGUI: def __init__(self, parent): self.controller=MyController() self.myParent = parent self.mainframe = Frame(parent,background="grey") self.mainframe.pack(fill=BOTH,expand=YES) ... def button1Click(self): controller.callback(uservalue) def showResult(resultvalue): //display on canvas class MyController: def createGUI(self): root = Tk() root.wm_title("MyGUI") self.myapp = MyGUI(root) root.mainloop() def callback(value): self.userenteredvalue=value def callGUI(self,resultvalue): self.myapp.showResult(resultvalue) if __name__ == "__main__": controller=MyController() controller.createGUI() resultTodisplay=self.userenteredvalue+1000 # or may be call some program to do the calc controller.callGUI(resultTodisplay) Here,root.mainloop() causes the application to go into Tk event loop and the controller will not be able to interact with the gui until i close the window. I was wondering if i can keep the gui window open and at the same time call the gui objects methods from my controller.If anyone can help/ advise please do thanks gordon -- http://mail.python.org/mailman/listinfo/python-list
Tkinter event loop question
is it possible to send a message to the gui instance while the Tk event loop is running?I mean after i create a gui object like root=Tk() mygui=SomeUI(root) and call root.mainloop() can i send message to mygui without quitting the ui or closing the window?i tried some code like mygui.someMethod() but it only gets executed after i close the the ui window.Is there a way to get this message passing while gui is running ? (forgive me ,it is a repeat question..but i am a bit desperate) thanks gordon -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter event loop question
On Aug 27, 10:42 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > so I guess the question here is from where you expect to call that > method, and what you expect Tkinter to do when you call it... thanks for the reply i was planning to write a controller (as in MVC) that will instantiate a gui class and show the ui.the gui will send user input back to the controller which in turn will process it and send a result to the gui to be displayed something like controllermodule.py class Controller: def createGUI(self): root=Tk() self.mygui=uimodule.MyGUI(root) root.mainloop() def sendMessageToUI(self): self.mygui.displayResult(someresultValue) i don't know if this is the right way to do this..when i call sendMessage() it tries to call displayResult() on the gui instance which is already in an event loop.displayResult() gets called only after the event loop is finished(when i close gui window). is there a way to keep the gui window open and have the controller send a message to the gui instance so that i can pass the processed result value to the gui instance? thanks gordon -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter event loop question
On Aug 29, 4:45 am, "Russell E. Owen" <[EMAIL PROTECTED]> wrote: >your Controller object should not create root nor should > it call mainloop to start the event loop. guys thanks for the helpful replies..I rewrote the code as you advised. It creates a controller object and a gui object from main script.However i had to chain some method calls in my code.i am wondering if that can be avoided in some way. this is the sequence 1.user enters some value in the textfield,and clicks OKbutton 2.on OKbuttonclick ,the gui takes userinput value and quits eventloop.It then calls controller and pass the userinputvalue. 3.controller does some calculation(i shd have an external program to do calculation,but for simplicity i just wrote a method inside controller) with the given value,obtains the result and calls gui's updateDisplay(), passing the result value. 4.the gui creates the result as text on a canvas.then the mainloop() is called to resume event loop again user enters some value in the textfield,and clicks OKbutton ... I exit the application by clicking quitButton that calls destroy() on top level window. I tried my application by entering some value on text field and then clicking OKbutton ,the calculated result is displayed on canvas .I do this process say 3 times ..Then i click the Quit button and the window closes. I have put a print statement inside the gui's updateDisplay()method right after the resuming of event loop by parent.mainloop().This print statement gets printed as many times as i had clicked the OK button(here in this case 3 times).Is this due to clearing of the stack ? I feel that it was not a good design ..I would be grateful if someone would tell me how i could improve it..can those chaining of method calls be avoided? this is how i restructured the code moduleA.py --- import moduleB from Tkinter import Tk class MyController(object): def __init__(self): print "controller()" def validateSelection(self,userinputVal): if(userinputVal > 50 or userinputVal==0): userinputVal=50 self.doSomeCalculation(userinputVal) def doSomeCalculation(self,userinputVal): resultvalue=2*userinputVal +10 self.updateResults(resultvalue) def updateResults(self,resultvalue): self.myapp.updateDisplay(resultvalue); if __name__ == "__main__": controller=MyController() root = Tk() root.wm_title("MyUIApp") controller.myapp =moduleB.MyUI(root,controller) root.mainloop() moduleB.py --- from Tkinter import * class MyUI(object): def __init__(self, parent,controller): self.myParent = parent self.mainframe = Frame(parent,background="grey") self.mainframe.pack(fill=BOTH,expand=YES) self.controller=controller added a canvas and OK,QUIT buttons def okBtnClick(self): print "okBtnClicked" self.okButton.configure(state=DISABLED) userinputvalue = self.getUserInputValue() self.myParent.quit() #quits event loop self.controller.validateSelection(userinputvalue) def quitBtnClick(self): print "Quit Btn clicked" self.myParent.destroy() def updateDisplay(self,resultValue): message='result is='+str(resultValue) self.canvresult.delete(ALL) self.canvresult.create_text(1, 40, anchor=W, text=message, width=280) self.okButton.configure(state=NORMAL) self.myParent.mainloop() # resumes event loop print 'in updateDisplay():called mainloop' thanks gordon -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter event loop question
On Aug 29, 10:46 pm, "Russell E. Owen" <[EMAIL PROTECTED]> wrote: you > can safely compute stuff with a background thread and display it from> the > main thread). But cross that bridge later.> > -- Russell thanks Russel gordon -- http://mail.python.org/mailman/listinfo/python-list
ctypes exception in callback handlind
This post concerns the situation where Python code calls C code via ctypes, the C code then calls a callback back into Python code which in turn raises an exception. Currently as I understand things when the callback finishes and control is returning to C land ctypes will catch and print the exception and then return normally back to C. The standard way of doing something meaningful with the exception is to catch it in the callback, set a global flag, somehow encourage the C code to unwind back to the original Python call and there check the flag and re-raise the exception. My current problems involves a non recoverable error being raised in the callback. The intermediate C code is not at all setup to deal with a failure like this and I can't find a way to "somehow encourage the C code to unwind". For extra giggles I can't just hit sys.exit as this stack got invoked as a callback out of a third party python library that needs to do some clean up. All of which leaves me wishing that ctypes would propgate the exception back to the python calling context for me. One approach I can think of that I would like to get some feedback on is the following: Create a new ctypes calling convention that does a setjmp on entry. When using that calling convention if an exception is raised by a call back, catch it and store it somewhere, longjmp back to the setjmp point and re-raise it. I appreciate that this will generally leave the intervening C code in an undefined state and as such would definitely have to be an optional feature. I realize that I could in theory do this myself by wrapping each of the C calls with a wrapper that does the setjmp work, but there are quite a few of them. So any comments or suggestions? G -- http://mail.python.org/mailman/listinfo/python-list
Gedcom and Genealogy
We have many small libraries in JAVA or Ruby that need to be ported to Python. Actually it's so simple a rewrite is possible too. -- http://mail.python.org/mailman/listinfo/python-list
Re: python backup script
In <36d2b7cf-2537-46a6-b984-9fce7ddd3...@googlegroups.com> m...@socialassets.org writes: > > cmd2 = subprocess.Popen(['gzip' '-c'], > > > > shell=False, > > > > stdout=filename > > > > stdin=cmd1.stdout) > Thank you Enrico. I've just tried your script and got this error: > stdin=cmd1.stdout) > ^ > SyntaxError: invalid syntax Looks like you need a comma after 'stdout=filename'. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Get filename using filefialog.askfilename
In cheirasa...@gmail.com writes: > print(file) > the output is: <..name="file.doc"...mode=..encoding.. > > How can i get the second member of 'file'? If you're using the interpreter, you can type this command: >>> help(file) And it will display documentation for using objects of that type. You can also use this command: >>> dir(file) And it will display all the members and methods that the object provides. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: @staticmethods called more than once
In <02f0123d-2f9e-4287-b983-cfa1db9db...@googlegroups.com> Christian writes: > Hi, > i'm somewhat confused working with @staticmethods. My logger and > configuration methods are called n times, but I have only one call. > n is number of classes which import the loger and configuration class > in the subfolder mymodule. What might be my mistake mistake? > Many thanks > Christian > ### __init__.py ### > from mymodule.MyLogger import MyLogger > from mymodule.MyConfig import MyConfig > # my_test.py ## > from mymodule import MyConfig,MyLogger > #Both methods are static > key,logfile,loglevel = MyConfig().get_config('Logging') > log = MyLogger.set_logger(key,logfile,loglevel) > log.critical(time.time()) > #Output > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 > 2013-05-21 17:20:37,192 - my_test - 17 - CRITICAL - 1369149637.19 You haven't given us the code for your MyLogger class, so it's difficult to say exactly what the problem is. However, I have a guess. Does MyLogger.set_logger() contain a call to addHandler()? Each call to addHandler() adds another handler to your logger, and when you call log.critical() [or any other log function] you get one line of output for each handler. You should only call addHandler() once. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: @staticmethods called more than once
In John Gordon writes: > You should only call addHandler() once. ...for each intended logging output destination, of course. If you want logging output to appear in a file and on-screen, then you would call addHandler() once with a file handler and once with a screen handler. But I think you may be calling addHandler multiple times for the same file handler, which is causing the duplicate logging output. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: lstrip problem - beginner question
In <1829efca-935d-4049-ba61-7138015a2...@googlegroups.com> mstagliamonte writes: > Hi everyone, > I am a beginner in python and trying to find my way through... :) > I am writing a script to get numbers from the headers of a text file. > If the header is something like: > h01 = ('>scaffold_1') > I just use: > h01.lstrip('>scaffold_') > and this returns me '1' > But, if the header is: > h02: ('>contig-100_0') > if I use: > h02.lstrip('>contig-100_') > this returns me with: '' > ...basically nothing. What surprises me is that if I do in this other way: > h02b = h02.lstrip('>contig-100') > I get h02b = ('_1') > and subsequently: > h02b.lstrip('_') > returns me with: '1' which is what I wanted! > Why is this happening? What am I missing? It's happening because the argument you pass to lstrip() isn't an exact string to be removed; it's a set of individual characters, all of which will be stripped out. So, when you make this call: h02.lstrip('>contig-100_') You're telling python to remove all of the characters in '>contig-100_' from the base string, which leaves nothing remaining. The reason it "worked" on your first example was that the character '1' didn't occur in your sample header string 'scaffold_'. If the underscore character is always the separating point in your headers, a better way might be to use the split() method instead of lstrip(). -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increment date by week?
In PieGuy writes: >Starting on any day/date, I would like to create a one year list, by week > (start date could be any day of week). Having a numerical week index in > front of date, ie 1-52, would be a bonus. >ie, 1. 6/4/2013 >2. 6/11/2013 >3. 6/18/2013etc to # 52. >And to save that result to a file. >Moving from 2.7 to 3.3 > TIA from datetime import date, timedelta the_date = date(year=2013, month=6, day=4) print "%d. %s" % (1, the_date) for n in range(2, 53): the_date = the_date + timedelta(days=7) print "%d. %s" % (n, the_date) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Errin when executing a cgi script that sets a cookie in the browser
In <400ea041-adcf-4640-8872-f81808f7d...@googlegroups.com> =?ISO-8859-7?B?zenq/Ovh7/Igyu/98eHy?= writes: > 'python files.py' interprets without an error. > Problem is that when via browser - http://superhost.gr/cgi-bin/koukos.py > i receive the following: Why should 'files.py' have any relation to 'koukous.py'? > What file does the error complain it cannot find? I do not understand its > message. Here is the code of koukos.py > - > #!/usr/bin/python Does /usr/bin/python exist? Scripts can throw a 'No such file or directory' or 'Command not found' error if they begin with a shebang line which refers to a nonexistent program. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Having a hard time to 'get' bing api search results
In "Yves S. Garret" writes: > Hello all, > This is my dilemma, I'm trying to get the generated JSON file using the > bing api search. > This is the code that I'm executing from inside the shell: > http://bin.cakephp.org/view/460660617 > The port doesn't matter to me. Thoughts? It looks like the code is mistakenly interpreting 'user:A' as a port specifier instead of a username and password. Can you supply the credentials another way, perhaps in a header? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Natural Language Processing with Python .dispersion_plot returns nothing
In <05bb0af7-a20b-4b89-92bb-ff25ebd69...@googlegroups.com> sixtyfourbit writes: > When I load all of the necessary modules and try to create the dispersion > plott, I get no return - no plot, no error message, not even a new >>> > prompt, just a blinking cursor under the last line I typed. How long did you wait for results before interrupting the command? How large is text4? It might just take a while to process. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Updating a filename's counter value failed each time
In Simpleton writes: > Hello again, something simple this time: > After a user selects a file from the form, that sleection of his can be > found form reading the variable 'filename' > If the filename already exists in to the database i want to update its > counter and that is what i'm trying to accomplish by: > --- > if form.getvalue('filename'): > cur.execute('''UPDATE files SET hits = hits + 1, host = %s, lastvisit = > %s WHERE url = %s''', (host, lastvisit, filename) ) > --- > For some reason this never return any data, because for troubleshooting > i have tried: > - > data = cur.fetchone() > if data: > print("something been returned out of this"_ > An UPDATE statement isn't a query. There are no results to be fetched. If you want to get results, execute a query (usually a SELECT.) Also, that print statement is an obvious syntax error. Please post the actual code you're running; don't type it in from memory. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Updating a filename's counter value failed each time
In Simpleton writes: > if form.getvalue('filename'): > cur.execute('''UPDATE files SET hits = hits + 1, host = %s, lastvisit = > %s WHERE url = %s''', (host, lastvisit, filename) ) Add an 'else' statement above that prints something, so you will at least know if the UPDATE statement is ever executed. Print the cur.rowcount attribute, which contains the number of rows that were affected by the update. If it's zero, that should tell you something. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Updating a filename's counter value failed each time
In Alister writes: > > #update file's counter if cookie does not exist cur.execute('''UPDATE > > files SET hits = hits + 1, host = %s, lastvisit = > > %s WHERE url = %s''', (host, lastvisit, filename) ) > > > > if cur.rowcount: > > print( " database has been affected" ) > > > > indeed every time i select afilename the message gets printed bu then > > again noticing the database via phpmyadmin the filename counter is > > always remaining 0, and not added by +1 > replase > if cur.rowcount: > print( " database has been affected" ) > with print cur.rowcount() rowcount isn't a method call; it's just an attribute. You don't need the parentheses. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the "for" loop syntax
In <18f427ef-7a9a-413d-a824-65c9df430...@googlegroups.com> arturo balbuena writes: > Hello guys... > I=B4m a begginer in Python, I'm doing a Hangman game, but I'm having troubl= > e with this blank space. I would be greatful if you help me. :) > Here's my code: > http://snipplr.com/view/71581/hangman/ Snipplr says that link doesn't exist. > When I run the code it says: Invalid Syntax and this is the error: > http://i.imgur.com/jKYOPMY.png > http://i.imgur.com/ySoOZFR.png I don't see anything obviously wrong with that code. Are you sure that's a real blank space, and not some weird character that *looks* like a space? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
In "Yves S. Garret" writes: > Hi, I have a question about breaking up really long lines of code in Python. > I have the following line of code: > log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], > settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) > Given the fact that it goes off very far to the right on my screen is not > terribly pleasing to my eyes (and can be rude for other developers). > I was thinking of splitting it up like so: > log.msg("Item wrote to MongoDB database %s/%s" > %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), > level=log.DEBUG, spider=spider) > Is this ok? Are there any rules in Python when it comes to breaking up > long lines of code? There are guidelines in the PEP8 document: http://www.python.org/dev/peps/pep-0008/ Check out the section entitled 'Code lay-out'. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i fix this?
In <54f1fb77-355b-4796-824f-1ee29c402...@googlegroups.com> =?UTF-8?B?0JHQvtGA0LjRgdC70LDQsiDQkdC+0YDQuNGB0LvQsNCy0L7Qsg==?= writes: > > > while 1: > > > name=raw_input("What is your name? ") > > > if name == "bobi": > > print "Hello Master!" > > break > > > else: print "error" > this doesent help me at all Then you'll have to explain why, exactly, it doesn't help. Simply saying "this doesn't help me" is very unhelpful to *us*. Does it produce a syntax error? Does it run, but produce the wrong output? Some other reason? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop Question
In christheco...@gmail.com writes: > On Sunday, June 23, 2013 6:18:35 PM UTC-5, christ...@gmail.com wrote: > > How do I bring users back to beginning of user/password question once they > > > > fail it? thx > Can't seem to get this to cooperate...where does the while statement belong? while True: username = raw_input("Please enter your username: ") password = raw_input("Please enter your password: ") if username == "john doe" and password == "fopwpo": print "Login Successful" break else: print "Please try again" -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop Question
In =?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?= writes: > > while True: > > username = raw_input("Please enter your username: ") > > password = raw_input("Please enter your password: ") > > > > if username == "john doe" and password == "fopwpo": > > print "Login Successful" > > break > > > > else: > > print "Please try again" > You didn't test the code, did you? Because the code you posted is > right. It's right, therefore I did not test it? I don't understand. If the code has a bug, please point it out. > And note that the getpass module is what you should use for that second > thing in real life, for the security of your users. I'm sure this is just an exercise for the OP to understand loops. Security would be counter-productive. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
In pablobarhamal...@gmail.com writes: > isWhite = True > > def change(event): > if event.x > x1 and event.x < x2 and event.y > y1 and event.y < y2: > if isWhite: > w.itemconfig(rect, fill="blue") > isWhite = False > else: > w.itemconfig(rect, fill="white") > isWhite = True > > w.bind("", change) > > root.mainloop() > The problem occurs when clicking on the white square. The following error > appears: > "if isWhite: > UnboundLocalError: local variable 'isWhite' referenced before assignment" > However, the isWhite variable is clearly defined at "True" a few lines > before. Since you're new to programming, this might be a bit tricky to explain, but I'll do my best. :-) The problem is that change() isn't being executed here; instead it's being executed from within root.mainloop(), whenever the user presses button-1. And within root.mainloop(), there is no variable called isWhite. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
In Dave Angel writes: > > The problem is that change() isn't being executed here; instead it's being > > executed from within root.mainloop(), whenever the user presses button-1. > > > > And within root.mainloop(), there is no variable called isWhite. > > > Actually that's irrelevant. Whether or not there's one global with the > same name, or twenty-three object attributes with the same name, the > fact that there's a binding of the local makes that name a local. The > only way to avoid that is not to bind, or to use global or nonlocal > declarations. Quite right. I should have verified my answer before posting. Thanks for setting me straight. :-) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python HTTP POST
In <00ec2f9b-fcae-428c-8932-163e653dd...@googlegroups.com> Matt Graves writes: > How would I submit a python HTTP POST request to... for example, go to > google.com, enter "Pie" into the search box and submit (Search) Something like this: import urllib import urllib2 # the google form search input box is named 'q' data = { 'q': 'Pie' } response = urllib2.urlopen('http://google.com', urllib.urlencode(data)) print response.read() -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Find and Replace Simplification
In Devyn Collier Johnson writes: > I have some code that I want to simplify. I know that a for-loop would > work well, but can I make re.sub perform all of the below tasks at once, > or can I write this in a way that is more efficient than using a for-loop? > DATA = re.sub(',', '', 'DATA') > DATA = re.sub('\'', '', 'DATA') > DATA = re.sub('(', '', 'DATA') > DATA = re.sub(')', '', 'DATA') If your actual use-case is this simple, you might want to use one of the built-in string functions such as strip() or translate(). -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Python 3 and web applications?
In Rui Maciel writes: > I'm currently learning Python, and I've been focusing on Python3. To try to > kill two birds with one stone, I would also like to learn the basics of > writing small web applications. > These web applications don't need to do much more than provide an interface > to a small database, and they may not even be required to be accessible > outside of a LAN. > Does anyone have any tips on what's the best way to start off this > adventure? I recommend using a web framework such as Django or Pylons. It's more to learn, but frameworks handle a ton of low-level details for you and make web development overall much easier. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: embedded python and threading
In <965b463e-e5bf-4ccd-9a3c-b0cb964b3...@googlegroups.com> "David M. Cotter" writes: > == > 9: Traceback (most recent call last): > 9: File "", line 10, in ? > 9: File "", line 6, in main > 9: AttributeError: 'builtin_function_or_method' object has no attribute > 'sleep' > == You must have a file named 'time.py' in the current directory, and the import statement is getting that module instead of the system time module. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: dump a multi dimensional dictionary
In cerr writes: > Can I somehow use pickle.dump() to store a dictionary of lists to a file? > I tried this: > >>> import pickle > >>> mylist = [] > >>> mydict = {} > >>> mylist = '1','2' > >>> mydict['3'] = mylist > >>> fhg = open ("test", 'w') > >>> pickle.dump(fhg,mydict) > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.7/pickle.py", line 1370, in dump > Pickler(file, protocol).dump(obj) > File "/usr/lib/python2.7/pickle.py", line 203, in __init__ > self.write = file.write > AttributeError: 'dict' object has no attribute 'write' > >>> print mydict > {'3': ('1', '2')} > or should I just write my own dump function that can hanle thiS? I think you have the arguments to pickle.dump() in the wrong order. The data to be dumped should come first, then the file object. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP8 79 char max
In Devyn Collier Johnson writes: > (http://www.python.org/dev/peps/pep-0008/#code-lay-out). What devices > cannot handle 80 or more characters on a line? For a start, older fixed-width dumb terminals and printers. And even some very new devices (tablet, smartphone) might have limited screen sizes. And even if you're on a device that can display more than 80 characters, it can be convenient to have several windows display side-to-side. > Would following this recommendation improve script performance? No, but it improves human readability. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: binary key in dictionary
In <9004a556-958f-4d1d-81a7-4d1b73134...@googlegroups.com> cerr writes: > Traceback (most recent call last): > File "gateway.py", line 2485, in > main() > File "gateway.py", line 2459, in main > cloud_check() > File "gateway.py", line 770, in cloud_check > gnstr_dict[src] = gn_from_cloud(curr_mac) > File "gateway.py", line 2103, in gn_from_cloud > tmpgndict[binmac] += "HELLO" > KeyError: '\x04\xeeu' You're not assigning to tmpgndict[binmac]; you're appending to it. This requires that tmpgndict[binmac] already exists, which it does not. Make sure that tmpgndict[binmac] exists before you try appending to it. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: script to Login a website
In wachk...@gmail.com writes: > I have created a script to log in a website. It gets its username and > password from two files, then log's in with this credentials. My code is > not showing me what username it is using to login from the file. And I am > not sure if it is even opening up the url and prompting for login. I am > stuck can someone help me ? How is the data in 'users.txt' and 'password.txt' organized? Given the filenames, I would expect that 'users.txt' contains one username on each line, and 'password.txt' contains one password on each line, with the first username belonging with the first password, the second username belonging with the second password, and so on. Is this correct? If so, that raises the question of how to handle multiple usernames and passwords. Do you just want to use one, or are you supposed to use them all somehow? Anyway, to begin to solve your problem, I'd copy just the file-reading code into a separate program and add plenty of print statements to make sure it works correctly. Once you have that fixed, then you can worry about the web login stuff. And when you read the contents of each file, be aware that the newlines at the end of each line are included. If you don't want these, be sure to call the rstrip() method to remove traling whitespace. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: how to compare below 2 json structure in python
In hisan writes: > sample_json1={{ >"globalControlId": 72, >"value": 0, >"controlId": 2 >}, >{ >"globalControlId": 77, >"value": 3, >"controlId": 7 >} > } > sample_json2={ >{ >"globalControlId": 77, >"value": 3, >"controlId": 7 >}, > { >"globalControlId": 72, >"value": 0, >"controlId": 2 >} > } Assuming you have valid json strings (which these aren't), I think you could convert them into python objects with json.loads() and then compare the python objects. For example: >>> import json >>> json1 = '{"color": "blue", "amount": 10}' >>> json2 = '{"amount": 10, "color": "blue"}' >>> python1 = json.loads(json1) >>> python2 = json.loads(json2) >>> print python1 == python2 True >>> -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: code review
In Kushal Kumaran writes: > I haven't actually seen the rest of the code, but I would like to > point out that applications placing maximum length limits on passwords > are extremely annoying. As a practical matter, doesn't there have to be *some* sort of limit? For example if the (encrypted) password is stored in a database, you can't exceed the table column width. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding to a List and displaying quantity in the list
In Shamefaced writes: > else: > print("%8.3f %s: Waited too long %6.3f" % (now()/60, self.name, > wait) + " time units have passed - Customer has left") > leavelist.append(self.acquired) What is self.acquired? Judging from earlier code it appears to be a function, but here you're appending it to leavelist. Did you really mean to append a function object to leavelist? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: adding a simulation mode
In andrea crotti writes: > try: > copytree('sjkdf', 'dsflkj') > Popen(['notfouhd'], shell=True) > except Exception as e: > print("here") > behaves differently from: > try: > Popen(['notfouhd'], shell=True) > copytree('sjkdf', 'dsflkj') > except Exception as e: > print("here") > because if copytree fails it quits anyway. > I also looked at the code but can't quite get why.. any idea? copytree() could contain a call to sys.exit(), although that seems like a rude thing to do. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: adding a simulation mode
In andrea crotti writes: > Well that's what I thought, but I can't find any explicit exit > anywhere in shutil, so what's going on there? Try catching SystemExit specifically (it doesn't inherit from Exception, so "except Exception" won't catch it.) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
In Dennis Lee Bieber writes: > > Sure it terminates...If you don't run out of RAM to represent the > > number "i" in question, there's also this "heat death of the > > universe" limit I keep hearing about ;-) > > > Since the current evidence indicates the universe will just keep > expanding, it's more of a "deep freeze death..." Heat death means *lack* of heat. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
In Chris Angelico writes: > The second law of thermodynamics states that energy tends to go from > higher states to lower, with heat being the very lowest. It's possible > to do work using (say) kinetic energy, and in the process, some of > that energy becomes heat. It's also possible to do work with any > difference in temperature (eg Stirling engines), so the state of the > universe in which it's no longer possible to do any work will be one > in which all energy is heat and everything's at the same temperature. > That doesn't mean a lack of heat; in fact, it implies that there'll be > rather more heat than there now is, because we currently have a whole > lot of chemical energy available to be used. *mind blown* -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: the meaning of rユ.......ï¾
In Mark Lawrence writes: > Sorry not with you is there something special about April 1st next year? In the United States, April 1st (also known as April Fool's Day) is an occasion for practical jokes, faked 'news' stories, and general silliness. I don't know if it is observed outside the U.S. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a neat solution to a nested loop problem
In Tom P writes: > consider a nested loop algorithm - > for i in range(100): > for j in range(100): > do_something(i,j) > Now, suppose I don't want to use i = 0 and j = 0 as initial values, but > some other values i = N and j = M, and I want to iterate through all > 10,000 values in sequence - is there a neat python-like way to this? I > realize I can do things like use a variable for k in range(1): and > then derive values for i and j from k, but I'm wondering if there's > something less clunky. You could define your own generator function that yields values in whatever order you want: def my_generator(): yield 9 yield 100 for i in range(200, 250): yield i yield 5 -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Objects in Python
In <18409992-1e28-4721-8e64-60c69668d...@googlegroups.com> shaun writes: > I'm having an issue its my first time using python and i set up a class one > of the methods is supposed to return a string but instead returns: > 389E0>> It looks like you're referencing the method object itself, instead of calling it method. In other words, you've left off the parentheses. I.e. you're doing something like this: print my_object.foo Instead of this: print my_object.foo() -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes - python2.7.3 vs python3.2.3
In <18eb8025-7545-4d10-9e76-2e41deaad...@googlegroups.com> Rolf writes: > uint32_t myfunction (char ** _mydata) > { >char mydata[16]; >strcpy(mydata, "Hello Dude!"); >*_mydata = mydata; >return 0; > } mydata is an auto variable, which goes out of scope when myfunction() exits. *_mydata ends up pointing to garbage. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes - python2.7.3 vs python3.2.3
In <9a74$503e88dd$546bb230$30...@cache80.multikabel.net> Jan Kuiken writes: > >> uint32_t myfunction (char ** _mydata) > >> { > >> char mydata[16]; > > > >> strcpy(mydata, "Hello Dude!"); > > > >> *_mydata = mydata; > > > >> return 0; > >> } > > > > mydata is an auto variable, which goes out of scope when myfunction() > > exits. *_mydata ends up pointing to garbage. > I'm not completely sure, but i think this can be solved by using: > static char mydata[16]; That will solve the immediate problem, however it makes myfunction() non-reentrant. > (Btw.: I don't know why you use char ** _mydata, i would use > char * _mydata, but then again, i'm not very familiar with > ctypes) He uses char **_mydata because he wants myfunction()'s caller to see the new value of _mydata, which it wouldn't if it were just char *_mydata. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python presentations
In andrea crotti writes: > For my experience if I only see code in slides I tend not to believe > that it works somehow Presumably you will have some credibility with your audience so they won't just assume you're making it up? I think slides would be fine. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing Pip onto a mac os x system
In John Mordecai Dildy writes: > Now it shows the error of: > sudo: easy_instal: command not found Try 'easy_install' instead of 'easy_instal'. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Print Function
In gengyang...@gmail.com writes: > I am currently using Python 3.2.3 . WHen I use the print function by > typing print "Game Over" , it mentions " SyntaxError : invalid syntax ". > Any ideas on what the problem is and how to resolve it ? Thanks a lot . In python version 3, print was changed into a function. Use this and it will work: print("Game Over") -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Reducing cache/buffer for faster display
In Chris Angelico writes: > On Fri, Sep 28, 2012 at 7:57 AM, Rikishi42 wrote: > > I have these 2 scripts that are very heavy on the file i/o, consume a very > > reasonable amount of cpu and output their counters at a - very - relaxed > > pace to the console. The output is very simply done using something like: > > > >print "files:", nFiles, "\r", > > > > > > Yet alltough there is no real reason for it, even a pace of a print every > > 10-30 secs will be cached, only to actually show an output update every 1-2 > > min or so. > Yup! Just add a call to sys.stdout.flush() after each print. Isn't terminal output line-buffered? I don't understand why there would be an output delay. (Unless the "\r" is messing things up...) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get progress in python script.
In =?ISO-8859-1?Q?Rolando_Ca=F1er_Roblejo?= writes: > Hi all, > Please, I need you suggest me a way to get statistics about a progress > of my python script. My python script could take a lot of time > processing a file, so I need a way that an external program check the > progress of the script. My first idea was that the python script write a > temp file showing the progress and the external program can check that > file, but I think might happen file read/write locking issues. The external program should open the progress file for read only, so I wouldn't think file locking would be an issue. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: how to insert random error in a programming
In Debashish Saha writes: > how to insert random error in a programming? Open the program source file and replace the Nth character with a random character. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception Messages
In MRAB writes: > > Why wasn't the message printed out? > > You didn't add a __str__ method: > class PvCamError(Exception): > def __init__(self, msg): > self.msg = msg > def __str__(self): > return self.msg Wouldn't PvCamError inherit __str__() from Exception? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to only get a list of the names of the non-directory files in current directory ('.')?
In iMath writes: > how to get a list of names of everything in the current directory ? Try os.listdir() . -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to only get a list of the names of the non-directory files in current directory ('.')?
In Chris Angelico writes: > It yields it? You mean Google is an iterator? ITYM generator. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate unique ID for URL
In <0692e6a2-343c-4eb0-be57-fe5c815ef...@googlegroups.com> Richard writes: > I want to create a URL-safe unique ID for URL's. > Currently I use: > url_id = base64.urlsafe_b64encode(url) > >>> base64.urlsafe_b64encode('docs.python.org/library/uuid.html') > 'ZG9jcy5weXRob24ub3JnL2xpYnJhcnkvdXVpZC5odG1s' > I would prefer more concise ID's. > What do you recommend? - Compression? Does the ID need to contain all the information necessary to recreate the original URL? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Robust regex
In "Joseph L. Casale" writes: > Trying to robustly parse a string that will have key/value pairs separated > by three pipes, where each additional key/value (if more than one exists) > will be delineated by four more pipes. > string = 'key_1|||value_1key_2|||value_2' > regex = '((?:(?!\|\|\|).)+)(?:\|\|\|)((?:(?!\|\|\|).)+)(?:\|\|\|\|)?' > I am not convinced this is the most effective or safest, any opinions would > be greatly appreciated! Regexes may be overkill here. A simple string split might be better: string = 'key_1|||value_1key_2|||value_2' pairs = string.split('') for pair in pairs: keyval = pair.split('|||') print '%s=%s' % (keyval[0], keyval[1]) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: 10 sec poll - please reply!
In <3d71f175-164e-494c-a521-2eaa5679b...@googlegroups.com> Michael Herrmann writes: > What, in your view, would be the most intuitive alternative name? keyboard_input(). -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: List problem
In <8c0a3ea9-2560-47eb-a9c7-3770e41fe...@googlegroups.com> subhabangal...@gmail.com writes: > Dear Group, > I have a list of the following pattern, > [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), (= > 'Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag'= > , 'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN= > '), ('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'N= > N'), ('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), = > ('in', 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','= > ), ("''", "''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'= > ), ('Capt', 'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said',= > 'VBD'), ('here', 'RB')] > Now, as we see it has multiple VBD elements. > I want to recognize,count and index them all. That depends on exactly what you mean by 'reorganize' and 'index'. But here's a start: items = [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), ('Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag' , 'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN'), ('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'NN'), ('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), ('in', 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','), ("''", "''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'), ('Capt', 'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said', 'VBD'), ('here', 'RB')] vbds = [item[0] for item in items if item[1] == 'VBD'] print vbds -- http://mail.python.org/mailman/listinfo/python-list
Re: Conversion of List of Tuples
In <6049bc85-6f8e-429b-a855-ecef47a9d...@googlegroups.com> subhabangal...@gmail.com writes: > Dear Group, > I have a tuple of list as, > tup_list=[(1,2), (3,4)] > Now if I want to covert as a simple list, > list=[1,2,3,4] > how may I do that? new_list = [] for t in tup_list: for item in t: new_list.append(item) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Conversion of List of Tuples
In subhabangal...@gmail.com writes: > Thanks. But I am not getting the counter "5posts 0 views"...if > moderator can please check the issue. I logged in via Google Groups and all the replies were present. What is your question? (This group is not moderated.) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: mini browser with python
In inq1ltd writes: > In other words I need a mini, simple browser; > something I can build that will open, read and > display a saved html or the connected url site. What will be the output of this mini browser? Plain text? Rendered graphics? An audible screen reader? Something else? What web standards does this mini browser need to support? Full HTML5? Partial HTML? CSS? Javascript? Flash? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: mini browser with python
In inq1ltd writes: > Right now I need some way to display > 15 to 20 lines of html in its own window or > as part of my screen. Could you open a shell window and run a text web browser such as Lynx? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: date-time comparison, aware vs naive
In <21eb3e6f-9a82-47aa-93ff-8f4083d18...@googlegroups.com> noydb writes: > I want to compare a user entered date-and-time against the date-and-time of > a pdf file. I posted on this (how to get a file's date-time) before, was > advised to do it like: > import datetime, os, stat > mtime = os.lstat(filename)[stat.ST_MTIME] // the files modification time > dt = datetime.datetime.fromtimestamp(mtime) > I am having problems with the comparison, that line is failing. What line? You haven't posted any comparison line of code here. Please post the actual code you're using, instead of telling us about it. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
In qbai...@ihets.org writes: > """ crypto.py > Implements a simple substitution cypher > """ > alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > key = "XPMGTDHLYONZBWEARKJUFSCIQV" > def main(): > keepGoing = True > while keepGoing: > response = menu() > if response == "1": > plain = raw_input("text to be encoded: ") > print encode(plain) > elif response == "2": > coded = raw_input("code to be decyphered: ") > print decode(coded) > elif response == "0": > print "Thanks for doing secret spy stuff with me." > keepGoing = False > else: > print "I don't know what you want to do..." > i really need help on how to encrypt it im not sure how to go about doing > that please help. def encode(plain): '''Return a substituted version of the plain text.''' encoded = '' for ch in plain: encoded += key[alpha.index(ch)] return encoded -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb compare lower
In Anatoli Hristov writes: > I have a situation where I compare the SKU in my DB and there are some > SKU that are with lowercase and some with uppercase, how can I solve > this in your opinion ? > def Update_SQL(price, sku): > db = MySQLdb.connect("localhost","getit","opencart", > use_unicode=True, charset="utf8") > cursor = db.cursor() > sql = "UPDATE product SET price=%s WHERE sku=%s" > cursor.execute(sql, (price, sku)) > db.commit() > db.close() I think this will work: sql = 'UPDATE product SET price=%s WHERE LOWER(sku)=%s' cursor.execute(sql, (price, sku.lower()) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Doesn't This MySQL Statement Execute?
In Tom Borkin writes: > Actually, what I originally had was: > cursor.execute("""insert into interactions values(Null, %s, "Call Back", > %s)""", (i_id, date_plus_2)) > and that didn't work, either. I tried your variation like: > cursor.execute("""insert into interactions values(Null, %s, "Call Back", > %s)""" % (i_id, date_plus_2)) > and no cigar :( > Tom Have you tried using single-quotes around Call Back, instead of double quotes? I've noticed that SQL statements prefer single-quoted strings (although that may be Oracle specific, as that's all I've really worked with). -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Evaluate postgres boolean field
In andydtay...@gmail.com writes: > for row in cursor: > row_count += 1 > if row[4] = True > print row[1] Since row[4] is a boolean value, you should be able to just say: if row[4]: print row[1] -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: new to python and programming at large.
In kwakukwat...@gmail.com writes: > thanks for ur help I wz able to do it.but I wish to expand it by asking > a user to input a number for the sqrt to be calculated it I dd it this > way but its not working. > from math import sqrt > number = raw_input('enter a number:') > def number(y): > return number(Y) You're storing the user input in a variable called 'number', but then you define a method also called 'number'. Call them something different. Within your method, you probably want to return sqrt(y) instead of calling the method from itself. The argument to your method is called 'y' in the definition, but you refer to it as 'Y' in the return statement. Variable names are case-sensitive. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why BOM in logging message?
In r...@panix.com (Roy Smith) writes: > What's weird is that two of the servers, and only those two, stick a > BOM (Byte Order Mark) in front of the message they log. It shows up > in syslog as: > 2013-01-09T00:00:00+00:00 web5.songza.com 2013-01-0900:00:00,754 > [18979]: [etc...] I worked on an application that would insert a BOM in syslog messages if the logged message contained unicode, but not if it was plain ascii. Not sure if this relates to your issue, but it's similar enough that it seemed worth mentioning. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Psycopg2 SyntaxError: invalid syntax on "INSERT INTO" database
In andydtay...@gmail.com writes: > I'm a bit stuck on this "INSERT INTO" syntax error. I have no idea why it's What syntax error? It's always helpful if you can post the actual error message. > not working actually... I've tried changing column types to char but that > didn't work. I've gone a bit blind looking at it, but hopefully you can set > me right. With the '#'d out lines instead the file does work. > #!/usr/bin/python > import psycopg2 > import sys > def main(): >db = psycopg2.connect( > host = 'localhost', > database = 'gisdb', > user = 'postgres', > password = '##' >) >cursor = db.cursor() >cursor.execute("DROP TABLE IF EXISTS tubecross") >cursor_to.execute("CREATE TABLE tubecross (id serial PRIMARY KEY, > station_code char, SAJ interval, SPB interval, SOQ interval);") >#cursor.execute("CREATE TABLE tubecross (id serial PRIMARY KEY, num > integer, data varchar);") >#cursor.execute("INSERT INTO tubecross (num, data) VALUES (%s, %s)",(900, > "9abc'def")) >cursor_to.execute("INSERT INTO tubecross (station_code, SAJ, SPB, SOQ) > VALUES (%s, %s, %s, %s)",(SAJ, 00:00, 00:22, 00:27)) >db.commit() > if __name__ == "__main__": > main() You appear to have two very different versions of the tubecross table. One version has three fields (id, num, data) and the other version has at least four (station_code, SAJ, SPB, SOQ). Which one is correct? Also, what is the 'cursor_to' variable? It doesn't appear to be defined anywhere. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Thought of the day
In Michael Torrie writes: > On 01/13/2013 09:16 PM, Steven D'Aprano wrote: > > A programmer had a problem, and thought Now he has "I know, I'll solve > > two it with threads!" problems. > The same applies to regular expressions, which is actually what the > expression was first used with years ago. Probably applies to just > about any technology. Including Java. Steven cleverly worded it in such a way as to apply directly to threads. The sentences are jumbled and interleaved, as if they were the output of two threads that are not synchronized. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Uniquely identifying each & every html template
In <8deb6f5d-ff10-4b36-bdd6-36f9eed58...@googlegroups.com> Ferrous Cranus writes: > Problem is that i have to insert at the very first line of every .html > template of mine, a unique string containing a number like: > index.html > somefile.html > other.html > nikos.html > cool.html > to HELP counter.py identify each webpage at a unique way. Instead of inserting unique content in every page, can you use the document path itself as the identifier? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Uniquely identifying each & every html template
In <5dd4babd-716d-4542-ad36-e6a841b73...@googlegroups.com> Ferrous Cranus writes: > > If that's the case, then I figure you have about 3 choices: > > 1) use the file path as your key, instead of requiring a number > No, i cannot, because it would mess things at a later time on when i for > example: > 1. mv name.html othername.html (document's filename altered) > 2. mv name.html /subfolder/name.html (document's filepath altered) Will the file always reside on the same device? If so, perhaps you could use the file inode number as the key. (That seems fairly brittle though. For example if the disk crashes and is restored from a backup, the inodes could easily be different.) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Using filepath method to identify an .html page
In Ferrous Cranus writes: > I just need a way to CONVERT a string(absolute path) to a 4-digit unique > number with INT!!! That's all i want!! But i cannot make it work :( Given your requirements, I don't think it *can* work. There's just no way to do it. How can the computer guarantee that billions of possible inputs (file paths) map to 10,000 unique outputs (4-digit numbers)? It's not possible. It might be possible if you had control over the format of the input strings, but it doesn't sound like you do. Can you maintain a separate database which maps file paths to numbers? If so, then this is an easy problem. Just keep a lookup table, like so: filepath number -- /home/files/bob/foo.html 0001 /home/files/bob/bar.html 0002 /home/files/steve/recipes/chocolate-cake.html0003 /home/files/mary/payroll.html 0004 -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to a number by using INT (no hash method)
In <592233bd-3fc1-4e13-97f8-e11f89fbb...@googlegroups.com> Ferrous Cranus writes: > > pin int( htmlpage.encode("hex"), 16 ) % 1 > > > > It'll give you your number, but there are no guarantees of uniqueness. > You're looking at more blind random luck using that. > Finally!! THANK YOU VERY MUCH!!! THIS IS WHAT I WAS LOOKING FOR!!! No it isn't; you said you wanted a unique 4-digit number. This method can return the same 4-digit number for lots of different file paths. > NOW, if you please explain it to me from the innermost parenthesis please, > because i do want to understand it!!! 1. Transform the html path string into a (large) hexadecimal number using the encode() function. 2. Convert the hexadecimal number into a decimal integer using the int() function. 3. Shrink the integer into the range 0- by using the % operator. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using filepath method to identify an .html page
In <4847a0e3-aefa-4330-9252-db08f2e99...@googlegroups.com> Ferrous Cranus writes: > And the .html files are not even close 10.000 You said you wanted a 4-digit number. There are 10,000 different 4-digit numbers. 0001 0002 ... -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing class from another file
In Kevin Holleran writes: > I have a class called My_Class in a subdir called Sub_Dir. > in My_Class.py is the following > class My_Class_Connector: > def __init__(self,un,pw,qs_srv="domain.com"): > self.username = un > self.password = pw > Then I am trying to call from a script in the parent dir like this: > from Sub_Dir.My_Class import * > q_api = My_Class.My_Class_Connector(string1,string2) Even if your import had worked, this would be wrong. You're importing everything from Sub_Dir.My_Class, so My_Class_Connector is in the current namespace. You don't need to add "My_Class." on the front (and in fact it's an error to do so.) > Traceback (most recent call last): > File "testing.py", line 1, in > from Sub_Dir.My_Class import * > ImportError: No module named Sub_Dir.My_Class Is there a file named __init__.py in Sub_Dir? A directory must contain that file in order to be considered a "module". (If you don't know what to put in the file, just leave it empty.) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to a number by using INT (no hash method)
In Ferrous Cranus writes: > May i sent you my code by mail so for you see whats wrong and > http://superhost.gr produces error? I tried going to that address and got some error output. I noticed this in the error dump: 186 if cursor.rowcount == 0: 187 cursor.execute( '''INSERT INTO visitors(pin, host , hits, useros, browser, date) VALUES(%s, %s, %s, %s, %s)''', (pin, hos t, 1, useros, browser, date) ) The INSERT statement gives six column names but only five placeholders (%s) in the VALUES clause. Perhaps that's the problem? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Search log for string and display hourly/daily report
In <4f952e77-258d-47ae-9d76-a86daa8ac...@googlegroups.com> spe...@gmail.com writes: > I need to search a log file for a specific string (Successfully Sent) and > report the number of instances in the last hour (from when executed) and > total for the day so far (midnight till the time executed). Can anyone > provide any examples of such a program or get me started? from datetime import datetime, timedelta from time import mktime, strptime now = datetime.now() midnight = now.replace(hour=0, minute=0, second=0, microsecond=0) one_hour_ago = now - timedelta(hours=1) daily_instances = 0 hourly_instances = 0 with open('myfile.log') as logfile: for line in logfile: if 'Successfully Sent' in line: time_string = line[0:19] struct = strptime(time_string, "%Y-%m-%dT%H:%M:%S") log_time = datetime.fromtimestamp(mktime(struct)) if log_time > midnight: daily_instances += 1 if log_time > one_hour_ago: hourly_instances += 1 print "Instances in the last hour: ", hourly_instances print "Instances since midnight: ", daily_instances This code assumes that log lines begin with a timestamp similar to "2013-01-23T09:27:01". If the timestamp is in a different format, or occurs elsewhere in the line, you'll have to adjust for that. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Arent these snippets equivalent?
In Coolgg writes: > Is this: > while True: > data = fp.read(4096) > if not data: > break > ... > not equivalent to this: > data = fp.read (4096) > while data: > ...{handle the chunk here} > data = fp.read (4096) It looks equivalent to me (in terms of control flow). But in the second example the fp.read() statement is duplicated, which is undesirable. It would be all too easy for a maintenance programmer to go into the code a year from now and change the first one but miss the second one. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: The best, friendly and easy use Python Editor.
In Hazard Seventyfour writes: > Hello, > I new in this python and decided to learn more about it, so i can make > an own script :), > for all senior can you suggest me the best, friendly and easy use with > nice GUI editor for me, and have many a good features such as auto > complete/auto correct. Try PyScripter. http://code.google.com/p/pyscripter/ -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: The best, friendly and easy use Python Editor.
In Sharwan Joram writes: > use vim. He said he wanted autocomplete. Does Vim have that? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Please provide a better explanation of tuples and dictionaries
In "Daniel W. Rouse Jr." writes: > I have recently started learning Python (2.7.3) but need a better > explanation of how to use tuples and dictionaries. A tuple is a linear sequence of items, accessed via subscripts that start at zero. Tuples are read-only; items cannot be added, removed, nor replaced. Items in a tuple need not be the same type. Example: >>> my_tuple = (1, 5, 'hello', 9.) >>> print my_tuple[0] 1 >>> print my_tuple[2] hello A dictionary is a mapping type; it allows you to access items via a meaningful name (usually a string.) Dictionaries do not preserve the order in which items are created (but there is a class in newer python versions, collections.OrderedDict, which does preserve order.) Example: >>> person = {} # start with an empty dictionary >>> person['name'] = 'John' >>> person['age'] = 40 >>> person['occupation'] = 'Programmer' >>> print person['age'] 40 Dictionaries can also be created with some initial values, like so: >>> person = { 'name': 'John', 'age': 40, 'occupation' : 'Programmer' } -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird newbie question
In Matty Sarro writes: > Hey everyone. I'm running into a funky error as I work through "Learn > Python the Hard Way." What's weird is both idle and the python > interpreter in idle spit out an error about syntax, but when I run the > same script from the command line it works just fine, with no issue. > I'm not sure if its an issue with IDLE or if I'm doing something > wrong. > Here's the book's code: > from sys import argv > script, filename = argv > txt = open(filename) > print "Here's your file %r:" % filename > print txt.read() > print "Type the filename again:" > file_again = raw_input("> ") > txt_again = open(file_again) > print txt_again.read() > Here's my code: > from sys import argv > script,filename=argv > txt=open(filename) > print "Here is your file %r:" % filename > print txt.read() > print "I'll also ask you to type it again:" > file_again=raw_input("> ") > txt_again=open(file_again) > print txt_again.read() > IDLE is saying that my error is on line 4, at the second set of > quotation marks. Since I can't get the error from the command line, I > can't actually see what the syntax error is that it's complaining > about. Any advice would really be appreciated, thank you!! This may be a Python version mismatch error. In python version 2.x (and 1.x for that matter), "print" is a statement, but it was changed to be a function in python version 3.x. In other words, in python 2.x you can say this: print x print "hello there" But in python 3.x you have to do it a little differently: print(x) print("hello there") It sounds like your IDLE is running python 3, but your command line is running python 2. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading files in from the proper directory
In smac2...@comcast.net writes: > Am I correct in thinking that I need to change the current working > directory to this folder in order for Python to read in these files, > then generate my output? You don't have to do it that way, no. In general, when opening a file, you can do it two ways: Either provide a full pathname, or provide a relative pathname. If you provide a full pathname (for example "/usr/home/smith/myfile.txt"), that file will be opened and it does not matter what the current working directory is. If you provide a relative pathname (for example "myfile.txt"), python will attempt to open that file starting from the current working dir. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading files in from the proper directory
In <9bfb3e39-2bc6-4399-90cc-1c53aa062...@h6g2000yqk.googlegroups.com> smac2...@comcast.net writes: > xls_files = glob.glob(in_dir + "*.xls") You may want to put a directory separator character in between the directory name and the filename glob pattern. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
How can I catch misnamed variables?
Recently I was been bitten by some stupid errors in my code, and I'm wondering if there's a simple way to catch them. One error was of the form: my_object.some_function() .. when I hadn't declared an object named "my_object". The other error was similar: x = my_module.CONSTANT .. when I hadn't imported my_module. Of course both of these errors were deep inside a long-running function call, so it took a while for them to crop up. Is there an automated way to catch errors like these? I'm using the compileall module to build my program and it does catch some errors such as incorrect indentation, but not errors like the above. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime module and timezone
In <20120210222545.4cbe6...@bigfoot.com> Olive writes: > In the datetime module, it has support for a notion of timezone but is > it possible to use one of the available timezone (I am on Linux). Linux > has a notion of timezone (in my distribution, they are stored > in /usr/share/zoneinfo). I would like to be able 1) to know the current > timezone and 2) to be able to use the timezone available on the system. > How can I do that? I believe the current user's timezone is stored in the TZ environment variable. I don't understand your second question. Are you asking for a list of of all the possible timezone choices? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: log and figure out what bits are slow and optimize them.
In Kev Dwyer writes: > *Any* instrumentation code is going to affect performance. Funny story about that... I wanted to profile some code of mine, and a colleague recommended the 'hotshot' module. It's pretty easy to use: there are functions to start profiling, stop profiling and print results. So I added the function calls and ran my code and it took a really long time. I mean a REALLY long time. In fact I eventually had to kill the process. I briefly wondered if my coworker was playing a prank on me... then I realized that I had neglected to call the function to stop profiling! So when I went to print the results, it was still profiling... endlessly. (Okay, maybe it wasn't that funny.) -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python code file prototype
In <66ea0353-02ee-4152-947a-97b44ff3e...@p7g2000yqk.googlegroups.com> Bruce Eckel writes: > There's an option when you do this to insert default file contents, so > I began searching the web for some kind of prototype Python file that > would be appropriate to start with. I'm certain I've seen this before > and that there's been discussions about the best starting point for a > python code file, but I find I can't get any search hits for it. Here's what PyScripter inserts in a new python file: #- # Name:module1 # Purpose: # # Author: $USERNAME # # Created: $DATE # Copyright: (c) $USERNAME $YEAR # Licence: #- #!/usr/bin/env python def main(): pass if __name__ == '__main__': main() Where $USERNAME, $DATE and $YEAR are expanded to the actual values. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehension question
In James Broadhead writes: > On 29 February 2012 13:52, Johann Spies wrote: > > In [82]: t.append(instansie) > > t.append(instansie) > > > > In [83]: t > > t > > Out[83]: ['Mangosuthu Technikon'] > > In [84]: t = [x.alt_name for x in lys].append(instansie) > > t = [x.alt_name for x in lys].append(instansie) > > > > In [85]: t > > t > > > > In [86]: type t > > type t > > ---> type(t) > > Out[86]: NoneType > > > You should note that in [82], you're not doing: > > t = t.append(instansie) append() modifies the list in-place. It doesn't return anything. (and therefore its return value is None) >>> x = [1, 2, 3] >>> y = x.append(4) >>> print x [1, 2, 3, 4] >>> print y None -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: Project
In Dev Dixit writes: > Please, tell me how to develop project on "how people intract with > social networing sites". First you need a more detailed description of exactly what you want. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this regular expression?
In <21519dbf-4097-4780-874d-41d76f645...@x17g2000yqj.googlegroups.com> John Salerno writes: > 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. The first error on that screen is that "xslt-config" is not found as a command. Try a web search for "xslt-config not found", there seemed to be some helpful results. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Best way to disconnect from ldap?
I'm writing an application that interacts with ldap, and I'm looking for advice on how to handle the connection. Specifically, how to close the ldap connection when the application is done. I wrote a class to wrap an LDAP connection, similar to this: import ldap import ConfigParser class MyLDAPWrapper(object): def __init__(self): config = ConfigParser.SafeConfigParser() config.read('sample.conf') uri = config.get('LDAP', 'uri') user = config.get('LDAP', 'user') password = config.get('LDAP', 'password') self.ldapClient = ldap.initialize(uri) self.ldapClient.simple_bind_s(user, password) My question is this: what is the best way to ensure the ldap connection gets closed when it should? I could write an explicit close() method, but that seems a bit messy; there would end up being lots of calls to close() scattered around in my code (primarily inside exception handlers.) Or I could write a __del__ method: def __del__(self): self.ldapClient.unbind_s() This seems like a much cleaner solution, as I don't ever have to worry about closing the connection; it gets done automatically. I haven't ever used __del__ before. Are there any 'gotchas' I need to worry about? Thanks! -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list