Re: [Tutor] File transfer
"Chris King" wrote How would I send a file from one computer to another. I have modules which can send simple objects, such as dictionaries with simple objects in it. They can't send files thou. Please help. Can you use ftp? Thats the easiest way... Python has an ftp module. The only snag is the other end needs to be running an ftp server. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File transfer
Corey Richardson wrote: If you can send a list, have the list [name, data] where name is the file name and data is the raw binary of the file, contained in a string. How do you send a list? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to notify/handle an error?
Which of the following ways is better to handle something wrong? Many thanks. # First: def is_valid_project(): # Do checks and valorize is_a_valid_project accordingly return is_a_valid_project # True / False # caller side if is_valid_project(): pass # do stuffs with valid project else: print "error" # Second solution: def is_valid_project(): # Do checks and valorize is_a_valid_project accordingly if not is_a_valid_project: raise NotAValidProject # caller side try: is_valid_project() pass # do stuffs with valid project except NotAValidProject: print "error" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Thanks, and I'm looking it over... On 10/30/10, Tino Dai wrote: > On Sat, Oct 30, 2010 at 6:44 PM, Jacob Bender > wrote: > >> Dear Tutors, >> >> I was wondering how I could make an AI for creatures that run >> around, and try to survive. Like polyworld. The real problem is making >> the code connection to make them learn. Can you please help? >> >> Thanks >> > > Hi Jacob, > > That is a really general question. Usually people have a specific > question and/or some code > they are having problems with. I don't know your level of Python knowledge, > but you should check > out http://wiki.hacdc.org/index.php/NARG for more information. They are > doing stuff along the > lines of what you are asking for. > > HTH, > Tino > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
I have a few more ?'s. I was trying to make a program for ubuntu that does one function: if ctrl + Alt + "t" is pressed, to shut down the computer. There are only two problems. I want it to run in the background, so nobody knows it's there. I do know how to make it run at startup, so that isn't a problem. I found pygame, so I could say if ctrl +Alt + "t" is pressed to do something, but a black window would always have to be open, which leads to my first problem. I do know how a .pyw works, but it still rests in the Task Manager at the bottom of the screen. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to notify/handle an error?
dave p. guandalino wrote: Which of the following ways is better to handle something wrong? Many thanks. It depends on what you are trying to do. # First: def is_valid_project(): # Do checks and valorize is_a_valid_project accordingly return is_a_valid_project # True / False Do you mean "validate" rather than "valorize"? # caller side if is_valid_project(): pass # do stuffs with valid project else: print "error" This is not the best approach. Never (well, *almost* never) use print for printing error messages. Here the caller should do one of these: # caller #1 if is_valid_project(): do_something_with_valid_project() else: do_something_else() # caller #2 if is_valid_project(): do_something_with_valid_project() else: # this is a fatal error, bail out raise SomeException() This general technique is called "Look before you leap" -- you're checking whether something is safe before attempting to do it. If it is safe, you continue, otherwise you take an alternative action (often just to raise an error and stop processing). # Second solution: def is_valid_project(): # Do checks and valorize is_a_valid_project accordingly if not is_a_valid_project: raise NotAValidProject # caller side try: is_valid_project() pass # do stuffs with valid project except NotAValidProject: print "error" This general technique is called "Easier to ask forgiveness than permission" -- just try to do what you want, and if it fails, catch the exception and do something else. Again, you should almost never catch an exception just to print an error message. Very rare exception to this rule: at the *very top level* of an application, you might catch the exception, log the technical details, display a user-friendly message to the user, and then exit the application. When you use raise, Python does nearly all of this for you. It won't log the failure, and the message is a technical traceback aimed at programmers rather than end-users, but it prints an error message and exits the application. Better would be: # caller #3 is_valid_project() # will raise an exception if there is a problem do_something_with_valid_project() # caller #4 try: is_valid_project() except NotAValidProject: do_something_else else: # no exception occurred do_something_with_valid_project() In Python, try blocks are very efficient, but actually catching an exception is moderately costly. So the general rule is, if you expect most cases to succeed, and failures to be rare, it is better to use a try...except block and the "Easier to ask forgiveness" strategy. If you expect failures to be common, it is better to "Look Before You Leap". -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Jacob Bender wrote: I have a few more ?'s. Well, don't keep them a secret, tell us what they are! What are your questions? I was trying to make a program for ubuntu that does one function: if ctrl + Alt + "t" is pressed, to shut down the computer. There are only two problems. I want it to run in the background, so nobody knows it's there. I do know how to make it run at startup, so that isn't a problem. I found pygame, so I could say if ctrl +Alt + "t" is pressed to do something, but a black window would always have to be open, which leads to my first problem. I do know how a .pyw works, but it still rests in the Task Manager at the bottom of the screen. Thanks! Well, I personally don't see the point, since your system almost certainly will have ctrl-alt-delete as shutdown keys. I'm glad you're so excited by your project that you felt you had to tell us about it. By the way, .pyw files are for Windows. They don't have any special powers in Ubuntu. You also might find that the best way to change the shutdown key combination is through /etc/inittab rather than writing a Python program to do it. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to notify/handle an error?
Steven D'Aprano wrote: Never (well, *almost* never) use print for printing error messages. More information here: http://en.wikipedia.org/wiki/Error_hiding -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators (the "at" sign)?
Thanks for this very helpful post, Lie. I find decorators quite interesting and am always looking for new ways to understand and use them. Your trace function is fun, and I added it to my decorator library. In response to your point about event-handling in GUIs: I haven't used pyqt that extensively yet, but it does have a decorator-based syntax for event-handling, which is more or less what you described. Its concept of events may be slightly different -- signals and slots -- but it's just a layer of abstraction on 'mouse-right-button-click-event,' so hopefully not unwelcome. I've been impressed with them so far. I hate GUI programming, and even got into programming in part to avoid GUIs, but I find it easy enough to make something with pyqt (using decorators) that a customized GUI is a decent alternative to just making command line scripts, especially if your working with anything visual that you'd like to display. Cheers, Soren --- On Tue, 10/26/10, Lie Ryan wrote: From: Lie Ryan Subject: Re: [Tutor] decorators (the "at" sign)? To: tutor@python.org Date: Tuesday, October 26, 2010, 12:30 PM On 10/26/10 13:46, Alex Hall wrote: > Hi all, > Now that I am able to run the source code of an open source > application I hope to one day help develop, I am trying to understand > how it works. One thing I keep seeing is an at sign followed by a > word, usually (maybe always) immediately preceeding a function > definition. For example, and I know this exact code will not make much > sense, but it gives the idea: > class Bing(Messages, Updating, Dismissable): > > @set_index > def get_url(self, index=None): > return self.storage[index]['Url'] > > What is the "@set_index" for? Specifically, what is the at sign doing? > Google was only able to provide me with a very vague idea of what is > going on, though it seems to crop up a lot in classmethod and > staticmethod calls (not sure about those either). I read PEP 318, but > it was not much help since I am coming at this having no idea what I > am looking at. The PEP did explain why I have never run into this > before, though - it is apparently specific to Python. I see this sort > of thing all over this source code so it seems like a good idea to get > exactly what it is for. TIA! The decorator syntax is really just a shorthand, from this: @decorator def func(arg): pass is equivalent to: def func(arg): pass func = decorator(func) basically, a decorator is a function that takes an function as a parameter/callable and (usually) returns another function/callable as return value. A slightly advanced usage of decorator: def trace(func): """ trace will print the func's name, the number of times func have been called, the arguments it's called with, and the return value of func whenever func is called. """ # define an inner function def _decorator(arg): print ("The %sth call of %s with arg: %s" % (_decorator._numcall, func.__name__, arg)) _decorator._numcall += 1 ret = func(arg) print "finished", func.__name__, "returns:", ret return ret # this is used to store the number of times # the decorated function is called _decorator._numcall = 0 # disable the decorator when debugging is enabled if __debug__: # or: return _decorator if __debug__ else func return _decorator else: return func @trace def twice(arg): return 2 * arg # the @trace makes it as if you do this: # twice = trace(twice) $ # let's start the program $ python decor.py The 0th call of twice() with arg: 30 finished twice() returns: 60 The 1th call of twice() with arg: 3 finished twice() returns: 6 The 2th call of twice() with arg: 4 finished twice() returns: 8 74 $ $ # now call it with debugging disabled: $ python -O decor.py 74 another nifty use of decorator is for event handling for a hypothetical GUI toolkit (I've yet to actually see a toolkit that uses this syntax yet): @button.on_click def shoot(button): ... @window.on_keypress('p') def pause(key): ... other built-in functions designed for decorator syntax is @property, @classmethod, and @instancemethod. Decorator can become extremely powerful when combined with the descriptor protocol (.__get__, .__set__). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File transfer
On 10/31/2010 12:03 PM, Corey Richardson wrote: On 10/31/2010 11:51 AM, Chris King wrote: On 10/30/2010 10:08 PM, Corey Richardson wrote: If you can send a list, have the list [name, data] where name is the file name and data is the raw binary of the file, contained in a string. On 10/30/2010 9:11 PM, Chris King wrote: Dear Tutors, How would I send a file from one computer to another. I have modules which can send simple objects, such as dictionaries with simple objects in it. They can't send files thou. Please help. Sincerely, Me ___ Tutor maillist -tu...@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor how do I get raw binary from a file, or preferably a folder? In order to send a folder, you would have to zip it up using the zipfile module.http://docs.python.org/library/zipfile.html To read from a file, you open it, and then read() it into a string like this: for line in file: string += string + file.readline() That is the basic concept, but it should carry you far. I don't think readline will work an image. How do you get raw binary from a zip? Also make sure you do reply to the tutor list too, not just me. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File transfer
On 10/31/2010 12:06 PM, Chris King wrote: On 10/31/2010 12:03 PM, Corey Richardson wrote: On 10/31/2010 11:51 AM, Chris King wrote: On 10/30/2010 10:08 PM, Corey Richardson wrote: If you can send a list, have the list [name, data] where name is the file name and data is the raw binary of the file, contained in a string. On 10/30/2010 9:11 PM, Chris King wrote: Dear Tutors, How would I send a file from one computer to another. I have modules which can send simple objects, such as dictionaries with simple objects in it. They can't send files thou. Please help. Sincerely, Me ___ Tutor maillist -tu...@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor how do I get raw binary from a file, or preferably a folder? In order to send a folder, you would have to zip it up using the zipfile module.http://docs.python.org/library/zipfile.html To read from a file, you open it, and then read() it into a string like this: for line in file: string += string + file.readline() That is the basic concept, but it should carry you far. I don't think readline will work an image. How do you get raw binary from a zip? Also make sure you do reply to the tutor list too, not just me. If you want me to reply to the whole list, try sending the message to the whole list. Readlines will not work for an image. You need to open the file with the "rb" flag, why don't you read more into file I/O? http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to notify/handle an error?
"dave p. guandalino" wrote Which of the following ways is better to handle something wrong? Its not really a questin of "better" but a question of more idiomatic. def is_valid_project(): # Do checks and valorize is_a_valid_project accordingly return is_a_valid_project # True / False This is a good return value given the functions name - it suggests it is a predicate so should return a boolean result. def is_valid_project(): # Do checks and valorize is_a_valid_project accordingly if not is_a_valid_project: raise NotAValidProject This is not showing what the return value is but one assumes it is True if the project is valid, but raises an exception if not valid. That mixed response is not good for a predicate. But if you renamed the function to validate_project(p) that returns None if OK and raises an exception for an invalid project that might be considered acceptable.That would resuult in code like: try: validate_project(p) pass # do stuff with project p except InvalidProjectError: HandleError() But a lot depends on what the tests look like. True exception based error handling would simply assume the project was valid, proceed to process it and only raise an exception if the processing failed. This probably obviates the need for the check function entirely... So... try: is_valid_project() pass # do stuffs with valid project except NotAValidProject: print "error" becomes try: pass # do stuffs with valid project except : HandleError() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] gauge of the fram
Hi all, sorry for long message but just read the red highlighted lines I am facing a problem with gauge update. I want to return a value from another script file but the problem is this value locate inside a loop. example : the mean running script : m=0 # this function to return any value from different script def return_values(value): global m m= value #print m return value def create(parent): return ANN(parent) [wxID_ANN, wxID_ANNBUTTON1, wxID_ANNFILEBROWSEBUTTON1, ... so on [wxID_ANNMENUFILEEXIT, wxID_ANNMENUFILEOPEN, wxID_ANNMENUFILESAVE, ] = [wx.NewId() for _init_coll_menuFile_Items in range(3)] [wxID_ANNMENUHELPABOUT] = [wx.NewId() for _init_coll_menuHelp_Items in range(1)] class ANN(wx.Frame): def _init_coll_menuBar1_Menus(self, parent): # generated method, don't edit parent.Append(menu=self.menuFile, title='File') parent.Append(menu=self.menuHelp, title='Help') def _init_coll_menuHelp_Items(self, parent): # generated method, don't edit def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_ANN, name='ANN', parent=prnt, pos=wx.Point(386, 130), size=wx.Size(715, 565), style=wx.DEFAULT_FRAME_STYLE, title='Artificial Neural Network') self._init_utils() self.SetClientSize(wx.Size(699, 527)) self.SetMenuBar(self.menuBar1) self.panel1 = wx.Panel(id=wxID_ANNPANEL1, name='panel1', parent=self, pos=wx.Point(0, 0), size=wx.Size(699, 484), style=wx.TAB_TRAVERSAL) self.gauge1 = wx.Gauge(id=wxID_ANNGAUGE1, name='gauge1', parent=self.panel2, pos=wx.Point(200, 112), range=100, size=wx.Size(100, 28), style=wx.GA_HORIZONTAL) self.gauge1.SetValue(0) self.gauge1.SetLabel('') and so on ... def OnNormtrainingButton(self, event): self.data= self.fileBrowseButton1.GetValue() target= self.fileBrowseButton2.GetValue() import normalization self.gauge1.Value=0 no= normalization.Norm() no.read_norm_data(data) #self.gauge1.Value= print m the second script is: normalization.py def read_norm_data(self, inputsData): self.pat=[] tragauge=0;totalrange= float(len(open(inputsData).readlines())) #for the gauge process while True: # read the input data line = f.readline() if len(line)==0: break inputs=line.split() self.inputs=map(float,inputs) #print self.inputs # for the training data norm gauge process self.traininggauge = ((tragauge+1)/totalrange)*100 tragauge=tragauge+1 ann.return_values(self.traininggauge) # HERE is the gauge from the last line I need this value to go in side the mean frame and update the gauge. I can return the value into the mean file but couldn’t make it for the gauge cuz the gauge is inside the ANN class which I couldn’t go inside it. I am trying to do that by make it as a global varible and update but it’s keep give me the same initial value m=0. may be I can get it by sending the value and the gauge into a new script and update the gauge but I think this is not a proper way. Any idea! Best regards,___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File transfer
Chris King quoted Corey Richardson: On 10/31/2010 12:03 PM, Corey Richardson wrote: [...] To read from a file, you open it, and then read() it into a string like this: for line in file: string += string + file.readline() Aii! Worst way to read from a file *EVAR*!!! Seriously. Don't do this. This is just *wrong*. (1) You're mixing file iteration (which already reads line by line) with readline(), which would end in every second line going missing. Fortunately Python doesn't let you do this: >>> for line in file: ... print file.readline() ... Traceback (most recent call last): File "", line 2, in ValueError: Mixing iteration and read methods would lose data (2) Even if Python let you do it, it would be slow. Never write any loop with repeated string concatenation: result = '' for string in list_of_strings: result += string # No! Never do this! BAD BAD BAD!!! This can, depending on the version of Python, the operating system, and various other factors, end up being thousands of times slower than the alternative: result = ''.join(list_of_strings) I'm not exaggerating. There was a bug reported in the Python HTTP library about six(?) months ago where Python was taking half an hour to read a file that Internet Explorer or wget could read in under a second. You might be lucky and never notice the poor performance, but one of your users will. This is a Shlemiel the Painter algorithm: http://www.joelonsoftware.com/articles/fog000319.html Under some circumstances, *some* versions of Python can correct for the poor performance and optimize it to run quickly, but not all versions, and even the ones that do sometimes run into operating system dependent problems that lead to terrible performance. Don't write Shlemiel the Painter code. The right way to read chunks of data from a file is with the read method: fp = open("filename", "rb") # open in binary mode data = fp.read() # read the whole file fp.close() If the file is large, and you want to read it in small chunks, read() takes a number of optional arguments including how many bytes to read: fp.read(64) # read 64 bytes If you want to read text files in lines, you can use the readline() method, which reads up to and including the next end of line; or readlines() which returns a list of each line; or just iterate over the file to get Chris King went on to ask: I don't think readline will work an image. How do you get raw binary from a zip? Also make sure you do reply to the tutor list too, not just me. readline() works fine on binary files, including images, but it won't be useful because binary files aren't split into lines. readline() reads until end-of-line, which varies according to the operating system you are running, but often is \n. A binary file may or may not contain any end-of-line characters. If it does, then readline() will read up to the next EOL perfectly fine: f.readline() => '\x23\x01\0=#%\xff\n' and if it doesn't, readline() will happily read the entire file all the way to the end: '\x23\x01\0=#%\xff3m.\x02\0\xa0\0\0\0+)\0\x03c!But this is the wrong way to solve the problem of transferring files from one computer to another. The right way is to use a transport protocol that already works, something like FTP or HTTP. The only reason for dealing with files as bytes is if you want to create your own file transport protocol. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor