Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
On 31/7/19 2:21 am, boB Stepp wrote: I have been using various iterations of a solitaire scorekeeper program to explore different programming thoughts. In my latest musings I am wondering about -- in general -- whether it is best to store calculated data values in a file and reload these values, or whether to recalculate such data upon each new run of a program. In terms of my solitaire scorekeeper program is it better to store "Hand Number, Date, Time, Score, Total Score" or instead, "Hand Number, Date, Time, Score"? Of course I don't really need to store hand number since it is easily determined by its row/record number in its csv file. In this trivial example I cannot imagine there is any realistic difference between the two approaches, but I am trying to generalize my thoughts for potentially much more expensive calculations, very large data sets, and what is the likelihood of storage errors occurring in files. Any thoughts on this? TIA! From a scientific viewpoint, you want to keep the raw data, so you can perform other calculations that you may not have thought of yet. But that's not got much to do with programming ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a graphics library for common tkinter Button functions?
On 21/3/19 10:19 am, Alan Gauld via Tutor wrote: On 20/03/19 22:43, Chris Roy-Smith wrote: Is there a "graphics library" of common button uses? that is things like forward record, back record, 1st record, last record, printer, save and the likes. The short answer is no. But you can assign any bitmap image to a button. (You can use other formats too but bitmaps are easiest in my experience!) But putting an image on the button does not give it any functionality. You need to program that yourself. HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks Alan, Yes I knew that buttons need a function to do anything. I was hoping that the wheel didn't need re-inventing. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] is there a graphics library for common tkinter Button functions?
Hi, Is there a "graphics library" of common button uses? that is things like forward record, back record, 1st record, last record, printer, save and the likes. I don't have very artistic abilities, so would prefer to save making my own library. Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter: Can's figure out how to put a frame in a second window
On 9/3/19 10:13 pm, Alan Gauld via Tutor wrote: On 09/03/2019 02:53, Chris Roy-Smith wrote: What is happening is that the contents of the frame appear in the master window. I was expecting them to show in the second window. Also I expected the frame to be sunken, but there is no obvious signs of the frame, not even a colored background. What am I doing wrong? Its a very common mistake in Tkinter. When you use one of the layout managers, in this case grid() the return value is always None. def NewWindow(): sw=Toplevel(master) sw.title('New Window') Label(sw, text='new window').grid(row=0, column=0) sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0) So you are here assigning None to sframe. Label(sframe, text='Label in a frame').grid(row=2, column=0) Label(sframe, text='Second label in this frame').grid(row=3, column=0) And when you pass None as the parent to a widget Tk defaults to the root. So your widgets appear in your main window. Change the sframe line to two lines: sframe=Frame(sw, relief=SUNKEN, bg='red') sframe.grid(row=1, column=0) and all will be well except the sunken relief wont work. TYhats because the sunken form requires a border width of at least 2 pixels to be visible. So you need to add border=2 (or more) to make it work. So the final line should be: sframe=Frame(sw, border=2, relief=SUNKEN, bg='red') sframe.grid(row=1, column=0) As I say its a very common mistake and so, any time weird things happen, always check that anywhere you assign a widget to a variable you call the layout manager on a separate line. HTH Thanks Alan, Simple when you know. I remember having a similar issue with Entry widgets, Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter: Can's figure out how to put a frame in a second window
Hi. running Linux, with python3.6 I am trying to learn how to put a frame on a second window. I get no errors showing in the terminal, and I get no traceback. What is happening is that the contents of the frame appear in the master window. I was expecting them to show in the second window. Also I expected the frame to be sunken, but there is no obvious signs of the frame, not even a colored background. What am I doing wrong? Thank you, Chris Roy-Smith here is my code: #! /usr/bin/python3 from tkinter import * def NewWindow(): sw=Toplevel(master) sw.title('New Window') Label(sw, text='new window').grid(row=0, column=0) sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0) Label(sframe, text='Label in a frame').grid(row=2, column=0) Label(sframe, text='Second label in this frame').grid(row=3, column=0) Button(sw, text='close window', command=sw.destroy).grid(row=5, column=0) master=Tk() master.title('Master Window') Button(master, text='open window', command=NewWindow).grid(row=1, column=1) Button(master, text='quit', command=master.destroy).grid(row=2, column=1) Label(master, text="learning").grid(row=0, column=0) master.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to write a function which reads files
On Tue, 7 Aug 2018 at 15:07, Rafael Knuth wrote: > def FileReader(file_path): > with open(file_path) as file_object: > contents = file_object.read > return contents > > print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for > better readability > > I got this error message: > > You forgot the parentheses (), and are returning a reference to the function instead of calling it and returning its result. Do this: contents = file_object.read() Also, consider using snake_case instead of PascalCase for your function name, since the latter is typically used for classes, and perhaps call it read_file to better describe it? -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] why can use a widget assigned to a variable or just use it on it's own?
Hi, I'm trying to understand working with objects. If I have grasped things correctly a widget is an object. So why can I assign the widget, or use it stand alone? See sample code below = #!/usr/bin/python3 from tkinter import * main=Tk() # as I understand it this will create an instance of the button widget called b1 b1=Button(main, text='instantce', command= lambda b='goodbye' : print(b)).grid(row=1, column=0) # but here I haven't made an instance, but all seems well Button(main, text='test1', command=lambda a='hello' :print(a)).grid(row=0, column=0) main.mainloop() === any explanation gratefully recieved Regards, Chris ROy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to change the command "string" on a tkinter Button?
On 01/07/18 19:19, Steven D'Aprano wrote: On Sun, Jul 01, 2018 at 03:32:59PM +1000, Chris Roy-Smith wrote: Python is the first language I have attempted since macro assembler for CP/M. Python seems to be another world. Yes indeed, high-level languages like Python *are* a radically different programming experience than low-level languages like assembler. The fundamental execution and data models of the languages are *very* different: - assembler lives in a universe of bytes and words; there are few abstractions and you are dealing (very nearly) with the lowest level of flipping bits in hardware, or at least of moving bytes. - Python lives in a world of big, complex abstractions like dicts and Unicode text and even objects as complex as "web server", and the fundamental operations are multiple layers away from moving bytes. It's not surprising that this may require some re-adjustment of your mental model of how to program. those big complex bits cut down on the amount of code needed to achieve a given task. :-) It appears that I broke the code I started experimenting with, to try changing the command, and that may have added to my confusion. "Save As..." before engaging in big changes is your friend :-) yes, was supposed to be a quick experiment to test idea ;) Even better would be to learn a form of VCS (version control system) such as Mercurial (hg) or git. Depending on the text editor you are using, it may have VCS integration available. I don't know anything about these tools, I use Kate as my editor for my programming. I usually give a new number to separate versions, I'm sure there are better ways, I just haven't gone looking for them yet. Idle only looks useful for CLI stuff. Off-topic: I see you are a fellow Internode user, like me. Which part of Australia are you in, and is your internet connection giving you as much grief as mine is? I have had little trouble with Internode over the last 13 years or so. The other day is the first time I had a really slow download, went to another mirror in Western Australia, and all went as fast as I'm supposed to get (I have the slowest option of NBN, ( bronze 100) which I have never NEEDED extra bandwidth, it might be nice, but I don't use the sort of service which depends on good bandwidth, downloads can go all night for all I care). I'm not greedy though it's all very fast compared to dial up, or packet radio I'm pretty sure that Internode is *grossly* oversubscribed. E.g. when I try doing a google search, I'll usually get "Waiting for www.google.com..." which then times out about six or twelve times on average before succeeding to connect, after which it is damn near instantaneous. I search with DuckDuckGo, and rarely have any response issue with my searches. I don't think they sell my search data. I downloaded 2 GB of data in about ten minutes yesterday, not long followed by a 2K email that took *three hours* to leave my computer because the connection to Internode's mail server kept timing out. Your connection is a bit faster than mine. I've not experienced any speed issues with the email server. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to change the command "string" on a tkinter Button?
On 01/07/18 02:17, Alan Gauld via Tutor wrote: On 30/06/18 03:55, Chris Roy-Smith wrote: I am trying to change the command of a tkinter Button in my program. Eventually I want to be able to do this to many buttons. Since I'm not 100% sure if you mean the command or the label or both here is a simple example that does both... import tkinter as tk def cmd1(): print('This is command 1') def cmd2(): print('This is number 2') I was hoping eventually to generate the command form the results of a database query, not knowing the exact command until run time. Perhaps what I was trying to achieve is too close to self modifying code, I was warned off this when I used to dabble in assembler. Does the same advice hold for python? def swapCmd(): c = b1['command'] # kluge to get the function name from Tcl id if str(c).endswith("cmd1"): b1['command'] = cmd2 else: b1['command'] = cmd1 I never thought to try anything like this, I was thinking more along the lines for how to change the text of a Labe.l def swapText(): t = b1['text'] if t == "Cool": b1['text'] = "Hot" else: b1['text'] = "Cool" # make GUI top = tk.Tk() win = tk.Frame(top) win.pack() b1 = tk.Button(win,text="Cool", command=cmd1) b1.pack() b2 = tk.Button(win, text="Swap text", command=swapText) b2.pack() b3 = tk.Button(win, text="Swap cmd", command=swapCmd) b3.pack() top.mainloop() ### Thank you again Alan, While your solution works, it's not how I imagined in terms of approach. Eventually I wanted to change the command of a variable number of buttons with the actual command depending on the results of a database query. I am unable to see how I can manage this in your solution style ( predetermined commands) might be difficult to achieve ( with my limited programming skills ). Your solution made me rethink what I was attempting to do, and found with a slightly modified database query, I didn't need to change the command at all. The rest of this bit of program I have already solved. Now I just have to learn a lot more about classes, and objects. again, thank you Alan. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to change the command "string" on a tkinter Button?
On 01/07/18 02:17, Alan Gauld via Tutor wrote: On 30/06/18 03:55, Chris Roy-Smith wrote: I am trying to change the command of a tkinter Button in my program. Eventually I want to be able to do this to many buttons. Since I'm not 100% sure if you mean the command or the label or both here is a simple example that does both... import tkinter as tk def cmd1(): print('This is command 1') def cmd2(): print('This is number 2') def swapCmd(): c = b1['command'] # kluge to get the function name from Tcl id if str(c).endswith("cmd1"): b1['command'] = cmd2 else: b1['command'] = cmd1 def swapText(): t = b1['text'] if t == "Cool": b1['text'] = "Hot" else: b1['text'] = "Cool" # make GUI top = tk.Tk() win = tk.Frame(top) win.pack() b1 = tk.Button(win,text="Cool", command=cmd1) b1.pack() b2 = tk.Button(win, text="Swap text", command=swapText) b2.pack() b3 = tk.Button(win, text="Swap cmd", command=swapCmd) b3.pack() top.mainloop() ### Thank you Alan, you have covered what I think I wanted to achieve. For me, programming is a continual learning experience, unfortunately I seem to forget nearly as much as I learn, Python is the first language I have attempted since macro assembler for CP/M. Python seems to be another world. It appears that I broke the code I started experimenting with, to try changing the command, and that may have added to my confusion. I'll play with your example to try an understand what is going on. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] how to change the command "string" on a tkinter Button?
Hi, OS is Linux, Python version is 3.6.5 I am trying to change the command of a tkinter Button in my program. Eventually I want to be able to do this to many buttons. My attempt at code brings up no error messages, but the button appears to do nothing. I really have no idea how to do this, but this is what I wrote. #!/usr/bin/python3 from tkinter import * class form(object): def __init__(self, x, reply, master, z,bu): self.x=x self.reply=reply self.master=master self.z=z self.bu=bu def change(x, reply, z, b): #f contains the alternative command (as a string) f=["lambda x=vars, txt=reply,fu=0 bu=b1 :form.change(x, txt, fu, bu)", "lambda x=vars, txt=first, fu=1 bu=b1: form.change(x, txt, fu, bu)"] for i in range(4): x[i].set(reply[i]) #attempt to change command clause set.button(f[z]) def draw(master): vars = [] label = [] button = StringVar for i in range(4): var = StringVar() vars.append(var) label.append("") label[i] = Label( master, textvariable=var, relief=RAISED ).grid(row=i, column=0) vars[i].set(first[i]) b1=Button(master, text="change", command=button).grid(row=i+1, column=0) reply=["now I don't know", "Happy birthday", "Many happy returns", "Next it's my turn",1] first=["What's your name?", "My name is Fred", "I have just had my birthday", "your's is next!",2] master=Tk() form.draw(master) master.mainloop() = How should I do this, I had worked around the problem by destroying the window and building it again, but it was pointed out that I have an unusual coding style doing this. All hints appreciated! Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter code executes before function returned
On 15/04/18 18:10, Alan Gauld via Tutor wrote: On 15/04/18 03:57, Chris Roy-Smith wrote: I am trying to get tkinter to return a number from a window, which then sets how many times to print a sign. I don;t jhave time to look at this in detail just now, maybe later. But first impressions is that you have a very unorthodox style of Tkinter programming. Its more traditional to build the entire GUI up front rather than creating and destroying widgets each time you execute an event handler. Its less disturbing to the user than having things appear/disappear etc, as you seem to be doing. You can make widget hide/show/deactivate themselves without destroying them just by withdrawing/unpacking them etc or changing their status, if that's really what you want to do. The code does not wait till the function returns a value, resulting in the signcount variable in having a None value, giving an output like below. I'll look at this a bit more closely later if nobody else answers by then... This is where you call your function. Looking at it quickly I think you would be as well using the standard Tkinter simpledialogs/messagebox modules to get user input. Have you looked at the simpledialogs? Thank you Alan, I didn't know of simpledialogs. That was all I needed to search documentation for these. I have now achieved what I was trying to do, with user interface as I was planning. Or better still having a static entry field on your GUI and just reading that? I'll have to figure out how to achieve that! Perhaps my intended design is not in line with modern styles? Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter code executes before function returned
On 15/04/18 23:36, Alan Gauld via Tutor wrote: On 15/04/18 14:24, Alan Gauld via Tutor wrote: OK, I've had a closet look now and can confirm the A closer look! Not a closet look. Ooops! :-/ Thank you Alan, I have even more to learn than I thought. I have been bashing away at several OOP tutorials, but the penny still hasn't dropped on making that work yet, I get the concept, but don't seem to understand how to make it work for methods. Events just add to my lack of understanding. I'll have to try your tutorial. Hopefully I won't have too many questions after that. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] tkinter code executes before function returned
Hi, System: Python 3.6, Ubuntu Linux 17.10 I am trying to get tkinter to return a number from a window, which then sets how many times to print a sign. The code does not wait till the function returns a value, resulting in the signcount variable in having a None value, giving an output like below. Note that the output "line 64 ### The required number of signs is 5 ###" only occurs after a number is input. I can use an input statement to get the desired output, but that's not good having to go to the terminal to enter the response. How can I get the printSign code to wait till getcount() returns it's value? Any help greatly appreciated. Regards, Chris Roy-Smith chris@chris-X451MA:~/Scripts/python3/dvms$ ./debug1.py line 27 ### required sign count for D is None ### Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__ return self.func(*args) File "./debug1.py", line 28, in printSign for x in range(signcount): TypeError: 'NoneType' object cannot be interpreted as an integer line 64 ### The required number of signs is 5 ### Code: #!/usr/bin/python3 from tkinter import * import os from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas from reportlab.lib.utils import ImageReader def printSign(): global gc, packages, rows myCanvas = canvas.Canvas("Signs.pdf", pagesize=A4) width, height = A4 #keep for myCanvas.rotate(90) myCanvas.setFillColorRGB(0,0,0) myCanvas.setFont("Helvetica-Bold", 400) TopMargin=-20 LeftMargin=1 Width=14 Height=19 VertPos=-15 Bottom=-1 a=[" " for i in range(rows)] i=0 sign=0 for line in packages: signcount=getcount(line[1]) print('line 27 ### required sign count for {} is {} ###'.format(line[1], str(signcount))) for x in range(signcount): #draw rectangle myCanvas.rect(LeftMargin*cm+Width*sign*cm, TopMargin*cm, Width*cm, Height*cm, stroke=0, fill=1) myCanvas.drawCentredString((LeftMargin+(0.5*Width))*cm+(Width*sign)*cm, VertPos*cm, line[0]) if sign==1: myCanvas.showPage() sign=0 myCanvas.rotate(90) i+=1 else: sign+=1 i+=1 myCanvas.showPage() myCanvas.save() if os.name == "posix": os.popen("evince %s" % ("Signs.pdf")) if os.name == "nt": os.startfile('Signs.pdf') def getcount(SignText): global gc,e gc=Toplevel(master) MsgText='How many copies of {} do you want to print?'.format(SignText) Label(gc, text=MsgText).grid(row=0, column=0, sticky=(W,E)) e = Entry(gc) e.grid(row=0, column=1) Button(gc, text='Okay', command=ReturnCount).grid(row=1, column=0, sticky=(W,E)) Button(gc, text='Cancel', command=gc.destroy).grid(row=1, column=1, sticky=(W,E)) def ReturnCount(): global gc,e b0=e.get() if b0 == None: b0=0 gc.destroy() print('line 64 ### The required number of signs is {} ###'.format(b0)) return b0 master = Tk() master.title("Testing") packages = [[0,'D','drill'],[1,'J','Jointer'],[2,'B','Bandsaw']] rows = 3 b2 = Button(master, text="Print Signs", command=printSign).grid(row=4, column=0, sticky=(W,E), padx=5, pady=5) b3 = Button(master, text="Quit", command=master.destroy).grid(row=4, column=3, sticky=(W,E)) master.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] thinter: can't figure out how to update a window instead of creating a new on
Hi, system: Python 3.6, LInux I have been playing around with the following code which I want to update the window, but I creates a new window (with the correct display), but I have not been able to find the solution. Perhaps I'm using the wrong key words in my searches. Thank you for any assistance, I'm hoping to learn something from this experience Regards, Chris Roy-Smith #!/usr/bin/python3 import mysql.connector from tkinter import * import pickle master = Tk() def getCfg(): fobj = open('members.pkl', 'rb') cfg = pickle.load(fobj) fobj.close() return cfg def editmember(page=1): form=Toplevel(master) form.title('test form') cfg=getCfg() QrySelectMembers='select ident, concat_ws(" " ,`given`, `surname`) as `fullname` from `details` where 1 order by `surname` asc, `given` asc limit '+str(page)+', 10' db=mysql.connector.connect(user = cfg['user'], password = cfg['password'], database = cfg['database']) cursor=db.cursor() cursor.execute(QrySelectMembers) #,(page)) MemberList=list(cursor) cursor.close() db.close ro=0 for Member in MemberList: ident=Member[0] msg='edit '+Member[1] Button(form, text=msg, command= lambda tmp=ident : EdForm(tmp)).grid(sticky=(W, E), row=ro, column=0) ro+=1 Button(form, text='exit', command=form.destroy).grid(row=ro+1, column=2) Button(form, text='next 10', command= lambda p=page+10 : editmember(p)).grid(row=ro, column=1) Button(form, text="previous 10", command= lambda p=page-10 : editmember(p)).grid(row=ro, column=0) Button(master, text='click to test', command=editmember).grid(row=0, column=0) Button(master, text='quit', command=master.destroy).grid(row=1, column=0) master.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble using tkinter CheckButton
On 16/01/18 22:35, Alan Gauld via Tutor wrote: On 16/01/18 04:37, Chris Roy-Smith wrote: File "./debugString.py", line 7, in SetFin SetStatus[x] = var.get(x) AttributeError: 'list' object has no attribute 'get' var=[IntVar() for x in range(8)] Here you create a list of IntVar objects. The list has no get() method - just as the error message says. You need to access the individual IntVar for your widget. I suspect you want SetStatus[x] = var[x].get() Yes, Thank you, that was the problem. other problems in my code, after correcting the get() were easy to sort out. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] trouble using tkinter CheckButton
Hi, I'm a relative newcomer to object oriented programming. Operating system Linux (ubuntu 17.10) Python version 3.6 With the code below, when I click on the "list set & unset" button I get the following error. This code is my attempt at debugging a bigger program. I have broken things down to what I think is as simple as I can get. Thank you for looking at this, Regards, Chris Roy-Smith Error message: ===== chris@chris-X451MA:~/Scripts/python3/dvms$ ./debugString.py Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__ return self.func(*args) File "./debugString.py", line 26, in Button(cmember, text='list set & unset',command= lambda lines = x : SetFin(lines) ).grid(row=x, column=2) File "./debugString.py", line 7, in SetFin SetStatus[x] = var.get(x) AttributeError: 'list' object has no attribute 'get' #!/usr/bin/python3 from tkinter import * def SetFin(lines): SetStatus=[" " for i in range(lines)] for x in range(lines): SetStatus[x] = var.get(x) print (SetStatus(x)) master = Tk() NameList=[(1, 'Vivian', 'Blackwell'), (2, 'Peter ', 'Bromell'), (3, 'Nev', 'Casey'), (4, 'Claude', 'Chatwin'), (5, 'John ', 'Dennison'), (6, 'Nicolene', 'Fairbrass'), (7, 'Paul', 'Fairbrass')] #in real situation this comes from a database and is of variable length cmember=Toplevel(master) x=0 y=0 var=[IntVar() for x in range(8)] for line in NameList: for field in line: Label(cmember, text=field).grid(row=x, column=y) y+=1 #make checkbox cb=Checkbutton(cmember, text='set', variable=var[x]).grid(row=x, column=y) y=0 x+=1 Button(cmember, text='list set & unset',command= lambda lines = x : SetFin(lines) ).grid(row=x, column=2) Button(cmember, text='exit', command=cmember.destroy).grid(row=x, column=4) mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with program in python in easy steps
i wrote these programs and saved them per instructions on page 128 and 129 in the book "python in easy steps". class Person: '''A base class to define Person properties.''' def__init__(self,name): self.name = name def speak( self,msg = '(Calling The Base Class)'): print(self.name,msg) from Person import* '''A derived class to define Man properties.''' class Man(Person): def speak(self,msg): print(self.name,':\n\tHello!',msg) from Person import* '''A derived class to define Hombre properties.''' class Hombre(Person): def speak(self,msg): print(self.name,':\n\tHola!',msg) from Man import* from Hombre import* guy_1 = Man('Richard') guy_2 = Hombre('Ricardo') guy_1.speak('It\'s a beautiful evening.\n') guy_2.speak('Es una tarde hermosa.\n') Person.speak(guy_1) Person.speak(guy_2) i ran the program override.py and get this error message: Traceback (most recent call last): File "scripts/override.py", line 1, in from Man import* File "/home/chris/scripts/Man.py", line 2 '''A derived class to define Man properties.''' ^ IndentationError: unexpected indent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems using a listbox
On 17/10/17 20:13, Peter Otten wrote: #!/usr/bin/python3 #test listbox from tkinter import * class Dialog(Frame): def __init__(self, master): Frame.__init__(self, master) self.list = Listbox(self, selectmode=EXTENDED) self.list.pack(fill=BOTH, expand=1) self.current = None self.poll() # start polling the list def poll(self): now = self.list.curselection() if now != self.current: self.list_has_changed(now) self.current = now self.after(250, self.poll) def list_has_changed(self, selection): print ("selection is", selection) snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry') master = Tk() dialog = Dialog(master) dialog.pack() for item in snames: dialog.list.insert(END, item) mainloop() Thank you, that works, I have difficulties with object oriented coding. Never used a language where I needed it. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] problems using a listbox
Hi, OS: Linux Chris-X451MA 4.4.0-97-generic #120-Ubuntu SMP Tue Sep 19 17:28:18 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux Python 3.5.2 (default, Sep 14 2017, 22:51:06) I am trying to learn how to use a tkinter listbox. When I execute my experimental code, an odd index is printed immediately (output below code), index looks wrong (shouldn’t it be an integer). Also it doesn't print new values when I select an entry. --- #!/usr/bin/python3 #test listbox from tkinter import * class Dialog(Frame): def __init__(self, master): Frame.__init__(self, master) self.list = Listbox(self, selectmode=EXTENDED) self.list.pack(fill=BOTH, expand=1) self.current = None self.poll() # start polling the list def poll(self): now = self.list.curselection() if now != self.current: self.list_has_changed(now) self.current = now self.after(250, self.poll) def list_has_changed(self, selection): print ("selection is", selection) snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry') master = Tk() listbox = Listbox(master) listbox.grid(row=0) for item in snames: listbox.insert(END, item) myindicator=Dialog.list_has_changed(master, listbox) mainloop() - output: --- ./listbox.py selection is .140537834621024 Thank you for any help Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Tree again: iterator, yield, increase (treelib)
All, I've a question about treelib library from pip. Treelib stores a tree and offers functions to add, delete or move nodes. Furthermore, you can print a tree like this: Harry ├── Harry2 ├── Harry3 ├── Harry4 └── Jane ├── Jane2 │ ├── Jane2.1 │ │ └── Jane2.1.1 │ ├── Jane2.2 │ └── Jane2.3 └── Jane3 I'm trying to understand how the print function is working. 1. The documentation [2] says, you have to call tree.show() to print the tree above. 2. tree.show calls the self__print_backend(...) 3. It seems that nid is initialized in get_iter, Line 218 [1] 4. nid is passed as parameter to __get_iter and the other participating funtions 5. the node with the id nid is fetched in line 222. 6. In Line 190 there's a loop. I don't understand what increments nid or what makes the __get_iter function loop through the self._nodes dictionary defined in Line 106? Couldn't the __get_iter function iterate another list or dictionary? Which line says that you want to get every Node in self._nodes? Thank you in advance! - Chris [1] https://github.com/caesar0301/treelib/blob/master/treelib/tree.py [2] http://treelib.readthedocs.io/en/latest/examples.html#basic-usage ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with program
just learning python as my first programming language. going through the book "python in easy steps" by mike mcgrath. i am going through the programs in chapter 7 and can't get them to work. here is the first one in the chapter: class Bird: '''A base class to define bird properties.''' count=0 def_init_(self,chat): self.sound=chat Bird.count+=1 def talk(self): return self.sound from Bird import* print('\nClass Instances Of:\n',Bird._doc_) polly=Bird('Squawk,squawk!') print('\nNumber Of Birds:',polly.count) print('Polly Says:',polly.talk()) harry=Bird('Tweet,tweet!') print('\nNumber Of Birds:',harry.count) print('Harry Says:',harry.talk()) i am getting this error message: File "scripts/bird.py", line 4 def_init_(self,chat): ^ SyntaxError: invalid syntax what am i doing or not doing that is causing this? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Directory Structure
Thank you for your detailed reply! I've tried to explain in my mails to Alan and Mats what I'm trying to achieve. On Sat, 30 Sep 2017 11:32:57 +1000 Steven D'Aprano <st...@pearwood.info> wrote: > On Fri, Sep 29, 2017 at 07:02:07PM +0200, Chris wrote: > > > Background: Maildirs with mails older than five years should be > > archived. The folder structure should be kept in the target. > > Archived to what? A separate Maildir on tape. > > I was very surprised, that there seems no readily usable module > > available. (In Perl neither). > > Reusable module to do what *precisely*? If you cannot explain what > you need, how do you expect somebody to have anticipated your > requirements and written a module to do it? Represent the structure in memory. > > What's the best way to save them? > > Depends on what you are doing. But coding the paths in your source > code is almost certainly not what you want to do. Surely you want to > read the paths from the maildir itself, as it *actually* exists, > rather than try to hard-code what you expect it to be in your source > code? Well, if I had the structure in memory, I could save additional information and could print different lists, e.g. sorted by attachment size, sorted by project. A project can appear in different places in the tree. > Have you looked at the contents of a maildir? Its actually an almost > flat structure. Nested mail folders are not nested on the disk: a > user's mail folder structure that looks like: > > inbox > sent > trash > personal > ├── family > └── friends > work > ├── critical > ├── important > └── low > > > is stored on disk as: > > Maildir/ > ├── .sent/ > ├── .trash/ > ├── .personal/ > ├── .personal.family/ > ├── .person.friends/ > ├── .work > ├── .work.critical > ├── .work.important > └── .work.low Good objection. You can make dovecot use the first layout on disk. Probably not a gain in disguise. > So all you really need is to record the path to the top level maildir > directories (the original, and the place where you are archiving > them). The subdirectories, you read from the disk as you go. Ok, I could even do this with the first structure. > Actually, *you* don't read them at all. Have you looked at the > mailbox module in the standard library? It supports Maildir. I expect > that what you would do is something like: > > source = Maildir('path/to/source') > archive = Maildir('path/to/archive') > for each directory in source: > for each mail in directory: > if mail older than five years: > copy mail to archive > delete mail from source I've used os.walk. I'll have a look at the Maildir library. - Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Directory Structure
On Fri, 29 Sep 2017 12:16:11 -0600 Mats Wichmann <m...@wichmann.us> wrote: > It's not clear what you're really looking for... Sorry. Tried to ask more precisely in my reply to Alan. > File/directory usage is really an OS-specific thing, and most of the > functionality you want seems like it would be in the os module. > Have you looked at functions like os.renames() and os.makedirs()? Sure, but I'd like to know how to represent the directory structure in my script. Finding (os.walk) and copying the mails is not the problem. > Do you need something much more complicated than that? Well, I just like to know how to do that. Of course, I can find the mails with os.walk and move them. Create the necessary directory structure with something like mkdir -p. That's no problem. But when I want to print a list for example, I have to keep the structure, because folders have different meanings depending where they're in the tree. - Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Question Regarding the Documentation Format
On 23 September 2017 at 15:15, Prateek <prateek...@gmail.com> wrote: > input(...) > input([prompt]) -> string > > I want to know what the significance of "-> string". I have tried > consulting several books but none of them gave me a clear-cut explanation > for this. This indicates the return type: input() returns a string. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess.getstatusoutput : UnicodeDecodeError
On 22 September 2017 at 03:57, Evuraan <evur...@gmail.com> wrote: >>>> result = subprocess.run(["tail", "-400", "/tmp/pmaster.txt"], >>>> stdout=subprocess.PIPE) >>>> result.returncode > 0 >>>> subprocess.getstatusoutput("file /tmp/pmaster.txt",) > (0, '/tmp/pmaster.txt: Non-ISO extended-ASCII text, with very long > lines, with LF, NEL line terminators') >>>> You’re still using the deprecated function. >>> subprocess.run(['file', '/tmp/pmaster.txt'], stdout=subprocess.PIPE) CompletedProcess(args=['file', '/tmp/pmaster.txt'], returncode=0, stdout=b'/tmp/pmaster.txt: Non-ISO…\n') >>> result = _ # underscore means result of previous line in interactive mode >>> result.stdout b'/tmp/pmaster.txt: Non-ISO…line terminators\n' >>> result.returncode 0 And if you want to get a Unicode string (if output of command is your system encoding, hopefully UTF-8): >>> subprocess.run(['file', '/tmp/pmaster.txt'], stdout=subprocess.PIPE, >>> universal_newlines=True) CompletedProcess(args=['file', '/tmp/pmaster.txt'], returncode=0, stdout='/tmp/pmaster.txt: Non-ISO…\n') >>> (_.stdout is an unicode string) Also, going back to your original example: you should not be using `tail` from within Python. You should not depend on tail being available (it’s not on Windows), and there may also be version differences. Instead of tail, you should use Python’s standard file operations (open()) to accomplish your task. [advertisement] Extra reading on security (shell=False) and the necessity of calling subprocesses: https://chriswarrick.com/blog/2017/09/02/spawning-subprocesses-smartly-and-securely/ [/advertisement] -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How is database creation normally handled?
On 10 September 2017 at 02:29, boB Stepp <robertvst...@gmail.com> wrote: > While reading about SQL, SQLite and the Python module sqlite3, it > appears that I could (1) have a program check for the existence of the > program's database, and if not found, create it, make the tables, > etc.; or, (2) create the database separately and include it with the > program. What are the pros and cons of each approach? (1) to me > looks only helpful if I wish to write a program that might want to > allow the user to have multiple databases. But this sounds like a lot > of extra coding and checking to make it work well. But if I only wish > to have a single database, then (2) sounds like the approach to use. > I would create the database, populate it with the needed empty tables > with the desired fields, making it ready to use by the program's user. > > Not having any experience in the database arena, I'm not even sure I > know how to properly think about this. A separate database creation script will be better. It’s good to separate the logic of your app and configuration/setup — just like you shouldn’t be “helpfully” installing dependencies when someone runs your script. For a good approach, look at Django: every app (sub-package of a site) has its own set of migrations. Migrations are responsible for creating tables, and more importantly — for updating them. Because you will need to make changes to your original DB structure throughout the lifetime of your software. I built a small Django app over the weekend, and I’ve created 10 migrations throughout the process¹, and that will probably be true of your project. Now, if those migrations would have to go to the main codebase instead of a side directory, it would be a burden to maintain. If there were no migration frameworks, I’d have to include something like “run this SQL to upgrade your DB when upgrading from version 0.1.0 to 0.1.1”, which is even less fun. So, when I make some change to my models.py (which has the database schema), I can just run: ./manage.py makemigrations ./manage.py migrate and my database will be magically updated, hassle-free and I don’t even have to look at the auto-generated code. (If you are writing a web app: do look at Django! If you aren’t: Alembic does the same thing for SQLAlchemy. Something for plain sqlite3 may or may not exist.) ¹ Progressive enhancement: adding more features that need extra columns I didn’t think of first. Or removing features that weren’t cool. Or restoring them the next day. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
On 6 September 2017 at 08:39, edmundo pierre via Tutor <tutor@python.org> wrote: > Hi Python, > I am trying to make a french to English dictionary. First of all, I made a > dictionary with keys and values. Then I asked the user to enter a letter. If > the letter correspond to the Keys, my print function should display the Key > and value. But my code below, could not . Thank you! > > List ={"le":"…"} (it”s called dict, or dictionary, and “List”/“dict” are not good variable names) > keys = List.keys()print(keys) > a = str(input("")) > if 'a' in keys:print(a + ":"+ List['a'])else:print("impossible") You’re trying to find the letter 'a' and print it, you aren’t using the variable a. Don’t put it in quotes. So, do it like this: data = {"le": "…"} print(data.keys()) search_key = str(input("> ")) if search_key in data: print(search_key, ":", data[search_key]) else: print("Not in dictionary.") (I also cleaned it up a little) -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3 for Beginners was: (Re: intro book for python)
On 3 September 2017 at 12:02, Leam Hall <leamh...@gmail.com> wrote: mmend anything from the author of LPTHW after he had the >> audacity to write this https://learnpythonthehardway.org/book/nopython3.html >> about Python 3, in addition to which there are several vastly superior books >> and/or tutorials anyway. >> >> Kindest regards. >> >> Mark Lawrence. > > > There are lots of other books on Python, that's true. "Practical > Programming" (Gries, Campbell, Montojo) is one I use. > > Are you going to toss "Learning Python" since Mark points out some of > python's drift from it's core values? > > I appreciate that link. Zed's right. Many of Zed’s argument are false and plain BS: https://eev.ee/blog/2016/11/23/a-rebuttal-for-python-3/ > Python 3 isn't used by the OS tools on Red Hat, and that's that major Linux > vendor in the US. This will change in RHEL 8, whenever that comes out: yum was replaced by dnf a few versions of Fedora ago, and that’s written in Python 3. > Anyone that uses python on Linux has to use Python 2. That means Python 3 is > just one more language that requires work to install and maintain. I'm not > seeing the benefits. How long has Python 3 been out? How many others are > seeing the benefits of total change? When will people who say "you should > upgrade" realize it's weeks or months of work with no real reason to do so? You’re getting: sane Unicode support, f"strings", type hinting, pathlib, asyncio, and a few more improvements. > Yesterday I was coding and had to work around Python 3 dict.keys() returning > a "dict_keys" type vs a list. Why did we need another type for this? I'm a > coding beginner. Performance and resource usage. If you use a list, Python needs to do some extra work to convert internal data structures of a dict into a list, and also store that new list in memory. > I can talk a decent game in a few languages like python but > I'm not experienced enough or smart enough to deal with these sorts of > problems easily. Returning a new type, without significant benefit, makes it > harder for people to progress in the language. There are a lot of things that return iterators or other fancy types instead of lists in Python 3 (eg. zip, range, all of itertools). You can always iterate over those like you would, and if you need a list for some reason, you can just call list(the_thing). > Some years ago I wanted to play with an IRC bot sort of thing. Someone on > Freenode #python mentioned Twisted so I got that and started playing. Half > an hour, maybe forty five minutes later and my little project did what I was > trying to do. This was before I really knew any python; the language was > that clean and easy to learn. You can still do that with Python 3. (Although you’ll be better off using asyncio and some IRC lib for that.) -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] intro book for python
I would recommend reading the official Python tutorial [0] This tutorial will explain the important parts of Python. It doesn’t spend too much time explaining programming basics though. My alternate recommendations include Think Python [1] or Automate the Boring Stuff with Python [2]. On 1 September 2017 at 19:51, Raghunadh <raghunadhpra...@gmail.com> wrote: > Hello Derek, > > I would start with this book > > hxxps://learnpythonthehardway.org > > Raghunadh LPTHW is a terrible book: slow and boring, tells readers to memorize truth tables instead of understanding them (sic!), 19% of it is thoughtlessly teaching print() — overall, a failure at teaching people to program. Moreover, the author wrote a nonsensical essay bashing Python 3 [3] (debunked in [4]), and released a Python 3.6 version of his book shortly afterwards. [0] https://docs.python.org/3/tutorial/index.html [1] http://greenteapress.com/wp/think-python-2e/ [2] https://automatetheboringstuff.com/ [3] https://learnpythonthehardway.org/book/nopython3.html [4] https://eev.ee/blog/2016/11/23/a-rebuttal-for-python-3/ -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Percentage of installations without setuptools (Was if __name__=='__main__' ...)
On 11 August 2017 at 19:54, Mats Wichmann <m...@wichmann.us> wrote: > On 08/11/2017 09:54 AM, Alan Gauld via Tutor wrote: >> On 11/08/17 13:35, Thomas Güttler wrote: >> >>> I guess most python installations have setuptools. >> >> I guess so too, although I don't know. >> Those that don't are probably in one of two categories >> a) people who just downloaded Python and never installed >>anything else False since Python 3.4/2.7.9. ensurepip installs Python on every new Python install. > Most Linux distributions choose to make it a separate package. I have > it (them - one for Py2 and one for Py3) installed everywhere, but I'd > guess it's not a default install then. > > Fedora: > python2-setuptools-36.2.0-1.fc26.noarch > python3-setuptools-36.2.0-1.fc26.noarch > > Ubuntu: > Desired=Unknown/Install/Remove/Purge/Hold > | > Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend > |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) > ||/ Name Version Architecture Description > +++-=---= > ii python-setuptools 33.1.1-1 all Python Distutils > Enhancements > ii python3-setuptools33.1.1-1 all Python3 Distutils > Enhancements On Fedora, setuptools is mandatory: package: python3-3.6.2-1.fc26.x86_64 [snip some unrelated stuff] dependency: python3-pip provider: python3-pip-9.0.1-9.fc26.noarch dependency: python3-setuptools provider: python3-setuptools-36.2.0-1.fc26.noarch On other distributions, it usually isn’t, although many users will eventually end up with a copy. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
On 9 August 2017 at 23:15, Steven D'Aprano <st...@pearwood.info> wrote: > On Tue, Aug 08, 2017 at 12:56:56PM +0200, Chris Warrick wrote: > >> While setuptools is not officially part of the stdlib, > > This is the critical factor. How can you use *by default* something that > is *NOT* supplied by default? > > Obviously you cannot. It is physically impossible. The problem with setuptools (and pip) is that they are not first-party stdlib members, but they are not third-party packages either. They’re somewhere in between. They have been blessed by the core developers. And yes, setuptools might be in all the places you mentioned: > But this does NOT hold for everyone, possibly not even for the majority > of Python users. For example: > > - students using their school's computers; > > - corporate and government users using a SOE (Standard Operating > Environment); > > - people using a system where, for policy reasons, only the > standard library is permitted. * If those computers run Windows (as they often do) and run a recent Python version (3.4 or newer/2.7.9 or newer), setuptools will be installed, unless the IT people explicitly disabled ensurepip. * On macOS, setuptools will be installed if they’re using the system Python, the python.org installers (which are not uninstallable), or Python from Homebrew. The last two also have pip, and system Python has ensurepip. * On Linux, setuptools/pip is likely to be there, but it’s not required in all distributions. (Fedora mandates setuptools; Debian even rips out ensurepip by default and hides it in python3-venv because reasons…) If the users are meant to install Python packages, their system administrators would take care of that — either by setting up setuptools/pip and perhaps virtualenv, or taking install requests from users. If users are not supposed to be running setuptools/pip, they probably shouldn’t, but they can still install it from ensurepip or downloading get-pip.py. > I've worked in places where installing unauthorized software was a > firing offence. Those people don’t need setuptools. Those people should not be using distutils either. They might not even be allowed to download packages and run __main__.py without installation. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
On 8 August 2017 at 03:30, Ben Finney <ben+pyt...@benfinney.id.au> wrote: > Thomas Güttler <guettl...@thomas-guettler.de> writes: > >> Why is "the sane default is 'use console_scripts entry-point in >> setup.py'" not a good answer? > > Because third-party Setuptools is required for entry points, which means > entry points cannot be a default choice. > > It may well be a good choice for many cases. But that's a different > matter from it being a good *default* choice; it can only be a default > choice if it's in the standard library. While setuptools is not officially part of the stdlib, it *is* recommended by the official documentation, the dev team, and it’s available pretty much everywhere. setuptools can’t be in stdlib, because it’s moving too fast for stdlib to keep up. Look here: http://pythonwheels.com/ — 254 of the top 360 packages on PyPI use wheels. It means that at least that many use setuptools; sometimes with a distutils fallback, but often without one. Moreover, many of the packages without wheels use setuptools as well. The sane default choice is entry_points. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
On 4 August 2017 at 12:15, Thomas Güttler <guettl...@thomas-guettler.de> wrote: > Chris wrote "Simple: `scripts` are legacy." > > You say it is the standard, and console_scripts is from a third party. > > For me "legacy" sound like "don't go this old way". > > For me "third party" sounds like "don't go this way, stick to the standard". > > I feel stupid since I have no clue. The official docs recommend distutils: https://docs.python.org/2/library/distutils.html > Most Python users will not want to use this module directly, but instead use > the cross-version tools maintained by the Python Packaging Authority. In > particular, setuptools is an enhanced alternative to distutils that provides: > [snip] > * the ability to declare project “entry points”, which can be used as the > basis for application plugin systems > * the ability to automatically generate Windows command line executables at > installation time rather than needing to prebuild them And, as eryk sun mentioned, recent Python 2.7 and 3.4 versions ship setuptools and pip, via the ensurepip module. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?
On 3 August 2017 at 09:52, Thomas Güttler <guettl...@thomas-guettler.de> wrote: > > > Am 02.08.2017 um 18:06 schrieb Wolfgang Maier: >> >> On 08/02/2017 04:57 PM, Steven D'Aprano wrote: >>> >>> On Wed, Aug 02, 2017 at 10:48:39PM +1000, Ben Finney wrote: >>>> >>>> Thomas Güttler <guettl...@thomas-guettler.de> writes: >>>> >>>>> Maybe I am doing something wrong. I was proud because I did use >>>>> “console_scripts” entry points. >>>> >>>> >>>> Did someone lead you to believe it was wrong? Setuptools console_scripts >>>> entry points are a good tool. >>>> >>>> My point was that it is an *advanced* tool, difficult to use and also >>>> difficult to explain because the concepts are advanced. >>> >>> >>> Can you explain the use-case for when somebody might want to use >>> console_scripts entry points? >>> >>> I have a module with a main() function and an "if __name__ == ..." >>> guard. Under what circumstances is that not sufficient, and I would want >>> console_scripts? >>> >> >> If you install things using pip/setuptools and have defined a >> console_scripts entry point for it, then the corresponding wrapper >> script will be installed in whatever is considered the scripts directory >> at install time on that machine. With a bit of luck the entry point will >> thus be executable directly without any end-user intervention (like >> adding folders to $PATH and chmodding files). >> Personally, I always found it straightforward to write the wrapper >> script myself, then define this as a 'scripts' file in the package >> layout of my setup.py, but people's MMV. > > > > I was not aware of "scripts" in setup.py. But I found docs: > > http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html > > Why are there two ways: "script" vs "console_scripts entry-point"? Simple: `scripts` are legacy. `entry_points` are the new thing. There’s also a third approach: gui_scripts entry_points, which work the same way on Linux/*nix, but on Windows, it means that running your script by opening the created .exe files does not show a console window. Note that stdout/stderr do not work in that mode under Windows, which can lead to spurious application crashes. (GUI-only processes cannot use stdout/stderr because they don’t have a console attached) I’ll take the liberty to link my (better) blog post about this: https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/ -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?
On 1 August 2017 at 16:54, Thomas Güttler <guettl...@thomas-guettler.de> wrote: > I have a friend who is a talented shell script writer. He is a linux guru > since > several years. > > He asked me if "if __name__=='main':" is state of the art if you want > to translate a shell script to python. > > I started to stutter and did not know how to reply. > > I use Python since several years and I use console_script in entry_points of > setup.py. > > I am very unsure if this is the right way if you want to teach a new comers > the joy of python. > > In the current context we want to translate a bunch of shell scripts to > python scripts. > > What do you think? > > Regards, > Thomas Güttler > > > -- > Thomas Guettler http://www.thomas-guettler.de/ > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Do both. If you’re making a package, create a __main__.py file as well so your package is usable with `python -m somepackage`. On the other hand, if you’re making things more akin to shell scripts, using just entry_points makes stuff harder, because you need to install the code (and write a setup.py), as opposed to just putting the script somewhere in $PATH. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommended Python Compiler
On 31 July 2017 at 14:45, Wolfgang Maier <wolfgang.ma...@biologie.uni-freiburg.de> wrote: > On 07/31/2017 03:31 AM, Mats Wichmann wrote: >> >> since this all opinions :), I don't think idle is worth bothering with. >> for editor that can do ide like things, consider atom (free, get a bunch of >> plugins) or sublime text (not free). for a full ide, pycharm is great >> (community edition free). for a lightweight ide to get started, i liked >> thonny when i trialed it at somebody's request, but do look at that wiki >> page, tons of choices there. > > > As you're saying, it is all about opinion here so let me defend IDLE here. > There may be more powerful IDEs than IDLE, but it takes you a long way (far > beyond beginner/scripting level) and, of interest if you are ever writing > Python code on a Windows machine, typically comes installed together with > the Python interpreter there, so you will find it on many machines (even > ones you are not allowed to install other software on). IDLE is one step up from Notepad. Which makes it a pretty terrible editor. It even lacks line numbers, which is an elementary feature, and a necessity for debugging (tracebacks!) On the other hand, some of the better editors (eg. Visual Studio Code) provide .zip packages that do not require installation and can even run off a USB stick. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can a virtual environment be renamed?
On 16 April 2017 at 18:16, Jim <jf_byr...@comcast.net> wrote: > On 04/16/2017 10:10 AM, Chris Warrick wrote: >> >> On 16 April 2017 at 16:45, Jim <jf_byr...@comcast.net> wrote: >>> >>> My system python is 2.7.12 so I created a virtual environment using venu >>> to >>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and >>> put it in env36. Is it possible to change env to env35 for 3.5.2 without >>> breaking things? >> >> >> No. You need to delete your existing virtualenv and create a new one. >> You can just use `pip freeze > requirements.txt` in the old one and >> run `pip install -r requirements.txt` in the new one to ”move” all the >> packages you had. >> >> > > Thanks Chris. I thought that would be the answer but wanted to check before > I spent a lot of time trying to do something that was not possible. > > Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12 > & 3.5.2 installed. So I would have to download a tar file of 3.6, then build > it and then use it's version of venv to create a virtual environment to try > 3.6. Is that correct? Yes, you need to install the appropriate interpreter first, and likewise a virtualenv won’t work if you uninstall an interpreter/upgrade it to a new minor version*. You might not need to use the source tarball if https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes works on Mint (and if you do use tarballs, make sure to install somewhere in /opt or whatever not to make a mess — it’s easy to break your OS if you’re not careful) * eg. 3.5 → 3.6. Won’t ever happen on Mint or other “friendly” distros, unless you do a dist-upgrade. Happens pretty often on rolling-release distros or macOS with homebrew. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can a virtual environment be renamed?
On 16 April 2017 at 16:45, Jim <jf_byr...@comcast.net> wrote: > My system python is 2.7.12 so I created a virtual environment using venu to > run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and > put it in env36. Is it possible to change env to env35 for 3.5.2 without > breaking things? No. You need to delete your existing virtualenv and create a new one. You can just use `pip freeze > requirements.txt` in the old one and run `pip install -r requirements.txt` in the new one to ”move” all the packages you had. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Problem with code interating thri a list
Hello Everyone, I have been practicing with strings. Splitting them, joining them, changing case. All has been going well but came across a exercise in one of the code practice sites that has you changing the case of different characters in a string. Anything in upper case is converted to lower case and anything in lower case is converted to upper. The solution I have created seems to work but I have not been able to figure out how to join the string back together. String I'm using is "This Is A Test!" to be changed to "tHIS iS a tEST!". My Logic: Since a string is immutable, I converted it to a list to separate out the characters and keep them in order. Idea is to change the case of the characters in the list then run a join to convert it back to a string. Can you point me in the right direction? the print statements in the code are for my debugging and will be removed in the end. Python 3.5.1 on Windows 10.- # Create a function that will take a string and change the upper case characters to lower # and the lower case characters to upper. # Create a function. def convert(text): print(text) text = list(text) # Convert string to a list to separate/split characters and maintain order. print(text) # Check case and convert to opposite case. for item in text: if item == item.lower(): item = item.upper() print(item) else: item = item.lower() print(item) # Convert list back into string with .join. result = "".join(text) print() print(result) return result # Call the function print(convert("This Is A Test!")) ----- Thanks,Chris Clifton ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Adding to a dict through a for loop confusion.
Thank you so much for the help, and the example! So, by putting quotes around a dict key, like so dict["key"] or in my case cart["item"] this makes the dict have ONE key. The loop assigns the cart_items to this ONE key until the end of the loop, and I'm left with {'item': 5}. . . Where as if you do NOT put the key in quotes, dict[key] or cart[item], this basically means the dict has as many keys as you're iterating through. In other words it assigns the cart_item as a key and a value, and saves them all to the dict. Is that correct? On Tue, May 17, 2016 at 5:01 AM, <c...@zip.com.au> wrote: > On 17May2016 04:28, Chris Kavanagh <cka...@gmail.com> wrote: > >> Could someone tell me why this different behavior occurs between these 2 >> code snippets, please. The 1st example has quotes around it ['item'] only >> adds the last item to the dict (cart). In the 2nd example the item does >> not >> have quotes around it [item] and every entry is added to the dict. >> >> Why? >> > [...] > >> # Example #1 >> cart_items = ['1','2','3','4','5'] >> cart = {} >> for item in cart_items: >>cart['item'] = item >> > > This for loop assigns the values '1','2','3','4','5' in succession to the > variable named "item". Then the body of the loop assigns that value (via > the variable "item") to the single dictionary slot with the fixed key with > string value 'item' i.e. always the same slot. And the last item is the > one kept. All the earlier assignments are overwritten by the later ones: > they happen, but are replaced. > > print cart >> #output >> {'item': 5} >> > > Which you see above. > > # Example #2 >> cart_items = ['1','2','3','4','5'] >> cart = {} >> for item in cart_items: >>cart[item] = item >> > > Here, the variable named "item" takes on the values as before, but the > diction slot chosen also comes form that variable. So each value ends up in > its own slot as your output shows. > > print cart >> # output >> {'1': '1', '3': '3', '2': '2', '5': '5', '4': '4'} >> > > The essential difference here is that in the first example the expression > for the slot in the dictionary is the expression: > > 'item' > > which is simply the fixed string 'item'. In the second example the > expression is: > > item > > which produces the current value stored in the variable "item". > > Cheers, > Cameron Simpson <c...@zip.com.au> > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Adding to a dict through a for loop confusion.
Could someone tell me why this different behavior occurs between these 2 code snippets, please. The 1st example has quotes around it ['item'] only adds the last item to the dict (cart). In the 2nd example the item does not have quotes around it [item] and every entry is added to the dict. Why? # Example #1 cart_items = ['1','2','3','4','5'] cart = {} for item in cart_items: cart['item'] = item print cart #output {'item': 5} # Example #2 cart_items = ['1','2','3','4','5'] cart = {} for item in cart_items: cart[item] = item print cart # output {'1': '1', '3': '3', '2': '2', '5': '5', '4': '4'} Thanks you for the help. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On 10/05/16 07:03, Ondřej Rusek wrote: Dne 9.5.2016 v 10:13 Chris Roy-Smith napsal(a): Hi Python 3.4 Linux (ubuntu) This code does what I want. curs is the result of a mysql query data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 if you want 'lists in list' (like your solution): data = [] for ddate, mood, walk, lag, sleep in curs: data += [ [ddate, mood, walk, lag, sleep] ] or 'tuples in list': data = [] for ddate, mood, walk, lag, sleep in curs: data += [ (ddate, mood, walk, lag, sleep) ] but for 'tuples in list'... simple: data = [] for record in curs: data += [record] Thanks, I hadn't considered having a second list of lists for my calculations, Your solution is the sort of thing I was looking for. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On 10/05/16 12:01, Steven D'Aprano wrote: On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote: data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 While I don't know a better way to do this, it seems a bit awkward, is there a better way? Hmmm, it's hard to be sure because we don't really know what count is. Do you want a bunch of empty rows at the end? My guess is No. In your code above, you initialise each row with ten spaces, and only replace five of them. So assuming you need the extra five spaces: data = [record + [" "]*5 for record in curs] provided curs returns lists, rather than tuples. (If not, it's easy to just convert using `list(record)`. If you don't need the extra five columns, the code is even simpler: data = list(curs) Thank you, that's much better I thought I needed the extra columns, but I changed things to use 2 lists of lists (one generated with the above line and another to hold my calculated results) What if you do want extra blank rows? Easiest to just add them at the end: # initialise data as above, then add blanks for i in range(how_many_extra_rows): data.append([" "]*10) which can be simplified to: data.extend([[" "]*10 for i in range(how_many_extra_rows)]) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] is there a better way to do this?
Hi Python 3.4 Linux (ubuntu) This code does what I want. curs is the result of a mysql query data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 While I don't know a better way to do this, it seems a bit awkward, is there a better way? Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 146, Issue 22
Gustavo, Reading your description, it sounds like you opening a Windows Explorer window and double clicking on pip.exe expecting it to run like a Windows application. But pip is a command line tool and you need to open a command line windows/console (cmd.exe) first before running pip. Open cmd.exe (Start -> find programs, type in cmd and it should come right up.) I have a shortcut for cmd.exe on my desktop. From inside the command line window/console, type "pip help", and you should see the help files associated with the pip program. "pip list", will show you any modules you have installed. From there you should be able to follow the documentation and install any modules you need. Good luck, I hope this helps. Chris Clifton Message: 3 Date: Tue, 19 Apr 2016 23:26:06 -0500 From: Gustavo Davis <gusdavi...@yahoo.com> To: tutor@python.org Subject: [Tutor] Fwd: Newbie trying to get pip run on windows 7 Message-ID: <92d01ec6-5bb3-42ee-92a1-737ec8929...@email.android.com> Content-Type: text/plain; charset="utf-8" -- Forwarded message -- From: Gus Davis <gusdavi...@yahoo.com> Date: Apr 19, 2016 9:53 PM Subject: Newbie trying to get pip run on windows 7 To: webmas...@python.org Cc: From: Gustavo Davis Sent: Tuesday April 19th, 2016 To: Python Org Subject: Python Module issues (specifically pip) Greetings! My name is Gustavo Davis. ?I am enjoying immensely what I'm learning about Python and all that it has to offer. Keep up the good work with Python and please continue making it one of the most popular and open source programming languages.? For right now the only thing that is causing me issues is with getting Pip to run on my PC. I've downloaded the files to my desktop folder and Ive even tried to look up the answers on youtube and other places. Some of the answers I understand about going to start>computer>properties>advancesystemsetttings>environmentvariables>path>edit and then add something like this: ;C:\Python34\Scripts\pip C:\Users\Owner\Desktop\Python Folder\Scripts But for some reason after I made the changes and saved them they wont run. I mean once I go to the file and right click on them and click run the cmd prompt pops up for a moment and then it just closes down and the pip module never runs in python. I have version 3.4.4. and 3.5.1. I'm very new to Python and I have to admit I'm not used to using the cmd prompt to install modules and I'm not sure that I understand how to do that. Any help you can give with this would be greatly appreciated. This problem has me stomped so much I almost wanted to give up for a while on Python. But I still have a love for its goals and its philosophy and that's what continues to draw me to it. I've very new to programming in general and thats why I when I came across Python I wanted to learn it and even work primarily a Python Developer one day. I know that most likely this question that has been addressed on the website. However I just kinda felt frustrated and wanted to speak with someone directly since I don't know much about programming at all. Below in the attachments are some the errors I keep getting even with IDLE. Please have a good day and thank you for taking out the time to listen to me. ? ?? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to run a python script
Forwarding to mailing list, please use Reply All in the future. On 21 February 2016 at 09:48, Erol Gericke <woodw...@cybersmart.co.za> wrote: > Hi Chris, > > Thanks for your prompt reply, the problem has been solved! > I was using the 'python' terminal not the 'DOS' terminal. > > I have created a new directory to hold the *.py scripts. > > As I type with only two fingers I want to keep everything as short as > possible. > Is there a way to avoid the full path when running a script. > > Thanks again, you have revived my interest in Python. > > Regards, > Erol Gericke > > >> Please paste the full error message, and your complete source code. >> Also, make sure you are running the commands in the regular command >> prompt window, and not in a Python-specific one. >> >> Also, your scripts should not live in C:\Python27, because they might >> conflict with other things. >> > You can open command prompt in the directory of your scripts [0] or put them in a directory that doesn’t require a lot of typing (C:\py for example). PS. it’s not the “DOS” terminal, it’s the command prompt (cmd.exe). DOS is not part of Windows NT/2000/XP and better, and rightfully so. [0]: In Windows 8?/10, available from the File menu. Otherwise: http://www.askvg.com/enable-open-command-window-here-option-in-context-menu-in-windows-vista/ -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to run a python script
On 20 February 2016 at 17:25, Erol Gericke <woodw...@cybersmart.co.za> wrote: > I want learn Python programming. Many years ago I taught myself BASIC so I > have some programming experience. > > I have installed Python 2.7.11 and Notepad ++ on my Win 7 computer. I have > also edited the PATH variable to include C:\Python27. > > However I am unable to run any scripts. > > When I type (into the COMMAND PROMPT window) python test.py or > python C:\python27\test.py I get SyntaxError: invalid syntax > > Until I solve this problem learning programming makes no sense. > > Can you please help me, I would appreciate your help. > > Thank you in advance, > Erol Gericke. > Somerse West. South Africa. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Please paste the full error message, and your complete source code. Also, make sure you are running the commands in the regular command prompt window, and not in a Python-specific one. Also, your scripts should not live in C:\Python27, because they might conflict with other things. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] AWS /Django/Apache/Python/Github
On 13 February 2016 at 01:02, sina sareth via Tutor <tutor@python.org> wrote: > Hi ThereHow are you looking for good videos on the deploy apps with Python > Framework. I wonder if somebody has any good videos. Thanks > Sina I don’t have any videos, but I do have a comprehensive tutorial on deploying a Python application on a Linux server: https://chriswarrick.com/blog/2016/02/10/deploying-python-web-apps-with-nginx-and-uwsgi-emperor/ -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is the square brackets about?
On 16 January 2016 at 16:51, Ege Berkay Gülcan <egeberka...@gmail.com> wrote: > def get_(loc, thing): > if loc==[]: return thing > return get_(loc[1:], thing[loc[0]]) > > Hi I am new to Python and I would like to learn about these uses of square > brackets. I know that loc[1:] means loc list without the first element but > I do not know the meanings of loc==[] and thing[loc[0]]. loc == [] checks “if `loc` is equal to an empty list”. Note that this is not a good way to do this. A much better way to spell this would be: if not loc: return thing thing[loc[0]] means “check what the 0th element of `loc` (`loc[0]`) is, and use it as an index for `thing` (`thing[…]`). -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] idle??
On 13 January 2016 at 21:49, Mark Lawrence <breamore...@yahoo.co.uk> wrote: > On 09/01/2016 10:38, Chris Warrick wrote: >> >> On 8 January 2016 at 20:07, bruce <badoug...@gmail.com> wrote: >>> >>> So, where does IDLE fit into this >> >> >> IDLE is a sad little “IDE”, which is really ugly, because it’s written >> in Tk. It lacks many IDE features. It comes with a really basic >> debugger (that doesn’t even highlight the line that is being currently >> executed…), function signature hinting, and some code completion. >> > > Please ignore this drivel, he's spouted this before without giving any > justification. IDLE is perfectly adequate as a starter for Python. I’m sorry, which part of “ugly” (which you cannot deny, it doesn’t match the OS most of the time), “no debugger line highlighting”, “no line numbering” (which is a crucial feature of any code editor!) is not enough “justification”? For learning, a text editor (that’s better than notepad.exe) is enough. However, the OP explicitly asked for an IDE, and as such, they should get a good one. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] idle??
On 8 January 2016 at 20:07, bruce <badoug...@gmail.com> wrote: > Hey guys/gals - list readers > > Recently came across someone here mentioning IDLE!! -- not knowing > this. I hit google for a look. > > Is IDLE essentially an ide for doing py dev? I see there's a > windows/linux (rpms) for it. > > I'm running py.. I normally do $$python to pop up the py env for quick > tests.. and of course run my test scripts/apps from the cmdline via > ./foo.py... > > So, where does IDLE fit into this IDLE is a sad little “IDE”, which is really ugly, because it’s written in Tk. It lacks many IDE features. It comes with a really basic debugger (that doesn’t even highlight the line that is being currently executed…), function signature hinting, and some code completion. And it doesn’t even do something as basic as line numbering. Pretty much anything is better than IDLE. I recommend using vim with the python-mode plugin and YouCompleteMe. The Atom editor can also be a good Python environment. For fans of full-blown IDEs, there’s PyCharm. For experiments, IPython, Jupyter (aka IPython Notebook) or bpython should be used. They are more capable than the basic interpreter, and even have more features than IDLE. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] To FORMAT or not to
On 3 January 2016 at 13:27, yehudak . <katye2...@gmail.com> wrote: > Hi there, > In a program I wrote the following line (Python 3.5): > > print("You've visited", island, '&', new + ".") > > A programmer told me that it's a bad habit, and I should have used instead: > > print("You've visited {0} {1} {2}{3}".format(island, "&", new, ".")) > > May I understand why? > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor The programmer was not very intelligent in his use of str.format in the first place. A more sensible way to write this is: print("You've visited {0} & {1}.".format(island, new)) Formatting with constant strings is pointless, just include it in the original input. However, string formatting is not. Here are a couple of reasons: * String formatting works everywhere, but this syntax is specific to print() — if you use something else, you might end up producing faulty code * The corrected string formatting usage is more readable than the original print() * String concatenation with + requires that all arguments are strings, which is even less readable * With string formatting, you can apply special formatting to your inputs (eg. set width, number precision…), which is hard or impossible with print() * Using print() with commas adds spaces between all entries, which might look bad (and it does in this example); the only way to prevent that is by setting `sep=`, but then you need to remember about a space after "visited" and around the ampersand… * Easy to localize (translate into different languages), which is generally impossible with any of the other options (some languages might rearrange the sentence!) -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Debugging in Python
On 16 November 2015 at 15:43, Alan Gauld <alan.ga...@btinternet.com> wrote: > Thats not an IDE its just a raw interpreter. > IDLE is a full IDE that includes a debugger. It’s an awful piece of garbage that pretends to be an IDE. >> I encountered some error in the source , then I fixed it and tried to run >> the module with the above snippet again , but the the error prevails even >> though the error part is commented and the updated version saved. > > > You need to reload the module but sadly there is no simple command to do > that in the interpreter. There is in IDLE ("Restart Shell" menu item) > > So if you use IDLE your issues will be resolved. You can install > IDLE3 from the Ubuntu package manager. No, they won’t. They will be replaced by a much worse and less friendly IDE. Please don’t bother installing IDLE and use the normal `python3` shell, ipython or bpython. The correct fix is to exit() from the python3 shell and start it again. Alternatively, add some main code at the end of your file and use `python3 hlibert.py`: if __name__ == '__main__': hilbert(3) -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why does this function execute before being called?
On 07/11/15 20:18, Alan Gauld wrote: On 07/11/15 04:34, Chris Roy-Smith wrote: def genF(ofield): ... for x in range(10): def second(): main=Toplevel(root) ofield=Text(main, height=15, width=15) ofield.pack() B3=Button(main, text='exit', command=main.destroy) B3.pack() B4=Button(main, text='fill text', command=genF(ofield)) You call a function by sup[plying the parens after its name. So the function gets called here. The normal way to circumvent that in Tkinter is to use a lambda expression to defer execution, like so: B4=Button(main, text='fill text', command=lambda wgt=ofield : genF(wgt)) This certainly wasn't obvious from what I could find on the internet. Now I see an application for Lambda B4.pack() main.mainloop() I'm not sure you need the second mainloop. I think the root level mainloop will work for your window too. Just tried out leaving this second mainloop, and every works the same. I had assumed I needed to create a loop the same as the top window. Thanks for clearing up this mystery ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] command line list arguments
On 7 November 2015 at 02:56, Garry Willgoose <garry.willgo...@newcastle.edu.au> wrote: > I want to input a python list as a command line argument as for example > > python weathering-sens.py -daughter ['p0-50-50','p0-0-0-100’] > > but what I get from sys.argv is [p0-50-50,p0-0-0-100] without the string > delimiters on the list elements. I’m probably missing something really simple > because sys.argv returns strings and probably strips the string delimiters in > that conversion … but is there any way that I can keep the string delimiters > so that inside the code I can just go (if arg is ['p0-50-50','p0-0-0-100’]) > > a=eval(arg) > > or is there no alternative to doing this > > python weathering-sens.py -daughter 'p0-50-50’ 'p0-0-0-100’ > > and doing the legwork of interpreting all the arguments individually (I’ve > seen an example of this on the web). 1. NEVER use eval(). 2. Trying to pass Python code as arguments looks bad. Don’t do that. 3. Your issues with '' are caused by your shell. You would need to wrap your entire thing in quotes first, or use escaping. But instead, 4. Use argparse or another argument parsing solution, and implement it with two arguments. -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Why does this function execute before being called?
Hi, Environment: Python 2.7 Linux (Ubuntu 15.10) I am experiencing a problem with the code below running the "genF" function on opening the second window. I expected that function to be executed on clicking the 'fill text' button. The text widget gets filled on opening the window. This is my first attempt at opening a second window, so I expect I have done something stupid. #! /usr/bin/python from Tkinter import * root=Tk() def genF(ofield): for x in range(10): ofield.insert(END, x) ofield.insert(END, "\n") def second(): main=Toplevel(root) ofield=Text(main, height=15, width=15) ofield.pack() B3=Button(main, text='exit', command=main.destroy) B3.pack() B4=Button(main, text='fill text', command=genF(ofield)) B4.pack() main.mainloop() b1=Button(root, text='open second window', command=second) b1.pack() b2=Button(root, text='exit', command=root.destroy) b2.pack() root.mainloop() Thanks, Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] generate a list/dict with a dynamic name..
On 27 September 2015 at 18:38, bruce <badoug...@gmail.com> wrote: > Hi. > > I can do a basic > a=[] > to generate a simple list.. > > i can do a a="aa"+bb" > > how can i do a > a=[] > > where a would have the value of "aabb" > > in other words, generate a list/dict with a dynamically generated name > > IRC replies have been "don't do it".. or it's bad.. but no one has > said you can do it this way.. > > just curious.. > > thanks > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor And we really mean it. There are two ways. One involves e**l, which means you are executing arbitrary code, and if a contained some malicious code, it could break your system. Using e**l is considered bad for this precise reason: you don’t know if the input might lead to formatting your hard drive. And you should not trust it to be good. The other way involves modifying the g*s() dict. It does not always work though. But for a REAL way to do it, just create a dict and use it — you can have arbitrary variable names just fine: things = {} a = "aabb" things[a] = [] PS. why are you creating a out of two strings? Why not just a = "aabb"? -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Tkinter-discuss] tkinter file dialog pattern matching (fwd)
On 23/08/15 23:52, Laura Creighton wrote: oooh. Seems that there is an undocumented feature we can use! Laura --- Forwarded Message Return-Path: tkinter-discuss-bounces+lac=openend...@python.org Date: Sun, 23 Aug 2015 12:40:02 +0200 From: Michael Lange klappn...@web.de To: tkinter-disc...@python.org Message-Id: 20150823124002.7391f37e21f9b5cfaa917...@web.de In-Reply-To: 20150822210424.321b826f@lenny References: 201508221103.t7mb3kdx010...@fido.openend.se Hi, On Sat, 22 Aug 2015 21:04:24 +0100 Pawel Mosakowski pa...@mosakowski.net wrote: Hi, I've found this little gem in the Tk docs https://www.tcl.tk/man/tcl8.4/TkCmd/getOpenFile.htm#M13 From what I see file patterns in the file dialog are not regex patterns and do not support special characters. Only things that work are: 1) * - any extension 2) - files without extension 3) literal extension without wildcard chars Unfortunately it looks like there is no simple way to filter out hidden files. actually the unix tk file dialog has an an (however undocumented) feature to hide hidden elements and display even a button that allows to toggle between hidden elements on/off, however we need to do a little tcl to get to this. Since the feature is not documented anywhere it might also be a good idea to wrap this into a try...except. See this little code snippet: # from Tkinter import * import tkFileDialog as tkfd root = Tk() try: # call a dummy dialog with an impossible option to initialize the file # dialog without really getting a dialog window; this will throw a # TclError, so we need a try...except : try: root.tk.call('tk_getOpenFile', '-foobarbaz') except TclError: pass # now set the magic variables accordingly root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1') root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0') except: pass # a simple callback for testing: def openfile(event): fname = tkfd.askopenfilename() print(fname) root.bind('Control-o', openfile) root.mainloop() # Best regards Michael ___ Tkinter-discuss mailing list tkinter-disc...@python.org https://mail.python.org/mailman/listinfo/tkinter-discuss --- End of Forwarded Message ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks Laura, That does exactly what I wanted to do. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filtering listed directories
On 23/08/15 00:42, Laura Creighton wrote: In a message of Sat, 22 Aug 2015 14:32:56 +0100, Alan Gauld writes: But maybe some questions on a Tix (or Tk) forum might get more help? Once you know how to do it in native Tcl/Tk/Tix you can usually figure out how to do it in Python. -- Alan G I asked the question on tkinter-discuss, but the question hasn't shown up yet. In the meantime, I have found this: http://www.ccs.neu.edu/research/demeter/course/projects/demdraw/www/tickle/u3/tk3_dialogs.html which looks like, if we converted it to tkinter, would do the job, since all it wants is a list of files. I have guests coming over for dinner, so it will be much later before I can work on this. (And I will be slow -- so if you are a wizard at converting tk to tkinter, by all means feel free to step in here. :) ) Laura ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks Laura, unfortunately I know next to nothing of tk, so I'll have wait. No worries, This in not an urgent thing, and is mostly a learning exercise, as I have a cli tool to do what what I'm aiming to write using Tkinter. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filtering listed directories
On 22/08/15 23:32, Alan Gauld wrote: On 22/08/15 11:43, Laura Creighton wrote: How can I filter out these hidden directories? Help(tkFileDialog) doesn't help me as it just shows **options, but doesn't show what these options might be. tix (tkinter extensions) https://wiki.python.org/moin/Tix have some more file dialogs, so maybe there is joy there. There is a FileSelectDialog in Tix that has a dircmd option according to the Tix documentation. However, I've played about with it and can't figure out how to make it work! There is also allegedly a 'hidden' check-box subwidget that controls whether hidden files are shown. Again I couldn't find how to access this. But maybe some questions on a Tix (or Tk) forum might get more help? Once you know how to do it in native Tcl/Tk/Tix you can usually figure out how to do it in Python. Thanks for the Tcl tk hint, so I searched for info for tcl tk. Unfortunately the options appear to be the same as offered by tkinter. I had hoped that the cause of my problem would be that I'm still to learn that bit ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filtering listed directories
On 23/08/15 18:13, Laura Creighton wrote: In a message of Sun, 23 Aug 2015 13:09:41 +1000, Chris Roy-Smith writes: On 22/08/15 23:32, Alan Gauld wrote: On 22/08/15 11:43, Laura Creighton wrote: How can I filter out these hidden directories? Help(tkFileDialog) doesn't help me as it just shows **options, but doesn't show what these options might be. tix (tkinter extensions) https://wiki.python.org/moin/Tix have some more file dialogs, so maybe there is joy there. There is a FileSelectDialog in Tix that has a dircmd option according to the Tix documentation. However, I've played about with it and can't figure out how to make it work! There is also allegedly a 'hidden' check-box subwidget that controls whether hidden files are shown. Again I couldn't find how to access this. But maybe some questions on a Tix (or Tk) forum might get more help? Once you know how to do it in native Tcl/Tk/Tix you can usually figure out how to do it in Python. Thanks for the Tcl tk hint, so I searched for info for tcl tk. Unfortunately the options appear to be the same as offered by tkinter. I had hoped that the cause of my problem would be that I'm still to learn that bit ;) No, the problem is that the tk widget is badly designed. Not only is there only minimal pattern support matching, but there is no way to subclass the thing and feed it your own list of file and directory names. It really is a case of Do not open. No user-servicable parts to be found within. which is frustrating. Laura Thanks Laura, I don't use idle but wondered how it handled hidden directories, and found that it also shows them. I guess I'll have to be inconsistent using the title bar to warn users and trap inappropriate selections sending the user back to try again. I can only assume that windows users don't get this problem. Do any of the other graphical packages avoid this problem? I guess I should try the appropriate news groups. Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] filtering listed directories
Hi, environment: Python 2.7, Ubuntu 12.4 Linux I am trying to get the list of directories shown by tkFileDialog.askdirectory to not show hidden files (starting with .) this code results in lots of hidden directories listed in the interface making things harder than they need to be for the user. #! /usr/bin/python import Tkinter, tkFileDialog root = Tkinter.Tk() root.withdraw() dirname = tkFileDialog.askdirectory(parent=root,initialdir=/home/chris/,title='Pick a directory') How can I filter out these hidden directories? Help(tkFileDialog) doesn't help me as it just shows **options, but doesn't show what these options might be. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python application with same name as its corresponding project
On 31 July 2015 at 17:13, Anthony DuPont acdup...@mtu.edu wrote: I am trying to setup my python application in a more standard way. In my research, the general recommendation seems to be that if my application is called projectgendocs, here is an acceptable structure: ProjectParent |-- bin/ | |-- projectgendocs.py | |-- projectgendocs | |-- unittest | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py | |-- setup.py |-- README It is my understanding that ProjectParent would be added to the PYTHONPATH so the projectgendocs project could be discovered for importing. The problem I am encountering is that when the bin/projectgendocs.py is run, it breaks the imports in the ProjectParent/projectgendocs files that have import projectgendocs.somefile.py I discovered this is due to the fact that the bin/projectgendocs is discovered in the search for a package called projectgendocs because the bin directory is added to the search path. I verified this by renaming the bin/projectgendocs.py file to something different. So, my question is this: How can a python application (the file installed in the bin folder) have the same name as its corresponding python project and not break the absolute imports? Or is the only way to do this is by using relative imports? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Don’t create custom bin/ scripts, use setuptools entry points. I described it on my blog: https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/ -- Chris Warrick https://chriswarrick.com/ PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Abs
On 27/07/15 11:06, Job wrote: I want to be able to ask a user to input an integer and print out the root and power of the given integer. Why do you use abs(x) for this program? I don't understand or see the link between abs() and root and powers. This reminds me of this: By knowing that when x%2==1 x is an odd number and when x%2 ==0 x is even, I was able to create a program that asked the user to enter 10 integers and printed out the largest odd number . So If I understand how and why abs() is used to find the cube root of a perfect cube or how to use abs() to make the computer print out the root and power of a given integer I may make this program. Thank you and forgive for my fuzzy thoughts. Job ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor You will fine that any attempt to find the root of a negative value will result in an error. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter window not showing max, min and close buttons
On 21/07/15 21:52, Alan Gauld wrote: On 21/07/15 08:15, Chris Roy-Smith wrote: On 21/07/15 17:02, Alan Gauld wrote: On 21/07/15 06:05, Chris Roy-Smith wrote: I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. The simplest program that should show the icons is: import Tkinter top = Tkinter.Tk() top.mainloop() What do you see when you type just those lines at the prompt? All I get is a white square, with no way to close without using kill I have done a bit of tinkering and have found that it is only my user account that behaves this way. OK, No idea why that would be happening but it may be a Unity setting - I use Mint/Cinnamon because I hated Unity... Can you try logging out and back in using a different desktop - say XFCE and see if that changes anything. That will hopefully narrow it down to a Unity v User settings issue. In either case it will probably be an issue for another forum since its unlikely to be a Python issue, but please keep me in the loop since it might affect other tutorial users. Thanks Alan, other desktops allow correct operation. Only Unity 3D has the fault, Unity-2D works fine. I had not considered that the desktop could be the problem. I hope to find the offending file or setting in the Unity configuration, as I would prefer to know how to fix this if I need to in the future. A clean install and restore isn't an option because my backup also has the offending error :( I have narrowed it down to 1 machine, so a little detective work should identify the offending file. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter window not showing max, min and close buttons
On 22/07/15 08:07, Chris Roy-Smith wrote: On 21/07/15 21:52, Alan Gauld wrote: On 21/07/15 08:15, Chris Roy-Smith wrote: On 21/07/15 17:02, Alan Gauld wrote: On 21/07/15 06:05, Chris Roy-Smith wrote: I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. The simplest program that should show the icons is: import Tkinter top = Tkinter.Tk() top.mainloop() What do you see when you type just those lines at the prompt? All I get is a white square, with no way to close without using kill I have done a bit of tinkering and have found that it is only my user account that behaves this way. OK, No idea why that would be happening but it may be a Unity setting - I use Mint/Cinnamon because I hated Unity... Can you try logging out and back in using a different desktop - say XFCE and see if that changes anything. That will hopefully narrow it down to a Unity v User settings issue. In either case it will probably be an issue for another forum since its unlikely to be a Python issue, but please keep me in the loop since it might affect other tutorial users. Thanks Alan, other desktops allow correct operation. Only Unity 3D has the fault, Unity-2D works fine. I had not considered that the desktop could be the problem. I hope to find the offending file or setting in the Unity configuration, as I would prefer to know how to fix this if I need to in the future. A clean install and restore isn't an option because my backup also has the offending error :( I have narrowed it down to 1 machine, so a little detective work should identify the offending file. Problem solved. Unity settings are stored using GConf. Resetting Unity with the following: dconf reset -f /org/compiz/ then log out and back in. This fixed a few other mysteries at the same time (some windows could not be moved) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter window not showing max, min and close buttons
On 21/07/15 17:02, Alan Gauld wrote: On 21/07/15 06:05, Chris Roy-Smith wrote: I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. The simplest program that should show the icons is: import Tkinter top = Tkinter.Tk() top.mainloop() What do you see when you type just those lines at the prompt? All I get is a white square, with no way to close without using kill I have done a bit of tinkering and have found that it is only my user account that behaves this way. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] tkinter window not showing max, min and close buttons
I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. system Python 2.7 (32 bit) Ubuntu Linux (unity) How might I get things to look like in the tutorial? Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of lists
On Thu, Jun 4, 2015 at 2:30 AM, Peter Otten __pete...@web.de wrote: Chris Stinemetz wrote: Although I am certain it is not very efficient I was able to accomplish what I wanted with the following code I wrote: import os import pprint import csv from collections import defaultdict print_map = {'MOU':0, 'Call_Att':1, 'Device':2} header = ['IMEI','MOUs','Call_Att','Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' os.chdir(path) running_MOU = {} call_attempts = {} d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in running_MOU.keys(): For big dicts in Python 2 the test key in some_dict.keys() is indeed very inefficient as it builds a list of keys first and then performs a linear scan for the key. Much better: key in some_dict This test avoids building the list and can also use an efficient lookup algorithm that is independent of the size of the dict. running_MOU[IMEI] += Elapsed_Mins else: running_MOU[IMEI] = Elapsed_Mins if IMEI in call_attempts.keys(): call_attempts[IMEI] += 1 else: call_attempts[IMEI] = 1 # if key matches append mou else append 0. d[IMEI] = [running_MOU[IMEI]] d[IMEI].append([call_attempts[IMEI]]) d[IMEI].append([device]) print ,.join(header) for k,v in sorted(d.items()): print k, ,, d[k][print_map['MOU']],,, d[k][print_map['Call_Att']][0],,, d[k][print_map['Device']][0] print complete Here's an alternative that uses only one dict: import csv import os import sys header = ['IMEI', 'MOUs', 'Call_Att', 'Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' d = {} for fname in os.listdir(path): with open(os.path.join(path, fname)) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] elapsed_mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in d: record = d[IMEI] record[1] += elapsed_mins record[2] += 1 else: d[IMEI] = [IMEI, elapsed_mins, 1, device] writer = csv.writer(sys.stdout) writer.writerow(header) writer.writerows(sorted(d.itervalues())) print complete Peter - Thank you for showing me how to do this with one dictionary and a more efficient method to lookup dictionary keys. I originally attempted to accomplish this by using one dictionary but could not find a good example that is why I used the defaultdict module. Your approach sped the parsing time up from about 3 minutes to about 15 seconds! Very cool. Thanks, Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] dictionary of lists
I am trying to create a dictionary of lists as I read a file. I envision it looking like: {key: [float_type],[string_type]} For the first item in the list I am trying to add the value to the existing value where the key matches but I am getting the following error: Resetting execution engine Running C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py The Python REPL process has exited Traceback (most recent call last): File C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py, line 22, in module d[IMEI] += Elapsed_Mins TypeError: 'float' object is not iterable Here is the code. My question is how can I keep it list type and just sumup the first element in the list as I read it? d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) d[IMEI] += Elapsed_Mins ## this is where the error occurs. Thanks in advance, Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of lists
Resetting execution engine Running C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py The Python REPL process has exited That's slightly unusual. How are you running this? I am running it with Microsoft Visual Studio Community 2013 using Python Tools for Visual Studio Now, what I don't know, is what you are trying to do. Are you trying to append the float to the list? Or to replace the list with the float? Or to add the float to the value of the first(or last?) element in the list - if it exists (and if it doesn't? Then what?) Although I am certain it is not very efficient I was able to accomplish what I wanted with the following code I wrote: import os import pprint import csv from collections import defaultdict print_map = {'MOU':0, 'Call_Att':1, 'Device':2} header = ['IMEI','MOUs','Call_Att','Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' os.chdir(path) running_MOU = {} call_attempts = {} d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in running_MOU.keys(): running_MOU[IMEI] += Elapsed_Mins else: running_MOU[IMEI] = Elapsed_Mins if IMEI in call_attempts.keys(): call_attempts[IMEI] += 1 else: call_attempts[IMEI] = 1 # if key matches append mou else append 0. d[IMEI] = [running_MOU[IMEI]] d[IMEI].append([call_attempts[IMEI]]) d[IMEI].append([device]) print ,.join(header) for k,v in sorted(d.items()): print k, ,, d[k][print_map['MOU']],,, d[k][print_map['Call_Att']][0],,, d[k][print_map['Device']][0] print complete ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with stringio function in python 3.2
On Mon, May 4, 2015 at 7:03 AM, anupama srinivas murthy anupama.2312.bm...@gmail.com wrote: Hello, My python code needs to run on versions 2.7 to 3.4. To use stringio function as appropriate, the code i use is; if sys.version '3': A better comparison to use would be if sys.version_info[0] == 2: It’s the standard idiom, which compares 2 == 2 instead of '2.7.9 (more garbage here)' '3'. dictionary = io.StringIO(u\n.join(english_words)) else: dictionary = io.StringIO(\n.join(english_words)) The code runs fine on all versions mentioned above except for 3.2 where i get the error: dictionary = io.StringIO(u\n.join(english_words)) ^ SyntaxError: invalid syntax How can I solve the issue? The best solution is not supporting Python 3.2, especially considering that Python 3.3.0 was released in September 2012 (and the latest version is 3.4.3). Python 3.0–3.2 do not support the u'' notation for Unicode strings, it was restored in Python 3.3 to make it easier to write code compatible with 2.x and 3.x (just like you are trying to do here!) Python has to read in and parse all the code, and it encounters a strange u'' thing it does not recognize. Thus, it fails with a SyntaxError. Many Python projects out there don’t support 3.2, and this was one of the reasons. If you REALLY have to support it (why?), there are two solutions. The first one is to use '\n'.decode('utf-8') instead of u'\n' for Python 2.7, which will not trigger a compile error (it does not matter that there is no str.decode in Python 3, the syntax makes sense even if it cannot be executed). The second one is to use (at the top of your file) from __future__ import unicode_literals This will make Python 2.7 think '\n' is a Unicode string, and Python 3.x will ignore this line — in that case, you can even drop the if/else and just use the same dictionary assignment for both Pythons. Just be warned that it applies to the entire file and can lead to problems. PS. There is no reason to use multi-line strings in this case, regular strings will do it equally well and are more readable. -- Chris Warrick https://chriswarrick.com/ PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python and Django Web Engineering Class
Not for everybody, but this just popped up in my neck of the woods, organized by members of my Python user group, and I though there might be a few people here looking for something like this: http://astrocodeschool.com/ It's one of those intensive multi-week code school formats that aren't inexpensive. But it's taught by the primary Python instructor at UNC. The school is also licensed by the State of North Carolina and sponsored by Caktus Group, the largest Django development firm. -- Sincerely, Chris Calloway, Applications Analyst UNC Renaissance Computing Institute 100 Europa Drive, Suite 540, Chapel Hill, NC 27517 (919) 599-3530 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] append value to dictionary key
I would like to append a value to a dictionary key where there is already a value. Something like the below: d = {'name': {'2': 0.0, '7': 10.0, '8': 0.0, '9': 0.0}} append 10 to d['name']['2'] d = {'name': {'2': 0.0,10, '7': 10.0, '8': 0.0, '9': 0.0}} When I try to this I get the following error: d['name']['2'].append(10) Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'float' object has no attribute 'append' I am obviously doing this wrong. How would I accomplish this? Thank you in advance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating a dictionary
I am getting closer. I think I have figured out the logic. I just have a quick question. How do you access key:values in a nested dictionary? MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} say I want to access the key:value 8:0 print dict['MOL02997_C']['8'] doesn't seem to work. Thanks in advance. On Thu, Feb 19, 2015 at 5:10 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 19/02/15 22:50, Emile van Sebille wrote: if cell.endswith(suffix, 14, 16) is False: ... so they'll never end with numeric values. Further, .endswith() accepts only one argument so you ought to get an error on this line. Sorry Emile, The OP is correct. ## help(''.endswith) endswith(...) method of builtins.str instance S.endswith(suffix[, start[, end]]) - bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. ### The tuple is the set of suffices and the numbers are the start/end points. Its not often seen like that but the OP is quite correct. The test against False is unusual it woyuld normally look like if not cell.endswith(suffix, 14, 16): but that is just a style issue. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating a dictionary
On Fri, Feb 20, 2015 at 4:51 PM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 20/02/2015 17:56, Chris Stinemetz wrote: Please don't top post as it makes long threads difficult if not impossible to follow, thanks. I am getting closer. I think I have figured out the logic. I just have a quick question. How do you access key:values in a nested dictionary? MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} say I want to access the key:value 8:0 print dict['MOL02997_C']['8'] doesn't seem to work. doesn't seem to work doesn't tell us much, so normally you would post your code and the full traceback that you get. However what you have seems to be a dictionary that you've called dict, hence overriding the Python built-in name. This isn't illegal but it's certainly frowned upon. For the key 'MOL02997_C' you have a list which holds one dict which contains a value '8' amongst others. Hence:- mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} mystruct {'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]} mystruct['MOL02997_C'] [{'7': '0', '8': '0', '2': '0', '9': '0'}] mystruct['MOL02997_C'][0] {'7': '0', '8': '0', '2': '0', '9': '0'} mystruct['MOL02997_C'][0]['8'] '0' Got that? Thank you Mark. I understand what you are explaining to me but I am not sure why every instance of the key 8:value changes when I assign a new value to it. I am expecting only vals['KSL04523_A'][0]['8'] value to change to 55.55 but as you can see bellow all rows in the dictionary are changes for key 8: Thank you in advance vals['KSL04523_A'] [{'7': '0', '9': '0', '8': '0', '2': '0'}] vals['KSL04523_A'][0] {'7': '0', '9': '0', '8': '0', '2': '0'} vals['KSL04523_A'][0]['8'] '0' vals['KSL04523_A'][0]['8'] = 55.55 pprint.pprint(vals) {'CELL_': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04514_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04514_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04515_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04515_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04515_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04516_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04516_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04516_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04517_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04517_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04517_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04519_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04519_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04519_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04520_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04520_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04520_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04521_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04521_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04521_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04523_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}]} ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] updating a dictionary
Hello List, I have a dictionary that I would like to update/add rows to it as I read a file line by line. The dictionary format looks like: format = {'Cell': '','7':'','8':'','9':'','2':''} For each line read in I would simply like to check to see if a Cell key;value exists and if it does update the correct key==band(7,8,9,2) within the dictionary. If the Cell doesn't exist do the same thing as above only make sure to update the Cell key:value with it's value form the file so it can check to see if it exists later. There are duplicate Cell:values in the file so when there is a duplicate it will need to look at band to see what key:value to update. Below is what I have attempted thus far. I can provide sample data if needed. Thank you in advance. import datetime import string import pprint from datetime import datetime # Open a files for reading inFileOne = open('PRB_utilization.txt', r) iDas = DB oDas = D suffix = (iDas,oDas) dict = {'Cell': '','7':'','8':'','9':'','2':''} for line in inFileOne.readlines(): index = line.rstrip(\n).split(\t) cell = index[1] if cell.endswith(suffix, 14, 16) is False: eNb = cell[0:8] sector = cell[10:11] band = cell[9:10] dl_prb_utl = index[60] site = eNb + _ + sector if site in dict: dict['Cell'] = site dict[band] = dl_prb_utl else: dict['Cell'] = site dict[band] = dl_prb_utl inFileOne.close(); ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating a dictionary
Other than the minor tweaks I've suggested I'm not sure what your problem is? I think we need to see the data to understand the issue. Here is a sample of the input data, it is tab delimited and I chopped it down for example purposes: KSL03502_7A_1 11.5921 KSL03502_7B_1 46.4997 KSL03502_7C_1 13.5839 KSL03505_7A_1 12.8684 KSL03505_7B_1 16.5311 KSL03505_7C_1 18.9926 KSL03509_7A_1 3.4104 KSL03509_7B_1 40.6244 KSL03509_7C_1 51.0597 KSL03511_7A_1 7.128 KSL03511_7B_1 53.4401 KSL03511_7C_1 66.2584 KSL03514_2A_1 25.6476 KSL03514_2B_1 53.17 KSL03514_2C_1 11.6469 KSL03514_7A_1 39.2292 KSL03514_7B_1 65.675 KSL03514_7C_1 3.4937 I would like to parse it buy using a dictionary structure. Where each row would be something like: name 7,8,9,2 KSL03514_C,3.4937,,,11.6469 KSL03514_B,65.675,,,53.17 I am just showing an example of what KSL03514_7C_1, KSL03514_2C_1, KSL03514_7B_1, KSL03514_2B_1 would parse. Hope this helps explain what I am trying to accomplish. Thank you in advance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Decode and Encode
On Wed, Jan 28, 2015 at 10:35 AM, Sunil Tech sunil.tech...@gmail.com wrote: Hi All, When i copied a text from web and pasted in the python-terminal, it automatically coverted into unicode(i suppose) can anyone tell me how it does? Eg: p = 你好 p '\xe4\xbd\xa0\xe5\xa5\xbd' o = 'ªîV' o '\xc2\xaa\xc3\xaeV' No, it didn’t. You created a bytestring, that contains some bytes. Python does NOT think of `p` as a unicode string of 2 characters, it’s a bytestring of 6 bytes. You cannot use that byte string to reliably get only the first character, for example — `p[0]` will get you garbage ('\xe4' which will render as a question mark on an UTF-8 terminal). In order to get a real unicode string, you must do one of the following: (a) prepend it with u''. This works only if your locale is set correctly and Python knows you use UTF-8. For example: p = u你好 p u'\u4f60\u597d' (b) Use decode on the bytestring, which is safer and does not depend on a properly configured system. p = 你好.decode('utf-8') p u'\u4f60\u597d' However, this does not apply in Python 3. Python 3 defaults to Unicode strings, so you can do: p = 你好 and have proper Unicode handling, assuming your system locale is set correctly. If it isn’t, p = b你好.decode('utf-8') would do it. -- Chris Warrick https://chriswarrick.com/ PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] syntax error with raw input
On Wed, Nov 12, 2014 at 12:08 PM, Vaibhav Banait careendosc...@gmail.com wrote: Hi I am new to python. I learnt (!) using raw_input a day back. Attempt to use has resulted in error. I am not able to spot a problem in syntax. I am using python 3.4.2. Kindly help a = raw_input(Write down your name: ) Output: Traceback (most recent call last): File pyshell#1, line 1, in module a = raw_input(Write down your name: ) NameError: name 'raw_input' is not defined ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor In Python 3, raw_input() was renamed to input(). a = input(Write down your name: ) Note that input() is also a thing in Python 2, but you shouldn’t use that one for security reasons. Python 3’s is fine though. -- Chris Warrick https://chriswarrick.com/ PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Remove artca...@google.com from mailing list, PLEASE
Do it yourself at https://mail.python.org/mailman/listinfo/tutor . Besides, your email is @gmail.com, not @google.com. -- Chris Warrick http://chriswarrick.com/ PGP: 5EAAEA16 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Insert time into email
On Mon, Oct 20, 2014 at 2:34 PM, Bo Morris crushe...@gmail.com wrote: hello all, hope everyone is doing well. The below code works, however I am going back and trying to enter the time and date and I cant quite figure out how to do this without breaking the code. #!/usr/bin/python import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import time strFrom = HourlyReport.com PS. You may want to use a real e-mail address here. Or, at the very least, something that looks like one. #strTo = engineer...@oneconnxt.com #strTo = mmed...@onemediacorpinc.com strTo = b...@onemediacorpinc.com l = ['3102EHD-01108.png', '3102DHD-01109.png','3102EHD-01082.png', '3102DHD-01033.png', '3102EHD-01302.png', '3102DHD-01149.png', '3102EHD-01125.png', '3102DHD-01144.png', '3102EHD-01105.png'] t = time.strftime(%H:%M:%S) d = time.strftime(%d/%m/%Y) msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Test Hourly Report' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) msgText = MIMEText('table cellspacing=15 border=1trtdimg src=cid:3102EHD-01108.png width=400 height=300/imgtabletrtdTIMEtdtdDATE/td/td/tr/table/tdtdimg src=cid:3102DHD-01109.png width=400 height=300/imgtabletrtdTIMEtdtdDATE/td/td/tr/table/td/trtable cellspacing=15 border=1trtdimg src=cid:3102EHD-01082.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/tdtdimg src=cid:3102DHD-01033.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/td/tr/tabletable cellspacing=15 border=1trtdimg src=cid:3102EHD-01302.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/tdtdimg src=cid:3102DHD-01149.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/td/trtable cellspacing=15 border=1trtdimg src=cid:3102EHD-01125.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/tdtdimg src=cid:3102DHD-01144.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/td/tr/td/tr/tabletable cellspacing=15 border=1trtdimg src=cid:3102DHD-01144.png width=400 height=300/imgtabletrtdTIME/tdtdDATE/td/tr/table/td/tr/table', 'html') msgAlternative.attach(msgText) for image in l: with open(image, 'rb') as fh: msgImage = MIMEImage(fh.read()) msgImage.add_header('Content-ID', '{0}'.format(image)) msgRoot.attach(msgImage) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(strFrom, strTo, msgRoot.as_string()) print Successfully sent email except smtplib.SMTPException: print Error: unable to send email I need to enter the time and date in the html where TIME and DATE are. I imagine I can do this by adding cid: t and cid:d which just refers back to t = time.strftime(%H:%M:%S) d = time.strftime(%d/%m/%Y)? No, not really. cid: is for images. You want to insert actual text. Use string formatting. '…snip…trtd{time}/tdtd{date}/tr…snip…'.format(time=t, date=d) This is assuming every date is the same. If it isn’t, you’d have to use different identifiers and values. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to express shift+enter in python
On Sun, Sep 28, 2014 at 4:53 PM, lei yang yanglei.f...@gmail.com wrote: Hi expert, How to express shift+enter in python ? Thanks What do you want to express, exactly? This key combination can have multiple meanings and ways to achieve it, depending on your needs. Do you want to send the key combination to an app? What is it, exactly, that you want to do? What app uses Shift+Enter in the way you want to use it? -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] This is driving my crazy! My file hasn't been corrupted
On Sun, Aug 31, 2014 at 6:31 PM, Richard Dillon dillo...@comcast.net wrote: My text file has five numbers, 1-5 I don't what the problem is. I've written the file using Word (saved as .txt ) as well as TextEdit Python 3.4.1 on a Mac We don’t really know either, without seeing the file. It probably has some unwanted garbage produced by your fancy-schmancy editor. Get a real plain text editor (TextWrangler for example) and don’t use rich-text editors. With a real editor, your code works here. Also, don’t do this: except: print('An error occured.') It’s better to let Python show the exceptions. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.4.1 question for Mac users
On Fri, Aug 29, 2014 at 5:01 PM, Richard Dillon dillo...@comcast.net wrote: I’m teaching myself Python 3.4.1 on a Mac and the book I’m using is written for Windows users. I’m trying to open a file on the desktop and I created a path using the example in the book. Any Mac users out there with a solution? My main drive is named “OS”. Here’s my code: def main(): my_file = input('Enter file to open: ') infile = open(r'\OS\Users\richarddillon\Desktop\my_file','r') file_contents = infile.read() infile.close() print(file.contents) main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.4.1 question for Mac users
Sorry for the errorneous quote-only response, gmail managed to send it without me typing a thing. On Fri, Aug 29, 2014 at 5:01 PM, Richard Dillon dillo...@comcast.net wrote: infile = open(r'\OS\Users\richarddillon\Desktop\my_file','r') On the Mac, you don’t need to specify a drive there; the main drive is just /. Also, the path separator is a forward slash (/). This also lets you remove the r in front of the string, which is needed for backslashes unless you escape them. The corrected code is: infile = open('/Users/richarddillon/Desktop/my_file', 'r') -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] debug and execute python code in Mac
On Thu, Aug 28, 2014 at 2:41 PM, William Ray Wing w...@mac.com wrote: On Aug 27, 2014, at 8:08 PM, Sebastian Silva sebast...@fuentelibre.org wrote: Too bad it's mac only. If you try it, do share your experience. I don't use non-free operating systems, so I can't try it myself. Just as an aside — Apple has stopped charging for OS-X. Sebastan probably meant “free” as in Stallman: http://www.gnu.org/philosophy/free-sw.html (most people believe free = $0. FSF people, however, want to steal that word for their concept. Not very successful at that, as you can see.) -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] time vs. timeit
On Tue, Aug 26, 2014 at 6:26 AM, diliup gabadamudalige dili...@gmail.com wrote: Hi all, 1. why do some say that the time module is more accurate than the timeit module? s = time.time() or s = timeit.timeit() 2. Why is it that both modules never return the same answer on each run? The two functions have completely different uses, and do completely different things. help(time.time) Help on built-in function time in module time: time(...) time() - floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. In other words, return this: http://en.wikipedia.org/wiki/Unix_time help(timeit) NAME timeit - Tool for measuring execution time of small code snippets. […] | timeit(self, number=100) | Time 'number' executions of the main statement. | | To be precise, this executes the setup statement once, and | then returns the time it takes to execute the main statement | a number of times, as a float measured in seconds. The | argument is the number of times through the loop, defaulting | to one million. The main statement, the setup statement and | the timer function to be used are passed to the constructor. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Preparing virtualenvwrapper for Django 1.6 development
On Sat, Aug 23, 2014 at 9:37 PM, Alan Gauld alan.ga...@btinternet.com wrote: While I wouldn't say its the best environment I don't think its fair to say Windows is a bad environment for Python. Any experienced Windows programmer will find it much easier to use Python on Windows than to learn a whole new OS and development environment. There are various pitfalls that happen on Windows and that don’t on Linux. Some packages outright assume Windows does not exist, and this leads to failing code. In other cases, you must compile a C extension, which is not easy to configure — and not ever package has wheels/.exes available… Linux tries to follow POSIX standards, and also acknowledges people may want to be programmers. Also, OP did not state whether they are experienced Windows programmers, experienced platform-independent programmers or newcomers to programming in general. [ And for context, I run Linux on my main desktop, MacOS on my laptop, and Windows 8.1 on a second desktop - used mainly for photography/video processing. And I use Python on all 3 of them) context: I have a dual-boot Arch Linux/Windows 7 system. Python installed on both OSes (and even in some Windows VMs). -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Preparing virtualenvwrapper for Django 1.6 development
On Fri, Aug 22, 2014 at 11:23 PM, Sithembewena Lloyd Dube zebr...@gmail.com wrote: Hi everyone, I am developing on a Windows 8.1 machine and wold like to setup virtualenvironment via virtualenvwrapper so as to have a properly set up Python development environment. I am referring to Jeff Knupp's guide at http://www.jeffknupp.com/blog/2013/12/18/starting-a-django-16-project-the-right-way/ After installation of virtualenvwrapper via pip, the guide says: After it's installed, add the following lines to your shell's start-up file (.zshrc, .bashrc, .profile, etc). export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/directory-you-do-development-in source /usr/local/bin/virtualenvwrapper.sh My issue is, I do not understand what these lines are doing (I have a vague idea but assumptions can be deadly). Moreover, it is clear that the instructions were authored with a UNIX environment in mind. Would anyone be so kind as to translate this to Windows speak, as well as perhaps pointing out what file this would go into in a Windows environment? virtualenvwrapper does not work in Windows. You should use regular virtualenv instead. Read this: http://virtualenv.readthedocs.org/en/latest/virtualenv.html#usage Note that this blog post is HEAVILY *nix-specific, and that Windows is a bad environment for Python development (especially Web development). I personally recommend you just get a virtual machine running some Linux instead of playing with Windows. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alert to all Experienced Python Software Object Oriented Programmers-Novice Needs Help In Understanding Textbook
On 18 August 2014 02:45 ALAN GAULD alan.ga...@btinternet.com wrote: At the Community College we used Python version 3.4.0 which I guess is up to date. Yes indeed, the latest and greatest. The “latest and greatest” is actually 3.4.1. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ Sent from my SGS3. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] read cell phone's directory?
On Aug 14, 2014 9:30 AM, = Clayton - Tang = c...@ctny.org wrote: Hi all, I am on WIndows and have an Android cell phone running Android 4.4.4. When I connect the phone to my PC using a micro-USB cable, the phone appears next to the local hard drive under This PC window, then I can browse the phone's directory like a regular disk. My goal is to find all the photos on the phone then do something with the files. So I copied the path from the File Explore navigation bar, which is 'This PC\Nexus 5\Internal storage\DCIM\Camera', but the follow code doesn't work. I get an error W indowsError: [Error 3] The system cannot find the path specified: 'This PC\\Nexus 5\\Internal storage\\DCIM\\Camera/*.*. Does anyone know who to make it work? This was recently discussed on the main list (python-list aka comp.lang.python). Long story short, modern Android phones are using the MTP protocol and do not behave like usual USB drives. You must use a module that implements MTP if you want to access your phone. import os; No need for a semicolon here. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ Sent from my SGS3. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re module
On 14 Aug 2014 15:58 Sunil Tech sunil.tech...@gmail.com wrote: Hi, I have string like stmt = 'pspan style=font-size: 11pt;span style=font-family: times new roman,times;Patient name:nbsp;Upadhyay Shyam/spanspan style=font-family: times new roman,times;nbsp;nbsp;br /Date of birth:nbsp;nbsp;nbsp;08/08/1988 br /Issue(s) to be analyzed:nbsp;nbsp;tes/span/spanbr /span style=font-size: 11pt;span style=font-family: times new roman,times;Nurse Clinical summary:nbsp;nbsp;test1/spanspan style=font-family: times new roman,times;nbsp;br /br /Date of injury:nbsp;nbsp;nbsp;12/14/2013/spanbr /span style=font-family: times new roman,times;Diagnoses:nbsp;nbsp;nbsp;723.4 - 300.02 - 298.3 - 780.50 - 724.4nbsp;Brachial neuritis or radiculitis nos - Generalized anxiety disorder - Acute paranoid reaction - Unspecified sleep disturbance - Thoracic or lumbosacral neuritis or radiculitis, unspecified/spanbr /span style=font-family: times new roman,times;Requester name:nbsp;nbsp;nbsp;Demo Spltycdtestt/spanbr /span style=font-family: times new roman,times;Phone #:nbsp;nbsp;nbsp;(213) 480-9000/spanbr /br /span style=font-family: times new roman,times;Medical records reviewed br /__ pages of medical and administrative records were reviewed including:br /br /br /Criteria used in analysis br /nbsp;br /br /Reviewer comments br /br /br /Determinationbr /Based on the clinical information submitted for this review and using the evidence-based, peer-reviewed guidelines referenced above, this request isnbsp;br /br /Peer Reviewer Name/Credentialsnbsp;nbsp;/spanbr /span style=font-family: times new roman,times;Solis, Test,nbsp;PhD/spanbr /span style=font-family: times new roman,times;Internal Medicine/spanbr /span style=font-family: times new roman,times;nbsp;/spanbr /br /span style=font-family: times new roman,times;Attestationbr /br /br /Contact Information/spanspan style=font-family: times new roman,times;nbsp;br //span/span/pbr/font face=\'times new roman,times\' size=\'3\'Peer to Peer contact attempt 1: 08/13/2014 02:46 PM, Central, Incoming Call, Successful, No Contact Made, Peer Contact Did Not Change Determination/font' i am trying to find the various font sizes and font face from this string. i tried print re.search(span style=\(.*)\, stmt).group() Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Don't use regular expressions for HTML. Use lxml instead. Also, why would you need that exact thing? It's useless. Also, this code is very ugly, with too many spans and — worse — fonts which should not be used at all. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ Sent from my SGS3. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] read cell phone's directory?
On 14 August 2014 17:48 = Clayton - Tang = c...@ctny.org wrote: Chris, thanks for the reply. I don't have newsgroup access, You don't need it. Use the official mailing list that is mirrored to Usenet. Main page with subscribe link: https://mail.python.org/mailman/listinfo/python-list The thread in question: https://mail.python.org/pipermail/python-list/2014-August/676375.html can you point me to some place where I can learn more? Do you have sample code I can learn from? Thanks. The thread does not have any ready answer just yet, it's currently busy arguing about the protocol. You can Google the term “python MTP”, you may find some answers there. -- Chris “Kwpolska” Warrick http://chriswarrick.com/ Sent from my SGS3. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python twitter errors:[{message:Could not authenticate you, code:32
On 08/08/2014 09:28 AM, Alan Gauld wrote: Example code often uses fictitious security keys. Are you sure these values are genuine values that work if you use them to access twitter directly? Do you mean you used the same keys as in the example? Or have you tested the keys work via some other method of access? I used my own keys and shortened them for this posting. They were working with an curl example from the twitter's dev homepage. I can't help there I know nothing about Twitter, far less its API! Now, I've downloaded another twitter-library - and it's working! Nevertheless thank you for your reply. -- Christian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Printing multi-line variables horizontally
It looks ilke this WONDERFUL mailing list which does not do something as basic as a sane Reply-to header made me send a response to the OP only. Here it is again: -- Forwarded message -- From: Chris “Kwpolska” Warrick kwpol...@gmail.com Date: Fri, Aug 8, 2014 at 7:36 PM Subject: Re: [Tutor] Printing multi-line variables horizontally To: Greg Markham greg.mark...@gmail.com On Aug 8, 2014 7:22 PM, Greg Markham greg.mark...@gmail.com wrote: Hello, Python novice back again. :) I'm making progress in my learning process, but struggling whenever attempting to creatively go beyond what's required in the various chapter assignments. For example, there's a simple random die roller program that looks like the following: # Craps Roller # Demonstrates random number generation import random # generate random numbers 1 - 6 die1 = random.randint(1, 6) die2 = random.randrange(6) + 1 total = die1 + die2 print(You rolled a, die1, and a, die2, for a total of, total) input(\n\nPress the enter key to exit.) I wanted to make it a little more interesting by using ascii art representations of the six die. When printing, however, they do so vertically and not horizontally. Here's a snippet of the code: die_2 = .-. |o| | | |o| `-' print(die_1, die_2) So, how would I get this to display horizontally? Like so... .-. .-. | | |o| | o | | | | | |o| `-' `-' Thanks, Greg ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor You would need to do some extra work. Specifically, you must split the string into lines, and print them side-by-side and line-by-line. Like this: die_1 = [ .-., |o|, | |, |o|, `-', ] die_2 = [ .-., | |, | o |, | |, `-', ] for l, r in zip(die_1, die_2): print(l, r) -- Chris “Kwpolska” Warrick http://chriswarrick.com/ Sent from my SGS3. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python twitter errors:[{message:Could not authenticate you, code:32
Dear All, I'm trying to execute the examples from https://github.com/sixohsix/twitter with the current library version installed by pip install (1.14.3). #!/usr/bin/env python # -- coding: utf-8 -- from twitter import * con_secret='DACs' # Consumer Secret con_secret_key='jold' # Consumer Key token='2554' # Access token token_key='HHSD' # Access Token Secret t = Twitter( auth=OAuth(token, token_key, con_secret, con_secret_key)) t.statuses.user_timeline(screen_name=RenateBergmann) The reply is: twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: 1.1/statuses/user_timeline.json using parameters: (oauth_consumer_key=DA...oauth_nonce=...oauth_signature_method=HMAC-SHA1oauth_timestamp=oauth_token=oauth_version=1.0screen_name=RenateBergmannoauth_signature=..) details: {errors:[{message:Could not authenticate you,code:32}]} What's the issue? Have I used the right tokens and keys? The labeling in the script is a bit different from the Twitter api page. Is Python 2.7 the proper version? The documentation said 2.6, but someone told me I had to use 2.7. Is the authentication method correct? It should be, because this is an example from the Github readme. I'm a beginner, so maybe it's only a slight mistake? Thank you in advance. -- Christian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error Handling in python
On Thu, Jul 24, 2014 at 1:35 PM, jitendra gupta jitu.ic...@gmail.com wrote: Hi All My shell script is not throwing any error when I am having some error in Python code. In this case, I dont want to run my second.py Even I am throwing error from my test.py, but still second.py is getting executed, which i dont want, You must expilicitly ask your shell to do exit if something fails. Like this: ~ shellTest.sh ~~~ #!/bin/bash set -e python test.py python second.py ~~~ I explicitly set the shell to /bin/bash on the shebang line, and then set the -e option to fail when a command exits with a non-zero status. You should always have a shebang line in your shell files, and execute them as ./shellTest.sh (after chmod +x shellTest.sh); moreover, one for Python files is recommended, like this: #!/usr/bin/env python -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error Handling in python
On Thu, Jul 24, 2014 at 2:01 PM, Wolfgang Maier wolfgang.ma...@biologie.uni-freiburg.de wrote: Try something like this (assuming bash): python test.py if [ $? = 0 ]; then python second.py fi as your shell script. The [ ] and = should be doubled. But all this is not needed, all you need is: python test.py python second.py However, you need to explicitly stack all the commands you want to execute this way — so, if there are more things, `set -e` might also be of use. (you would need an even uglier tree for `if`s.) -- Chris “Kwpolska” Warrick http://chriswarrick.com/ PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor