[Tutor] how to get variable from an external script or program
Hey all I have a small program that when run from the command line, will return a certain value for an arguement. Like this: > mfetchz 45 > 45j so the program is mfetchz and the argument is 45 i know i can call the program with os.system("mfetchz 45") but how do i get the return? The OS is linux, if that matters thanks sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get variable from an external script or program
kick butt, gents, thanks a lot sk On Fri, May 29, 2009 at 4:39 PM, W W wrote: > On Fri, May 29, 2009 at 4:27 PM, shawn bright wrote: >> >> Hey all >> >> I have a small program that when run from the command line, will >> return a certain value for an arguement. Like this: >> >> > mfetchz 45 >> > 45j >> >> so the program is mfetchz and the argument is 45 >> >> i know i can call the program with os.system("mfetchz 45") >> but how do i get the return? >> >> The OS is linux, if that matters > > use subprocess module: > > import subprocess > > op = subprocess.Popen(['mfetchz', '45'], stdout=subprocess.PIPE) > > for line in op.stdout: > print line > > > HTH, > Wayne > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get variable from an external script or program
cool, thanks again sk On Fri, May 29, 2009 at 5:09 PM, Alan Gauld wrote: > > "vince spicer" wrote >> >> import commands >> output = commands.getout("ls -lah") > > There are many ways to do this in Python including os.popen, commands and > subprocess. > > But subprocess is the "officially correct" version, the others are > deprecated and could theoretically disappear in a future version of Python. > (But not soon I suspect because of the amount of legacy code that uses it!) > > But its definitely worth weaning oneself onto subprocess even though it is > initially harder work. In the end the superior flexibility and consistency > of approach pay back. > > Alan G. > > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to know if process is running?
Hey all, I have an app that runs in a GUI written in pygtk. It spawns several threads, and runs all the time. It is mission critical that we can never have two instances of this running at once. So, my question is, how can i write something that will know if there is an instance of that something already running? I am doing this in python 2.5 on Ubuntu, if that matters ( which i suspect it does ). thanks, shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to know if process is running?
Thanks for the pointers Wayne, Tino, Looks easier than i had thought. sk On Tue, Jul 28, 2009 at 11:10 AM, Tino Dai wrote: > On Tue, Jul 28, 2009 at 11:45 AM, shawn bright wrote: >> >> So, my question is, how can i write something that will know if there >> is an instance of that something already running? >> > > There are a lot of ways to do this. Writing to a file on the filesystem and > having the 2nd process check for that file. Have the thread write to a log > file every x seconds and having the 2nd process check for that. Having some > sort of ipc mechanism set up (http://docs.python.org/library/ipc.html). Have > a semaphore mechanism set up. > (http://www.python.org/doc/2.5.2/lib/semaphore-objects.html) > > HTH, > Tino > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to know if process is running?
Hey all, i used the popen with getpid() option. working well so far, thanks to all of you. shawn On Tue, Jul 28, 2009 at 12:11 PM, Mac Ryan wrote: > I am not an expert, but if I got you correctly, what you want to achieve > is a "singleton": http://en.wikipedia.org/wiki/Singleton_pattern if you > watch at the sample implementation, there is a Python example too. > > Mac. > > On Tue, 2009-07-28 at 10:45 -0500, shawn bright wrote: >> Hey all, >> >> I have an app that runs in a GUI written in pygtk. It spawns several >> threads, and runs all the time. >> It is mission critical that we can never have two instances of this >> running at once. >> >> So, my question is, how can i write something that will know if there >> is an instance of that something already running? >> >> I am doing this in python 2.5 on Ubuntu, if that matters ( which i >> suspect it does ). >> >> thanks, >> shawn >> ___ >> Tutor maillist - tu...@python.org >> http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with socket connection
Hey all, I keep getting a connection error 111 connection refused. When i try to connect to a server at a remote ip address. I am using linux on both computers. the socket server looks like this: #!/usr/bin/python import SocketServer class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print "%s wrote:" % self.client_address[0] print self.data # just send back the same data, but upper-cased self.request.send(self.data.upper()) if __name__ == "__main__": HOST, PORT = "127.0.0.1", 3000 # Create the server, binding to localhost on port server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() and the client looks like this: #!/usr/bin/python import socket import sys HOST, PORT = "ip.address.of.server", 3000 data = "hello world" # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to server and send data sock.connect((HOST, PORT)) sock.send(data + "\n") # Receive data from the server and shut down received = sock.recv(1024) sock.close() print "Sent: %s" % data print "Received: %s" % received the server starts fine on the remote computer, but the client dies immediatly when executed ( to time to find the server, i don't think) with the connection refused error. The port forwarding is set up correctly on both computers, i know because i have another app that runs on 3000 ( but is not running when i am trying this) any tips would be greatly appreciated, thanks sk ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with socket connection
Hey all, I keep getting a connection error 111 connection refused. When i try to connect to a server at a remote ip address. I am using linux on both computers. the socket server looks like this: #!/usr/bin/python import SocketServer class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print "%s wrote:" % self.client_address[0] print self.data # just send back the same data, but upper-cased self.request.send(self.data.upper()) if __name__ == "__main__": HOST, PORT = "127.0.0.1", 3000 # Create the server, binding to localhost on port server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() and the client looks like this: #!/usr/bin/python import socket import sys HOST, PORT = "ip.address.of.server", 3000 data = "hello world" # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to server and send data sock.connect((HOST, PORT)) sock.send(data + "\n") # Receive data from the server and shut down received = sock.recv(1024) sock.close() print "Sent: %s" % data print "Received: %s" % received the server starts fine on the remote computer, but the client dies immediatly when executed ( to time to find the server, i don't think) with the connection refused error. The port forwarding is set up correctly on both computers, i know because i have another app that runs on 3000 ( but is not running when i am trying this) also, it does not work between two linux computer on the same LAN, it does work if i use localhost and run both server and client on the same computer. any tips would be greatly appreciated, thanks sk ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to stop a function
hello all, i have a gui app that uses functions to respond to gui events. like def on_start_button_clicked(self, stuff): do this or that. now there is one function that i have a kinda nested if else conditions that i need to stop if necessary if value == 1: if next_val == 4: do this or that else: here i need the function to just die do somthing here is there something i can do to make this happen? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to stop a function
jeeze, thanks, sorry, stupid question. On 4/24/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > shawn bright wrote: > > now there is one function that i have a kinda nested if else > > conditions that i need to stop if necessary > > > > if value == 1: > > if next_val == 4: > >do this or that > > else: > >here i need the function to just die > > do somthing here > > > > is there something i can do to make this happen? > > return > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] best way to tell if i am connected to the internet
hello there all, i am wondering, what would be the simplest way to get a true/false am i connected to the internet ? right now i am using httplib to fetch a webpage every 20 minutes to see, but i am thinking that there is a better way, any suggestions would be encouraging thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] best way to tell if i am connected to the internet
ok, cool. thanks sk On 4/30/07, Jalil <[EMAIL PROTECTED]> wrote: ping a host on the net if you get an echo response back you are good. better yet ping the host page you are scraping. On 4/30/07, shawn bright < [EMAIL PROTECTED]> wrote: > > hello there all, > > i am wondering, what would be the simplest way to get a true/false > am i connected to the internet ? > > right now i am using httplib to fetch a webpage every 20 minutes to see, > but i am thinking that there is a better way, > > any suggestions would be encouraging > > thanks > shawn > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] best way to tell if i am connected to the internet
good enough, i suppose i can use a try, except to test if i am online and from that have a true / false. That is what i was looking for. I just didn't think it necessary to pull a webpage every 20 minutes. thanks shawn k On 5/1/07, Alan Gauld <[EMAIL PROTECTED]> wrote: "shawn bright" <[EMAIL PROTECTED]> wrote > i am wondering, what would be the simplest way to get a true/false > am i connected to the internet ? > > right now i am using httplib to fetch a webpage every 20 minutes to > see, but > i am thinking that there is a better way, You don't need to fetch it just connect. If there are no errors you are online. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to stop output to terminal
lo there all, i have a simple thread that i want to run without piping any output to the terminal. like if i do an x = os.system("ping -c 1 www.google.com") i don't want it to show all the stuff in the terminal. can i disable that ? can i disable it for only certain lines? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to stop output to terminal
cool, thanks sk On 5/11/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote: shawn bright wrote: > lo there all, > > i have a simple thread that i want to run without piping any output to > the terminal. > like if i do an > > x = os.system("ping -c 1 www.google.com <http://www.google.com>") > > i don't want it to show all the stuff in the terminal. if you use os.popen or the subprocess module you can execute system commands and have their output stored in file-like objects. then if you don't want any output, don't read from them. > > can i disable it for only certain lines? yeah, just read in all lines and display the ones which meet your criteria. > > thanks > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] easiest way to get true/false of odd/even number
nevermind, i found it. 4 %2 = 0 (even) 5 %2 = 1 (odd) pretty simple shawn On 5/14/07, shawn bright <[EMAIL PROTECTED]> wrote: Hey there all, i know this sounds kinda easy, but i was wanting the least verbose way to get a True / False of a number being odd (not even) thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] easiest way to get true/false of odd/even number
Hey there all, i know this sounds kinda easy, but i was wanting the least verbose way to get a True / False of a number being odd (not even) thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python IDE
you can use gedit with some plugins that make it pretty much like an ide, and its really fast. another really cool one is JEdit. That is what i used before i switched to vim to do everything. runs on everything, has what you are looking for. Eclipse with PyDev is cool, too. But a little heavy for me. hth On 6/11/07, scott <[EMAIL PROTECTED]> wrote: Hi, I have been using Kdevelop so far to develop and a few bugs it inherits from Kate/Kwrite are really annoying me. It does not collapse quotes properly and there are other graphical glitches as well. Could someone suggest a few good IDE's for me to look at. I would need a IDE that haves syntax highlighting and I also really like type completion where the IDE gives you suggestions as you type. Extras like a good built in dictionary and anything else that makes coding faster or easier would be great. I also prefer a IDE that is for multiple languages, but I am willing to use a IDE that is only Python for now until those bugs get fixed in Kdevelop. Lastly, I am a Linux user, so the IDE would need to run natively on Linux. Thanks. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] cyclical redundancy check
Hello there all, Does anyone know where i can find a function that does an 8 bit Cyclical Redundancy Check. I need it to verify data, and i need to be able to create one given an 12 byte message. Does anyone know much about doing this in python ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cyclical redundancy check
wait, sorry, thats 16 bits total, a low byte and a high byte. If that makes more sense thanks On 7/4/07, shawn bright <[EMAIL PROTECTED]> wrote: Hello there all, Does anyone know where i can find a function that does an 8 bit Cyclical Redundancy Check. I need it to verify data, and i need to be able to create one given an 12 byte message. Does anyone know much about doing this in python ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with translating a c function to a python function
hello all, i have a c function from some modbus documentation that i need to translate into python. it looks like this: unsigned short CRC16(puchMsg, usDataLen) unsigned char *puchMsg ; unsigned short usDataLen ; { unsigned char uchCRCHi = 0xFF ; unsigned char uchCRCLo = 0xFF ; unsigned uIndex ; while (usDataLen––) { uIndex = uchCRCHi ^ *puchMsgg++ ; uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; uchCRCLo = auchCRCLo[uIndex] ; } return (uchCRCHi << 8 | uchCRCLo) ; } some of it i can make out, but i can't seem to figgure out this part ' auchCRCHi[uIndex}; it looks like a typo, because there is a closing } that does not match the opening [. anyway, if someone could kinda give me a push, it would help me out a lot. thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with translating a c function to a python function
oh, here is what i have so far, but is not giving me the right values def crc16(data): crc_hi = 0xff crc_lo = 0xff for x in data: crc_index = crc_hi ^ x crc_hi = crc_lo ^ (crc_hi | crc_index) crc_lo = crc_lo | crc_index return (crc_hi << 8 | crc_lo) whaddya think? On 7/5/07, shawn bright <[EMAIL PROTECTED]> wrote: > hello all, > > i have a c function from some modbus documentation that i need to > translate into python. > > it looks like this: > > > unsigned short CRC16(puchMsg, usDataLen) > unsigned char *puchMsg ; > unsigned short usDataLen ; > { > unsigned char uchCRCHi = 0xFF ; > unsigned char uchCRCLo = 0xFF ; > unsigned uIndex ; > while (usDataLen––) > { > uIndex = uchCRCHi ^ *puchMsgg++ ; > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > uchCRCLo = auchCRCLo[uIndex] ; > } > return (uchCRCHi << 8 | uchCRCLo) ; > } > > some of it i can make out, but i can't seem to figgure out > this part ' auchCRCHi[uIndex}; > it looks like a typo, because there is a closing } that does not match > the opening [. > > anyway, if someone could kinda give me a push, it would help me out a lot. > thanks > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with translating a c function to a python function
Thanks Alan, so do you think my translation is close? i do not know a lick of c. Nope, not one line. thanks shawn On 7/5/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > "shawn bright" <[EMAIL PROTECTED]> wrote > while (usDataLen––) > { > uIndex = uchCRCHi ^ *puchMsgg++ ; > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > uchCRCLo = auchCRCLo[uIndex] ; > } > return (uchCRCHi << 8 | uchCRCLo) ; > } > > > this part ' auchCRCHi[uIndex}; > > it looks like a typo, because there is a closing } that does not > > match > > the opening [. > > Its probably a typo but there is one (pretty remote, and horrible) > possible way for it to be valid which is if uIndex is a macro that > expands to complete the square bracket expression and introduce > an expression which needs a brace to finish it. But thats > just perverse, so I think its a mistake! (Especially since I just > noticed uIndex is used elsewhere without any closing brace) > > Alan G. > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] back on bytes
hello all, i have a number 12480 i have a low byte of 192 and a high byte of 176 so i can do this IDLE 1.2.1 No Subprocess >>> (176 & 127) * 256 + 192 12480 but if i start with the 12480, how do i get the two bytes (lo and hi) that make it up? i kinda know what i am doing here, but keep getting tripped up thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] back on bytes
Well, I contacted the programmer of these controls and the reason they mask the MSB on these reports is to designate what type of sensor it is. If the MSB is set, the sensor is one type, if not, another. So, knowing that i could put these together ok. To me, the speed is of no consequence like it would be if i were processing files, these sensors report anywhere from 6 to 12 bytes total, and we get them at the rate of about 20 / minute. Having said all that, I want to express thanks to this list, especially you guys, Kent and Alan, not just for the help here the past week, but also what i have been able to dig out of my gmail archives from help you gave me on similar issues months ago. I appreciate it a lot. shawn On 7/7/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > Alan Gauld wrote: > > Surely it is easier and more obvious > > to simply shift the bits right or left using >> and << and use > > bitwise and/or operations than do all this multiplication and > > addition malarky. (Its also a lot faster!) > > Are you sure about that? With Python 2.5 on a MacBook Pro it seems to > be *slightly* faster: > > src $ python -m timeit "5 << 21; 10 << 21; 50 << 21; 247 << 21" > 1000 loops, best of 3: 0.0917 usec per loop > > src $ python -m timeit "5 * 0x20; 10 * 0x20; 50 * 0x20; 247 > * 0x20" > 1000 loops, best of 3: 0.0924 usec per loop > > .0917/.0924 = 0.99242424242424254 > > src $ python -m timeit -s "nums=range(256); mults=range(1, 22)" "for i > in nums:" " for m in mults:" "i< 1000 loops, best of 3: 564 usec per loop > > src $ python -m timeit -s "nums=range(256); mults=[1< range(1, 22)]" "for i in nums:" " for m in mults:" "i*m" > 1000 loops, best of 3: 579 usec per loop > > src $ python -m timeit -s "nums=range(256); mults=[1< range(1, 22)]" "for i in nums:" " for m in mults:" "pass" > 1 loops, best of 3: 195 usec per loop > > If the last timing is a reasonable estimate of the loop overhead in the > previous two, then roughly the speed difference is 579-195=384 vs > 564-195=369 and shifting is 369/384.=0.9609375 the speed of multiplication. > > My guess is the integer multiply in my computer recognizes this simple > case and optimizes it to a shift. > > Kent > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with translating a c function to a python function
Hey thanks, i finally did get a function working. i posted it on www.bitsbam.com i did guess that the puchMsg++ ment that it was iterating through the bytes of an array. And Kent and Alan helped me get through the other parts. I am glad for all this help, because this is an issue that comes up increasingly often. so i am also glad for the email archiving by gmail. he he thanks all, shawn On 7/8/07, Tiger12506 <[EMAIL PROTECTED]> wrote: >> i have a c function from some modbus documentation that i need to >> translate into python. >> unsigned short CRC16(puchMsg, usDataLen) >> unsigned char *puchMsg ; >> unsigned short usDataLen ; >> { >> unsigned char uchCRCHi = 0xFF ; >> unsigned char uchCRCLo = 0xFF ; >> unsigned uIndex ; >> while (usDataLen––) >> { >> uIndex = uchCRCHi ^ *puchMsgg++ ; >> uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; >> uchCRCLo = auchCRCLo[uIndex] ; >> } >> return (uchCRCHi << 8 | uchCRCLo) ; >> } I found this link which may provide some insight into what's going on here. (google "modbus CRC16") http://www.modbustools.com/modbus_crc16.htm This proves to me that auchCRCHi is a lookup table that you do not have access to. Happily :-) that link provides the table. Hmmm... let's see, the difficult C stuff... *puchMsgg++ means to return the current character in a string, and then increment the pointer, so that when the C code encounters *puchMsgg++ again it reads the next character, increments, etc. You can emulate this with an index and array notation in python. ^ , << , and | are all bitwise operators, and python uses all of these in the same way as C '^' means XOR exclusive OR. 0101 ^ 0011 = 0110i.e. 5 ^ 3 = 6 '<< ' means left - shift 0010 << 2 = 1000 i.e. a << b = a * (2**b) '|' means OR. 0101 ^ 0011 = 0111 i.e. 5 ^ 3 = 7 puchMsgg is basically a string and all the unsigned stuff are (very roughly) integers. HTH, Jacob S. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] storm anyone?
Hey there all, i got the news that storm was released as open source. Storm is a db orm for python. i have a downloaded package and i would like to play with it, but it does not come with any install instructions. i found the package here https://storm.canonical.com/FrontPage there is a makefile in the top level folder, so should i use gcc and try to 'make' 'make install' or is that not necessarily the way to go here? thanks for any tips shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do you install EGG files
Hey thanks for this, yes, i used the easy_install method and it did work on the python 2.4, the python 2.5 failed. shawn On 7/18/07, Kent Johnson <[EMAIL PROTECTED]> wrote: Terry Carroll wrote: > On Wed, 11 Jul 2007, shawn bright wrote: > >> Hey there all, >> i got the news that storm was released as open source. Storm is a db orm for >> python. >> i have a downloaded package and i would like to play with it, but it does >> not come with any install instructions. >> i found the package here https://storm.canonical.com/FrontPage >> there is a makefile in the top level folder, so should i use gcc and try to >> 'make' 'make install' or is that not necessarily the way to go here? The makefile is just a front-end to the tests. I think you can just copy the storm directory (the one containing __init__.py, not the top-level storm-0.9 dir) to your site-packages directory. > I see it comes in an EGG format, which is just a ZIP file. What will (I > think) work is to open the EGG file with your favorite unzipper and unzip > into your site-packages directory (making sure to use the directory names > from the EGG file). egg files are zip files packaged for use with easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall In many cases easy_install gives one-step installation of Python packages, including downloading from the CheeseShop. In the case of storm it didn't work for me (using the --dry-run option though). YMMV. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] about importing a module
hello there, if i have a module that is in the same directory as the file that imports it, but that module has the same name as a module in my python path, which one gets imported ? i ask because i want to do some work on the module, but dont want to mess with my stable one in site-packages. so i want to import it from the local directory only. thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about importing a module
change the name of the module, simple. thanks shawn On 7/19/07, Tiger12506 <[EMAIL PROTECTED]> wrote: If the module has been imported before your code is run, it will be the library module (very important if working in IDLE which importants many modules, for example). But if it has not been imported before, the module in the current directory is imported first. You can check if a module has been imported previously by checking if in sys.modules. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about datetime object
Hello there, if i have a python datetime object, what is the easiest way to make it into epoch seconds ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] another question ( unrelated )
ok, how would i have it re-initialize itself ? yes, i want to do this on a failure condition. something wrapped in a try - except its long and complicated dealing with talking to a dataserver over ip and passing byte streams back and forth. i just need to do this for testing to see where something is failing and how soon i could re-connect to the data server. whew ! thanks shawn On 7/20/07, Kent Johnson <[EMAIL PROTECTED]> wrote: shawn bright wrote: > If i have a thread, of type threading.Thread > that i initiate with an __init__ > in the > def run(self): > while 1: > do some stuff > > > is there a way i can stop this thread and restart this thread from > within itself ? No. A thread stops by exiting the run method, then it is done. And how would a stopped thread restart itself? What you can do, is write your run() method to do whatever you want; in particular it could sense some condition and re-initialize itself. If you are using a Thread subclass and overriding run() (as opposed to passing the run method to the constructor) you can use the subclass to hold any state you need and you can write/call any other methods you need. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] another question ( unrelated )
If i have a thread, of type threading.Thread that i initiate with an __init__ in the def run(self): while 1: do some stuff is there a way i can stop this thread and restart this thread from within itself ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to sort a dictionary by values
hello there all, i am wondering how to sort a dictionary that i have by values. And i also need to sort them from greatest to least like if i have a dictionary d = {'a':21.3, 'b':32.8, 'c': 12.92} how could i sort these from least to greatest so that the order would turn out b,a,c thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
sorry all, i did mean greatest to least, thanks for all the help here shawn On 8/8/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > Tiger12506 wrote: > >> Just curious: Is there a reason to use __getitem__() over itemgetter > (used > >> in the example in my reply)? > > > > __getitem__ is a method builtin to a dict object. itemgetter 1) has to > be > > imported 2) is more generically used, therefore probably using a more > > generic/slower algorithm > > itemgetter() written in C and should be pretty fast. The actual sort > algorithm is the same in either case, in fact the list of keys to be > sorted is the same in either case. > > On my computer my version seems to be a little faster on random data but > as I noted in a separate email, the results are different so the > algorithm should be chosen based on the desired results. > > In [27]: import random > In [28]: d = dict( (i, random.random()) for i in range(1000) ) > In [29]: import timeit > In [34]: timeit.Timer('sorted(d.keys(), key=d.__getitem__, > reverse=True)', 'from __main__ import d').timeit(1) > Out[34]: 7.3717570304870605 > In [38]: timeit.Timer('sorted(d.items(), key=operator.itemgetter(1), > reverse=True)', 'from __main__ import d; import operator').timeit(1) > Out[38]: 8.2723259925842285 > > Kent > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to add arguments to a command line program
lo there all, i want to write a program that will be called from another program. I need to pass it one variable. i suppose i could also do this with a module, and create a new instance of whatever i want to pass it to, but all the same, how would i go about this. like if i had a program that i wanted to pass a number into. i am sure i do it with sys args, but don't know how. like python run_my_script.py somevar does this make sense ? The other way to do this is create a class i suppose that could be called. Should probably do it that way, but still, i would like to know. thanks. shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to add arguments to a command line program
Just what i was looking for, thanks shawn On 9/14/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > > "shawn bright" <[EMAIL PROTECTED]> wrote > > > i am sure i do it with sys args, but don't know how. > > > > like > > > > python run_my_script.py somevar > > > > does this make sense ? > > > > Check my Talking to the User topic in my tutorial. > The second half talks about using command line arguments. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] do i have to import modules at the start of a file?
lo there all, i have a gui program that imports a few modules that i don't need if i am using the program remotely. The program has an admin interface and thread interface, only the admin interface is needed when i am using the program from a remote computer. all of my modules are imported at the start of the file, and not initiated till a certain button is clicked on the GUI, could i put those import statements in the button click event? thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] do i have to import modules at the start of a file?
It's the second one, not all the modules will be available on the portable version. But the threads that require those modules will not be necessary on the portable version. I want to be able to go to any linux computer with GTK and mysqldb installed and check out my stuff from svn and run the admin part of the program. But the main computer at work that takes data in will need the modules to run the threads. thanks for your help on this shawn On 9/26/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > shawn bright wrote: > > lo there all, > > > > i have a gui program that imports a few modules that i don't need if i > > am using the program remotely. > > The program has an admin interface and thread interface, only the admin > > interface is needed when > > i am using the program from a remote computer. > > > > all of my modules are imported at the start of the file, and not > > initiated till a certain button is clicked on the GUI, could i put those > > import statements in the button click event? > > Yes but why do you want to? The reasons I know for doing this: > - the import takes a long time or a lot of memory and you don't want to > incur the cost unless you need it > - the imported module may not be available always and you want the rest > of the importing module still to be usable > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] internet access
i did something very similar to this. My daughter would stay on her instant messenger (gaim) all night if i didn't. i have a cron script that checks the hour of day, if later than x pm. does os.system("/etc/init.d/network stop") os.system("chmod a-x /etc/init.d/network") ( so that a reboot doesn't override it ) then in the morning, makes it executable, and starts it up again. Then again, this is linux and my daughter, though somewhat geeky would not know how to beat this. Maybe something similar could be done in windows ? I don't know much about that OS. sk On 10/11/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > "Kirk Vander Meulen" <[EMAIL PROTECTED]> wrote > > > I'd like to write a script that limits internet access to certain > > hours of > > the day. This seems like it should be simple but I'm not very > > experienced > > Its actually not that simple because its fundamentally going against > the design of the computer. Modern computers and operating systems > are designed to allow multiple users to perform multiple tasks > 'simultaneously' without getting in each others way. Thus it's > relatively > easy for an application to change its own access but much more > difficult for an application to change a user's access and even more > difficult for one user's application to change access for every user > or for the machine as a whole. It's designed to be that way. > > Now there is one loophole, which is the administrators account > (which is root on Linux/MacOS or nearly every user on XP! > I dunno if Vista has closed this gaping Windows security hole or > not?). > > The administrator's account should not be used for day to day > usaage (XP defaults not withstanding) but for administewring all > other users and the machine itself. Thus to do what you need the > application would need to run as administrator and would need to > tweak the operating system networking setup. Neither of these are > particularly trivial in a well set up machine (and for good reason). > > So the question is, do you want to lock down a single application? > Or a single user? Or the whole computer? And which OS are you > using? > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] need a way to get my own ip address
Greetings, i am looking for an easy way to get my own ip address as a string from python. I am using Ubuntu Linux if that makes any difference. thanks ! shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need a way to get my own ip address
Thanks, Jay, in IDLE, this gave me 127.0.0.1 is there a way to get my assigned ip instead of the localhost one? thanks On Jan 2, 2008 8:31 AM, jay <[EMAIL PROTECTED]> wrote: > You could perhaps use this method > > import socket > myIP = socket.gethostbyaddr(socket.gethostname())[2] > > Jay > > On Jan 2, 2008 8:25 AM, shawn bright < [EMAIL PROTECTED]> wrote: > > > Greetings, > > > > i am looking for an easy way to get my own ip address as a string from > > python. > > I am using Ubuntu Linux if that makes any difference. > > thanks ! > > > > shawn > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need a way to get my own ip address
It returns this ('hostname', [], ['127.0.1.1']) i am running this on a linux system thanks On Jan 2, 2008 8:50 AM, jay <[EMAIL PROTECTED]> wrote: > Well that will return the reverse lookup of the current hostname assigned > to your system. Is this a Windows or Linux/Unix system? What does this > return? > > print socket.gethostname() > print socket.gethostbyaddr(socket.gethostname ()) > > j > > > On Jan 2, 2008 8:45 AM, shawn bright <[EMAIL PROTECTED]> wrote: > > > Thanks, Jay, > > in IDLE, this gave me 127.0.0.1 > > is there a way to get my assigned ip instead of the localhost one? > > thanks > > > > > > On Jan 2, 2008 8:31 AM, jay < [EMAIL PROTECTED]> wrote: > > > > > You could perhaps use this method > > > > > > import socket > > > myIP = socket.gethostbyaddr(socket.gethostname())[2] > > > > > > Jay > > > > > > On Jan 2, 2008 8:25 AM, shawn bright < [EMAIL PROTECTED]> wrote: > > > > > > > Greetings, > > > > > > > > i am looking for an easy way to get my own ip address as a string > > > > from python. > > > > I am using Ubuntu Linux if that makes any difference. > > > > thanks ! > > > > > > > > shawn > > > > > > > > ___ > > > > Tutor maillist - Tutor@python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need a way to get my own ip address
Thanks, Jay, just what i was looking for. Works great. shawn On Jan 2, 2008 9:10 AM, jay <[EMAIL PROTECTED]> wrote: > Well that is what I normally use, but I always have my hostname setup > properly. In your case, that socket call won't work. You could try this > link I found on google > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094 > > jay > > > On Jan 2, 2008 9:00 AM, shawn bright <[EMAIL PROTECTED]> wrote: > > > It returns this > > ('hostname', [], [' 127.0.1.1']) > > i am running this on a linux system > > thanks > > > > > > On Jan 2, 2008 8:50 AM, jay < [EMAIL PROTECTED]> wrote: > > > > > Well that will return the reverse lookup of the current hostname > > > assigned to your system. Is this a Windows or Linux/Unix system? What > > > does > > > this return? > > > > > > print socket.gethostname() > > > print socket.gethostbyaddr(socket.gethostname ()) > > > > > > j > > > > > > > > > On Jan 2, 2008 8:45 AM, shawn bright <[EMAIL PROTECTED] > wrote: > > > > > > > Thanks, Jay, > > > > in IDLE, this gave me 127.0.0.1 > > > > is there a way to get my assigned ip instead of the localhost one? > > > > thanks > > > > > > > > > > > > On Jan 2, 2008 8:31 AM, jay < [EMAIL PROTECTED]> wrote: > > > > > > > > > You could perhaps use this method > > > > > > > > > > import socket > > > > > myIP = socket.gethostbyaddr(socket.gethostname())[2] > > > > > > > > > > Jay > > > > > > > > > > On Jan 2, 2008 8:25 AM, shawn bright < [EMAIL PROTECTED]> wrote: > > > > > > > > > > > Greetings, > > > > > > > > > > > > i am looking for an easy way to get my own ip address as a > > > > > > string from python. > > > > > > I am using Ubuntu Linux if that makes any difference. > > > > > > thanks ! > > > > > > > > > > > > shawn > > > > > > > > > > > > ___ > > > > > > Tutor maillist - Tutor@python.org > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > > > ___ > > > > > Tutor maillist - Tutor@python.org > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about a number and bytes.
Thanks for your reply. i need to do this in python because python is what scripting language our data I/O system is written in. i am writing a command out over a serial port that tells an RTU to change part of it's program. I am not sure what you mean by using it in any other python context, this is about the only thing we will need to be able to do this for, at least, that is the case for right now. thanks sk On Jan 29, 2008 2:55 PM, Tiger12506 <[EMAIL PROTECTED]> wrote: > > Hello there all. > > > > I have a need to make a hi byte and lo byte out of a number. > > > > so, lets say i have a number 300, and need this number to be > > represented in two bytes, how do i go about that? > > First question. Why would you need to do this in python? Second question. If > you could do that, how would you use it in any other python context? > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about a number and bytes.
Hello there all. I have a need to make a hi byte and lo byte out of a number. so, lets say i have a number 300, and need this number to be represented in two bytes, how do i go about that? thanks for any tips, sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about a number and bytes.
ok, was using pyserial, but was not using struct.pack. thanks sk On Jan 29, 2008 3:16 PM, Michael Langford <[EMAIL PROTECTED]> wrote: > Use pyserial: > > http://pyserial.sourceforge.net/ > > Use struct.pack: > > http://docs.python.org/lib/module-struct.html > > The format string will depend whether you need little or big endian. > >--Michael > > > > On Jan 29, 2008 4:13 PM, shawn bright <[EMAIL PROTECTED]> wrote: > > Thanks for your reply. > > i need to do this in python because python is what scripting language > > our data I/O system is written in. > > i am writing a command out over a serial port that tells an RTU to > > change part of it's program. I am not sure what you mean by using it > > in any other python context, this is about the only thing we will need > > to be able to do this for, at least, that is the case for right now. > > thanks > > sk > > > > > > On Jan 29, 2008 2:55 PM, Tiger12506 <[EMAIL PROTECTED]> wrote: > > > > Hello there all. > > > > > > > > I have a need to make a hi byte and lo byte out of a number. > > > > > > > > so, lets say i have a number 300, and need this number to be > > > > represented in two bytes, how do i go about that? > > > > > > First question. Why would you need to do this in python? Second question. > > > If > > > you could do that, how would you use it in any other python context? > > > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.RowdyLabs.com > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MySQLdb question.
you may be missing db.commit(). When you do insert, update, etc.. you call commit() to make the changes stick.-skOn 7/28/06, Kent Johnson < [EMAIL PROTECTED]> wrote:Ron Phillips wrote:> I am trying to write a script that adds data to a table using > MySQLdb.py. For some reason, "INSERT" seems to work temporarily. I> run a command to insert a row, and then do a select query, and it's> there. After the program shuts down, though, it's gone. No rows are > permanently created. SELECT works fine from MySQLdb, CREATE TABLE too,> but when I add data, it's only there while the script is executing,> then it's gone.Try calling conn.commit() before conn.close (). IIRC older versions ofMySQL were set to auto-commit by default but newer versions require theexplicit commit.Kent___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about type str
Hey there,i have an app with this line.sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))it is failing with the following error.Traceback (most recent call last): File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 88, in ? entered_digits = getNumber(welcome, time_limit, password_digits) File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 72, in getNumber sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))TypeError: 'str' object is not callableanyone know what i may be doing wrong here?thanksshawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about type str
gee whiz, i thought i had poured over that line sufficiently.It works now. imagine that.thanks,shawnOn 7/29/06, Python < [EMAIL PROTECTED]> wrote:On Sat, 2006-07-29 at 09:26 -0500, shawn bright wrote: > Hey there,> i have an app with this line.> sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit, digit_count))sys.stderr.write("GET DATA %s %d %d\n" % (sound, time_limit, digit_count)) ^You meant to do string interpolation, but left out the interpolation(formating) operator. So the parenthesized _expression_ looked like afunction call.> > it is failing with the following error.>> Traceback (most recent call last):> File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 88, in ?> entered_digits = getNumber(welcome, time_limit, password_digits) > File "/usr/share/asterisk/agi-bin/ast_agi_test.agi", line 72, in> getNumber> sys.stderr.write("GET DATA %s %d %d\n" (sound, time_limit,> digit_count))> TypeError: 'str' object is not callable >>> anyone know what i may be doing wrong here?>> thanks> shawn> ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor--Lloyd KvamVenix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with rejected mail smtplib
Hello there,i have a customer list, each with a number of email address that we send notifications to via text message.the problem is, there are a number of providers ( just two ) that reject our messages.the script goes a little something like this : Address = '[EMAIL PROTECTED]'From = '[EMAIL PROTECTED]'message = 'From: [EMAIL PROTECTED]: %s\r\nSubject: %s\r\n\r\n%s' % (Address,'alert',message) server.sendmail(From, Address, message)most of the time it goes thru ok. but only some providers have a problem. However, those same providers get messages if i send them thru Evolution.any ideas of what to check out? thanks-sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with rejected mail smtplib
Oh, right... sorry... i didn't know i could do it like that. I was looping thru themfor address in addresses: server.sendmail(from,address,message)i did not mention that in the OP.-shawn On 7/30/06, Michael P. Reilly <[EMAIL PROTECTED]> wrote: On 7/29/06, shawn bright <[EMAIL PROTECTED] > wrote: Hello there,i have a customer list, each with a number of email address that we send notifications to via text message.the problem is, there are a number of providers ( just two ) that reject our messages. the script goes a little something like this : Address = '[EMAIL PROTECTED]'From = ' [EMAIL PROTECTED]'message = 'From: [EMAIL PROTECTED]: %s\r\nSubject: %s\r\n\r\n%s' % (Address,'alert',message) server.sendmail(From, Address, message)most of the time it goes thru ok. but only some providers have a problem. However, those same providers get messages if i send them thru Evolution.any ideas of what to check out? The second argument to SMTP.sendmail is supposed to be a sequence. You are sending a sequence (a string), so you do not get a complaint, but it is not the sequence you want. Try this: server.sendmail(From, [Address], message) -Arcege-- There's so many different worlds,So many different suns.And we have just one world, But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Self
Im not the OP, but this clears up some stuff for ma about "self". I thank you for your time to post this. -shawnOn 7/31/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote: Sebastian Smith wrote:> I am new to Python, real new. I am loving the language and learning> fast but I have hit a wall with the 'self'. I have Googled and> searched and read a few definitions but it still doesn't make sense to > me.>> I would love to hear some of your 'layman's definitions' on the self.>> Thank you all,>> Ben.> ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor>>Consider this:#--start code def f():print 'hello' >>> a = f >>> a >>> a()hello >>> f >>> f()hello #-- end codeSee how whenever you define a function, it creates a 'function' object?This means you can do anything with the function, assign a variable to it,put it in a list or a dictionary, etc.we assigned the variable 'a' to the function 'f', so we could call function 'f' using either 'a()' or 'f()'.The reason we're allowed to have as many variables pointing to the samefunction as we want is because the function always does the same thingwhen passed the same parameters (more or less.) However, when you have a 'Class' object, it has its own collectionof variables that it can modify, and its own set of functions that workon its variables. Because of this, you might want one class to doa certain thing and another class to do something else. Consider the following class:#-- start codeClass Address(object):def __init__(street,city,zip): print "Street: %s, City: %s, Zip: %s" % (street,city,zip)#-- end codeWe can do whatever we want with these variables inside of our __init__ function.If we call the function, using Address.__init__('1232 west highwayboulevard','indianapolis','1')it will print the string 'Street: 1232 west highway boulevard, City:indianapolis, Zip: 1' That's cool, but what if we want to store the values of these attributes?Well, if we're going to store the values, we'll want to make a separatecopy of the classthat we can modify, so that we don't have to change the original. This is where self comes in.#-- start codeClass Address(object):def __init__(self,street,city,zip): self.street = street self.city = city self.zip = zipdef output(self): print "Street: %s, City: %s, Zip: %s" %(self.street,self.city,self.zip)#-- end codeNow we can make a separate copy of the Address class, calledan 'instance' of the class, like this: >>> address1 = Address('1232 lexington drive','Annapolis','32423')when we call the output method of address1 we see: >>> address1.output()Street: 1232 lexington drive, City: Annapolis, Zip: 32423 Now say we want to change the city name, cause we meant to put'Indianapolis.' All we have to do is this:address1.city = 'Indianapolis'Basically, when you call any function inside of a class, using a class instance,(calling address1.anything is calling a function in an instance of a class,calling Address.anything is calling the function from the original copyof the class.)the first argument passed will be 'self', which is just the entire contents of the class.Hope that helps, I'd go more in-depth but I gotta run.Luke___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about headers and smtplib
Hey there, me again with another question about headers.. if i use my python script to send an email, it gets rejected by some providers. but another app that i use can send the same email and it gets thru. i have sent myself test messages from both apps and looked at the headers. the only difference in one from the other is that in the headers of the other app (not my python script) there exist the following lines: MIME-Version: 1.0 X-Mailer: OstroSoft SMTP Control (4.0.20) Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7-bit i do not understand how to make mine work and include (or configure to) the above example. anyone point me in a right direction ? thanks, shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about headers and smtplib
OK, this worked, please disregard my last. The online docs at python.org told me the answer to that one. Between their example and yours, i am able to make it work. thanks a whole bunch ! shawnOn 7/31/06, Justin Ezequiel <[EMAIL PROTECTED]> wrote: When I first started with Python, I used MimeWriter to create E-mails.Then some mail servers rejected my E-mails.Some research (google) indicated (to me) that I needed a MIME-Version header.(Can't recall now if I also needed a Content-Type header.) Anyway, more research (Python docs) indicated that I should use theemail package instead.I have been doing so since and have not had reports of anymore rejected E-mails.Hope this helps.>>> import email >>> from email.MIMENonMultipart import MIMENonMultipart>>> from email.Utils import formataddr>>> format_addresses = lambda pairs: ', '.join([formataddr(pair) forpair in pairs]) >>> msg = MIMENonMultipart('text', 'plain', charset='us-ascii')>>> msg.set_payload('Foo Bar')>>> msg.add_header('From', formataddr(('Justin', '[EMAIL PROTECTED]'))) >>> msg.add_header('To', format_addresses([('Justin', '[EMAIL PROTECTED]'),('You', '[EMAIL PROTECTED]')]))>>> print msg.as_string()Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0From: Justin <[EMAIL PROTECTED]>To: Justin <[EMAIL PROTECTED]>, You <[EMAIL PROTECTED]>Foo Bar>>> ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] quick OO pointer
Hello there,a while back i wrote a module called DbConnector.py that allowed me to run different types of SQL queries. Cool enough.i did it mostly to handle the open and close of a db connection so i wouldn't have to worry about 'too many connection' errors. it makes a connection, runs a query, then closes the connection. The reason i write this, is that i know how the module works to make a connection 'object'now, i have a few functions in some scripts that i would like to reuse across the board. But, they dont really fit the "object" thing, i dont thing. Basically, i have a bunch of functions that do different things and i would like one script to hold them all. do i need to define a class for this, or can you import a function from another script ?like if i have def write_something_to_log(logfile, something) f = open(logfile, 'a') f.write('%s\n' % something) f.close() return 'success'and i wanted to use this same function in about four different scripts, do i need a class ? Do i need to just create a script full of common functions that i can access ? and if so, how ? usually in the tutorials i read, they deal with OO and classes. Most commonly a class called Person. Then person has different attributes. But these functions are just bits of code that i want to reusewhat is the cleanest way to do something like this ? thankssk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick OO pointer
Way cool, thanks a lot. I have one more small question.If my script that needs to call a function from another module, and the module itself both require, say, the string module do i need to import it in both?If i just import string on my original script, will the module know what to do with it? and if so, is that good practice ?thanks againshawnOn 8/7/06, Alan Gauld <[EMAIL PROTECTED] > wrote:> now, i have a few functions in some scripts that i would like to > reuse> across the board. But, they dont really fit the "object" thing, i> dont> thing. Basically, i have a bunch of functions that do different> things and i> would like one script to hold them all. You can put normal functions in a module and reuse them sure.If they operate on the same kinds of data then a class would bemore appropriate but otherwise functions are fine.Its probably good to try to group them into families if possible. And you definitely want to use Functional Programming principlesto maximise reuse. By that I mean:1) No use of global variables2) Pass everything in by parameters3) Use default values to minimise the number of values the user sets 4) pass multiple values back in tuples where appropriate5) make sure that the same set of input values alwaysreturns the same value - no hidden stateConsider a number of smaller modules with related functionns too. Its tempting to just create a module called mystuff or similar thatholds everything, but you then wind up with every projectdepending on mystuiff and small changes affect lots of code.Better to have small modules with only a few functions that can be imported as needed. Grouping the functions around the kindof data they manipulate is a good start - but that brings us backto objects again :-)> def write_something_to_log(logfile, something) >f = open(logfile, 'a')>f.write('%s\n' % something)>f.close()>return 'success'>> and i wanted to use this same function in about four different> scripts, do i > need a class ? Do i need to just create a script full of common> functions> that i can access ? and if so, how ?### file: mylogger.pydef write_something_to_log(logfile, something) f = open(logfile, 'a')f.write('%s\n' % something)f.close()return 'success' file myprog.pyimport myloggermylogger.write_something ('logfile.txt', 'hello world')##As simple as that!Just make sure the module file is where it can be found by import...More on creating modules in my tutorial topic on "Functions & Modules".Alan GauldAuthor of the Learn to Program web sitehttp://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to get an email attachment
lo there pythoneers !i have a simple script to pull some emails from a pop server.so far, its working. What i need to do is get an attachment. That attachment is going to be encoded in base 64.so, i am looking and i can't find how to get the attachment. I have some info on the base64 module, so i shouldn't have a problem when i get it... here is what i have so far#!/usr/bin/pythonimport poplibimport stringimport timeserver = poplib.POP3('mail.xit.net')server.user('moulder') server.pass_('trustno1')# server.list returns message info from server in # form of response, message_list, size where message_list# is a list of messages in form of 'message_id size'message_list = server.list () i = 0for message in message_list[1]: i += 1 message_parts = string.split(message,' ') message_id = message_parts[0] print 'message id is %s\n' % message_id total_email_message = server.retr(message_id)[1] for line in total_email_message: print line print 'deleting message' # not deleting for right now # server.dele(message_id) time.sleep(1) print 'done' server.quit()any ideas would be greatly appreciated.if you have read this far down, thanks for your time.sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Big wad of Python tutorials
way cool, thanks !-skOn 8/21/06, Carroll, Barry <[EMAIL PROTECTED]> wrote: > -Original Message-> Date: Mon, 21 Aug 2006 13:52:45 -0700 (PDT)> From: Terry Carroll <[EMAIL PROTECTED]>> Subject: [Tutor] Big wad of Python tutorials > To: tutor@python.org> Message-ID:> <[EMAIL PROTECTED] >> Content-Type: TEXT/PLAIN; charset=US-ASCII>>> This page, consisting of links to a few hundred topically sortedPython> tutorials, was mentioned on Digg recently. I thought I'd pass on the URL:>> http://www.awaretek.com/tutorials.html>> Many of the URLs will be familiar to some on this list, but many moreare> new, certainly at least to me. >Thanks, Terry. That link looks like a great resource. I think I'llstart with the GUI sections.Regards,Barry[EMAIL PROTECTED]541-302-1107 We who cut mere stones must always be envisioning cathedrals.-Quarry worker's creed___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to get an email attachment
Yes, indeed. I found in the essential reference book. It looks like it works in the email module also. I will try a few things out here and let you know how it goes.thanks.shawn On 8/21/06, Alan Gauld <[EMAIL PROTECTED]> wrote: I'm no expert here, but isn't there a Mime module forhandling mail attachments? Might be worth a look.Alan G.- Original Message -----From: "shawn bright" < [EMAIL PROTECTED]>To: "tutor-python" <tutor@python.org>Sent: Monday, August 21, 2006 9:50 PMSubject: [Tutor] how to get an email attachment > lo there pythoneers !>> i have a simple script to pull some emails from a pop server.> so far, its working. What i need to do is get an attachment. That> attachment> is going to be encoded in base 64. > so, i am looking and i can't find how to get the attachment. I have> some> info on the base64 module, so i shouldn't have a problem when i get> it...>> here is what i have so far >> #!/usr/bin/python>> import poplib> import string> import time>> server = poplib.POP3('mail.xit.net')> server.user('moulder') > server.pass_('trustno1')>> # server.list returns message info from server in> # form of response, message_list, size where message_list> # is a list of messages in form of 'message_id size' > message_list = server.list()>> i = 0> for message in message_list[1]:>i += 1>>message_parts = string.split(message,' ')>message_id = message_parts[0] >print 'message id is %s\n' % message_id>total_email_message = server.retr(message_id)[1]>for line in total_email_message:>print line>print 'deleting message' ># not deleting for right now># server.dele(message_id)>time.sleep(1)>print 'done'>> server.quit()>> any ideas would be greatly appreciated.> if you have read this far down, thanks for your time. >> sk> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] prob with 64 encoded email attachement
hello there, i am having a bit o trouble being able to read a base64 encoded email attachement. here is the script. import email import poplib import base64 import os email_folder = 'emails/' mime = "application/octet-stream" def WriteAttachment(msg): for part in msg.walk(): print part if part.get_content_type() == mime: name = part.get_filename() data = ""> email_folder = 'emails/' f = file('%s%s'%(email_folder,name),'wb') f.write(data) f.close() ms = poplib.POP3('my.mailserver.net') ms.user('me') ms.pass_('pass') msgcount = len(ms.list()[1]) ii = 0 for i in range(msgcount): ii+=1 if ii > 1: break response, msg_as_list, size = ms.retr(i+1) msg = email.message_from_string('\r\n'.join(msg_as_list)) WriteAttachment(msg) dumped_files = os.listdir(email_folder) i = 0 for d_file in dumped_files: i+=1 base64.decode(open("%s%s" % (email_folder,d_file)), open("out.txt", "w")) the issue is when it gets to the part of decoding. The traceback says binascii.Error: Incorrect Padding. but i am certain that the info as it is being sent is good. anyone see where i may be missing it here ? thanks. -shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] revisiting struct module
Hey there,I am writing this because there is something that I am not understanding about the struct module.I have to send a message over a socket. The message has to be exactly 4 bytes, and the last bit has to be the value of 200. so like this:null,null,null,200 would be the message, and the 200 has to be an unsigned long int.I know the stream of info that I am supposed to send the server is big endian. I also know that I should be using the struct.pack(), but I don't know how to set this up.This is actually only part of the message, but I am trying to learn this as i go.thanks for any tips.shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] revisiting struct module
Luke ! That worked ! Man, if you knew how i have pulled my hair out over this for a while. I did not wind up using the struct at all. I really thought that I was supposed to, but once i made the message with ord. Like ord(0)+ord(0)+ord(0)+ord(200)... it worked. So i guess this means that it doesn't matter if its big endian or not ? anyway, thanks for lots of help, i would have replied sooner, but i was tinkering. -sk On 9/28/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote: shawn bright wrote:> Hey there,> I am writing this because there is something that I am not> understanding about the struct module.Okay, let's see what we can do.> I have to send a message over a socket. The message has to be exactly > 4 bytes, and the last bit has to be the value of 200.Okay, that makes sense.Except you used the term 'last bit'. Do I understand you to mean 'thelast part' and not 'the last bit (0/1)'?> so like this: > null,null,null,200 would be the message, and the 200 has to be an> unsigned long int.Hmm, an unsigned long int? Isn't that 4 bytes?Do you meanastr = chr(0)+chr(0)+chr(0)+chr(200)?I can't really answer your specific question without this information. >> I know the stream of info that I am supposed to send the server is big> endian.> I also know that I should be using the struct.pack(), but I don't know> how to set this up.Basically, if the first 3 elements of the messages are null _characters_ and the 200 is an unsigned long int (which is more than a 4-byte string)formatstr = '>cccL'packedstruct = struct.pack(formatstr,chr(0),chr(0),chr(0),200)Is probably how you'd do it.>> This is actually only part of the message, but I am trying to learn > this as i go.Sounds like a plan.HTH,-Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] revisiting struct and bytes again.
Hey there,this time my question is a bit simpler.i can make a byte a string or number or whatever now. Up to the number 255.I now have a problem with something that comes in as a 4 byte representation of the number of seconds since 1970. I have been using ord(byte) to make sense of the messages so far, but i don't know how to add bytes greater than 255.the c program that sends us these defines the variable as an unsigned long int. anyone know how to make these four bytes a number of seconds ?thankssk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about number of threads
Hey there, i have an app that runs several processes as threads. using the threading.Thread() now, i have another app that does the same thing. Now, pretty soon, we will be combining all the features of the two packages together into one app. My question is, is there a limit on how many threads one GUI application can have running in the background ? Most of them are sleeping most of the time. They wake up and do something every 10 seconds, 20 minutes, etc... Any pitfalls out there i shoud know about ? thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: question about number of threads
-- Forwarded message --From: shawn bright <[EMAIL PROTECTED]>Date: Oct 12, 2006 9:15 AM Subject: Re: [Tutor] question about number of threadsTo: Kent Johnson <[EMAIL PROTECTED]>oh, well then i do not have anything to worry about. I was talking about a move from 6 threads to 10. he he. Thanks for the advice ! shawnOn 10/12/06, Kent Johnson < [EMAIL PROTECTED]> wrote: shawn bright wrote:> Hey there,> i have an app that runs several processes as threads.> using the threading.Thread()>> now, i have another app that does the same thing. Now, pretty soon, we > will be combining all the features of the two packages together into one> app.>> My question is, is there a limit on how many threads one GUI application> can have running in the background ? > Most of them are sleeping most of the time. They wake up and do> something every 10 seconds, 20 minutes, etc...IIRC the number of threads is limited by memory - each thread requiressome heap space for its stack, etc. I don't think you will have trouble until you have hundreds or thousands of threads.For example on my computer this program prints 1031 before it exits withthread.error: can't start new thread:import timefrom threading import Thread, activeCount def run(): while 1: time.sleep(1)while 1: print activeCount() t=Thread(target=run) t.setDaemon(1) t.start()(The setDaemon() call lets the application exit normally when it gets an exception; otherwise it hangs with all the threads running.)Kent___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] need some class / module help
Hey there,I am trying to create a module with one classthe module name is group.pyit looks like this so farimport DbConnectorclass Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12)position = mygroup.position() # gives me position of group where id = 12mygroup.set_position(13) # changes value of position to 13is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later.Just wanted to know if i am on the right track.if you have read this far, thanks ! sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
Hey thanks for the help, yes, the class in in another file called group. the class Group is the only class in the module. I am doing this because the script that will call it is not the only place in all our scripts where it can be used. I have been doing stuff with python for over a year now, thought i would take advantage of some stuff that might save me some time. thanks againshawnOn 10/20/06, Bob Gailer <[EMAIL PROTECTED]> wrote: shawn bright wrote: Hey there, I am trying to create a module with one class the module name is group.py it looks like this so far import DbConnector class Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12) position = mygroup.position() # gives me position of group where id = 12 mygroup.set_position(13) # changes value of position to 13 Is this code in another module? If so you need: import group and mygroup = Group.group(12) should be (module name followed by class name) mygroup = group.Group(12). mygroup.position() # this is a call, and position is not callable. should be mygroup.position "select `name`, `position` from `groups` where `id` = '"+id+"' " is OK but an easier to read version is: "select `name`, `position` from `groups` where `id` = '%s'" % (id,) is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later. Just wanted to know if i am on the right track. if you have read this far, thanks ! sk ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
oh, one more thing.these objects are going to be created at the rate of about 20 / minute in a thread.at some point is this going to be a problem ? do they go away over time?Or do i need to write something that will kill them? thanksskOn 10/20/06, shawn bright <[EMAIL PROTECTED]> wrote: Hey thanks for the help, yes, the class in in another file called group. the class Group is the only class in the module. I am doing this because the script that will call it is not the only place in all our scripts where it can be used. I have been doing stuff with python for over a year now, thought i would take advantage of some stuff that might save me some time. thanks againshawnOn 10/20/06, Bob Gailer < [EMAIL PROTECTED]> wrote: shawn bright wrote: Hey there, I am trying to create a module with one class the module name is group.py it looks like this so far import DbConnector class Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12) position = mygroup.position() # gives me position of group where id = 12 mygroup.set_position(13) # changes value of position to 13 Is this code in another module? If so you need: import group and mygroup = Group.group(12) should be (module name followed by class name) mygroup = group.Group(12). mygroup.position() # this is a call, and position is not callable. should be mygroup.position "select `name`, `position` from `groups` where `id` = '"+id+"' " is OK but an easier to read version is: "select `name`, `position` from `groups` where `id` = '%s'" % (id,) is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later. Just wanted to know if i am on the right track. if you have read this far, thanks ! sk ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
if i name them, like bob = group.Group(some_id) ?what is going to happen is that each time, the variable will create a different objectlike while 1: group = group.Group(some_id) do some stuff with group. so since it keeps getting replaced, it should be ok without some way to destroy it ?thanksOn 10/20/06, Simon Brunning < [EMAIL PROTECTED]> wrote:On 10/20/06, shawn bright < [EMAIL PROTECTED]> wrote:> oh, one more thing.> these objects are going to be created at the rate of about 20 / minute in a> thread.> at some point is this going to be a problem ? do they go away over time? > Or do i need to write something that will kill them?If you don't keep references too them (i.e. by having names that arebound to them, or by keeping them in collections) then they'll go away- usually as soon as the last reference to them is gone. --Cheers,Simon B[EMAIL PROTECTED]http://www.brunningonline.net/simon/blog/___ Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
way cool, thanks much guys.skOn 10/20/06, Python <[EMAIL PROTECTED]> wrote: On Fri, 2006-10-20 at 13:44 -0500, shawn bright wrote:> if i name them, like bob = group.Group(some_id) ?>> what is going to happen is that each time, the variable will create a> different object >> like> while 1:> group = group.Group(some_id)> do some stuff with group.>> so since it keeps getting replaced, it should be ok without some way> to destroy it ? You can verify this by putting some kind of signal in the __del__method. For instance:>>> class A:... def __del__(self): print "destroyed"...>>> bob = A() >>> bob = A()destroyed>>> dir()['A', '__builtins__', '__doc__', '__name__', 'bob']So you can see that binding the name "bob" to a different instanceresulted in destroying the first one. >>> thanks>>> On 10/20/06, Simon Brunning <[EMAIL PROTECTED]> wrote:> On 10/20/06, shawn bright < [EMAIL PROTECTED]> wrote:> > oh, one more thing.> > these objects are going to be created at the rate of about> 20 / minute in a> > thread.> > at some point is this going to be a problem ? do they go > away over time?> > Or do i need to write something that will kill them?>> If you don't keep references too them (i.e. by having names> that are> bound to them, or by keeping them in collections) then they'll > go away> - usually as soon as the last reference to them is gone.>> --> Cheers,> Simon B> [EMAIL PROTECTED]> http://www.brunningonline.net/simon/blog/> ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor>> ___ > Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor--Lloyd KvamVenix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] can i pass a list to a function and get one back ?
hey there, i was just wondering if i could get a list back from a function.something likedef return_a_list(some_var): some_list = [] for i in range(5): var = some_var + i some_list.append(var) return some_listis this cool ?thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i pass a list to a function and get one back ?
great, thanks, i have idle right here, would have been just as easy.sorry about thatskOn 10/21/06, Bill Campbell < [EMAIL PROTECTED]> wrote:On Sat, Oct 21, 2006, shawn bright wrote:> > hey there, i was just wondering if i could get a list back from a> function.> something like> def return_a_list(some_var):> some_list = []> for i in range(5): > var = some_var + i> some_list.append(var)> return some_list> is this cool ?Ayup!The best way to find answers to questions like this is to just doit, and see what python does. Bill--INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLCURL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676``It will be of little avail to the people that the laws are made by men oftheir own choice if the laws be so voluminous that they cannot be read, or so incoherent that they cannot be understood.''-James Madison, Federalist Paper #62___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i pass a list to a function and get one back ?
way cool, thanks. I am always looking for ways to clean things up-skOn 10/21/06, Danny Yoo <[EMAIL PROTECTED] > wrote:> great, thanks, i have idle right here, would have been just as easy. > sorry about thatNo problem; it's cool.>> > hey there, i was just wondering if i could get a list back from a>> > function.>> > something like>> > def return_a_list(some_var): >> > some_list = []>> > for i in range(5):>> > var = some_var + i>> > some_list.append(var)>> > return some_list>> > is this cool ? It's cool. *grin*One small comment: we often don't need to use temporary variables like'var'.def return_a_list(some_var):some_list = []for i in range(5):some_list.append(some_var + i) return some_listSometimes a temporary variable is useful, and sometimes not. Here, itseems like it's not too necessary.Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i pass a list to a function and get one back ?
he he heOn 10/23/06, John Fouhy <[EMAIL PROTECTED]> wrote: On 23/10/06, Kent Johnson <[EMAIL PROTECTED]> wrote:> or for that matter>return range(some_var:some_var+5)[nit-pick]That would berange(some_var, some_var+5) :-)--John.___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem importing class
hey therei have written a module called site.pyin the file i have this:import DbConnectorimport sensorclass Site(object): "site object" def __init__(self, id): self.id = id self.con = DbConnector.DbConnector() id = str(self.id) stats = self.con.getOne("selct `group_id`, `name`, `ivr_code`, \ `site_type`, `notes`, `sensor_id` \ from `sites` where `id` = '"+str(id)+"' ") self.group_id = stats[0] self.name = stats[1] self.ivr_code = stats[2] self.site_type = stats[3] self.notes = stats[4] self.sensor_id = stats[5] def get_sensor(self): self.sensor = sensor.Sensor (self.sensor_id) return self.sensorok, in the program i am trying to run i have these lines:import sitenew_site = site.Site(id_number)and this is what my output is:Traceback (most recent call last): File "./new_camp.py", line 2014, in on_site_tree_view_row_activated acitve_site = site.Site(id_number)AttributeError: 'module' object has no attribute 'Site'It looks like the same code works for a different module i have ; i don't get what i could be missing here, any tips?if you have read this far, thanks for your time.sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem importing class
Hey thanks for the help, gents,i renamed site.py to site_obj.py and my import and statement.everything is working now. Thank you guys very very much.shawnOn 10/26/06, Danny Yoo <[EMAIL PROTECTED]> wrote: Hi Shawn,It looks like people have identified the problem, that your site.py moduleisn't being found because it conflicts with something from Python'sStandard Library.This isn't the first time this kind of problem has hit people. This problem is well known and is the subject of a Python Enhancement Proposal(PEP 328). If you're using Python 2.5, you can use a new feature called'absolute_import' to avoid the import problem. See: http://docs.python.org/whatsnew/pep-328.htmlfor more details.In the meantime, if you can't depend on using Python 2.5 yet, just renameyour site.py module to something else to avoid the collision betweenPython's own site.py module and your own. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [pygtk] ListStore question
this is cool, ill give it a shotskOn 10/27/06, euoar <[EMAIL PROTECTED]> wrote: euoar escribió:> mc collilieux escribió:>> euoar wrote:>> I'm learning the use of liststores and treeviews. I have wrotten this litle class as exercice: # name is the name of the new column to add, values is a tuple with the values to add def add_result (self, name, values): self.iter = self.liststore.append (values[0]) for value in values: self.liststore.insert_after(self.iter, value)>> rereading the tutorial, I note "...The row parameter specifies the data>> that should be inserted in the row after it is created ... If row is >> specified it must be a tuple or list containing as many items as the>> number of columns in the ListStore...so self.liststore.insert_after(self.iter, [value])>> >> Hope it's the good answer... PS : sorry for the answer directly to your mail. too quickly clic>>> That's exactly the solution. It has to be a tuple. Thank you very much > for your help!>>> __ LLama Gratis a> cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por> minuto. http://es.voice.yahoo.com> ___> pygtk mailing list pygtk@daa.com.au> http://www.daa.com.au/mailman/listinfo/pygtk> Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/>I think I have the solution (I'm answering myself to avoid people to waste time thinking in my question):args = [str, str, str]gtk.ListStore(*args)__LLama Gratis a cualquier PC del Mundo.Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about pylab
hey there,i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time.the docs say to use the function plot_date() but i cannot seem to get the values to agree. I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice. thanks for your time,sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about pylab
ok, looks like the date2num() function on a datetime.datetime object is working. So cool.i am very new at this, so i may be back ( read probably be back ). Thanks much for the tips.i appreciate it a lot.sk On 10/31/06, Kent Johnson <[EMAIL PROTECTED]> wrote: shawn bright wrote:> hey there,> i am trying to use a graph and chart app called matplotlib, but i cannot> figgure out how to have it plot a simple chart over time.> the docs say to use the function plot_date() but i cannot seem to get > the values to agree.> I am sending datetimes to the charting app for x, and the y is a list of> values that the our equipment reports.> sometimes there are lots of reports in a row, and i would like the chart > to show it like that instead of plotting out every time as an evenly> spaced tick on the x scale. Does this make any sense, what i am after> here? Anyway, if any of you have much experience with this sort of > thing, or may suggest a package (pylab is my first attempt) please send> me some advice.I have used pylab to create a scatterplot of date vs value. The datevalues were created by calling pylab.date2num () on a datetime.datetimevalue. The axes were set up with this code:# Set up the xaxisax = axes([0.05, 0.05, 0.9, 0.9])ax.xaxis.set_major_locator(MinuteLocator(interval=10))ax.xaxis.set_minor_locator (MinuteLocator())ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))I called pylab.scatter() to create the plot.HTH,Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about __init__ in a class
Hello there all.i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this: class Sensor_Object(object): def __init__(self, id, monitor): if id: self.id = id load values from the database value1 = somevalue value2 = someOthervalue else: self.monitor = monitor get some values from database value1 = somevalue value2 = someothervaluenow i could call it like this: new_monitor = sensor.Sensor('', 'XJ191')ornew_monitor = sensor.Sensor('3433', '')to load based on the other variable.i think that this would work, but i was thinking that there must be a cleaner way to do it. any suggestions ?sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
Thats a lot better, thanks, will use it like that.-shawnOn 11/13/06, Mike Hansen <[EMAIL PROTECTED] > wrote:> -Original Message-> From: [EMAIL PROTECTED]> [mailto:[EMAIL PROTECTED]] On Behalf Of shawn bright> Sent: Monday, November 13, 2006 11:45 AM> To: tutor-python> Subject: [Tutor] question about __init__ in a class >> Hello there all.> i have a class that i need to load some class variables> depending on what is passed to the class, it would either be> set up using one variable or another. The values for the > class variables would be loaded from a database. But how it> is looked up depends on how its called. Like this:>> class Sensor_Object(object):> def __init__(self, id, monitor): > if id:>self.id = id>load values from the database>value1 = somevalue>value2 = someOthervalue> else: >self.monitor = monitor>get some values from database>value1 = somevalue>value2 = someothervalue>> now i could call it like this: >> new_monitor = sensor.Sensor('', 'XJ191')> or> new_monitor = sensor.Sensor('3433', '')> to load based on the other variable.>> i think that this would work, but i was thinking that there > must be a cleaner way to do it.> any suggestions ?>> skI don't know if it's cleaner, but it might be easier to read if you usedefault named arguments.def __init__(self, id = None, monitor = None): Calling itnew_monitor = sensor.Sensor(monitor = 'XJ191')new_monitor = sensor.Sensor(id = '3433')Check to make sure one or the other arguments is supplied. Otherwisethrow an exception.Maybe there'll be some better ideas from other posters. Mike- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
hey thanks, did not think about the possible consequences of the use of a built in as a variable name.-skOn 11/13/06, Andreas Kostyrka < [EMAIL PROTECTED]> wrote:* shawn bright < [EMAIL PROTECTED]> [061113 19:46]:> Hello there all.> i have a class that i need to load some class variables depending on what is> passed to the class, it would either be set up using one variable or > another. The values for the class variables would be loaded from a database.> But how it is looked up depends on how its called. Like this:>> class Sensor_Object(object):>def __init__(self, id, monitor): >if id:> self.id = id> load values from the database> value1 = somevalue> value2 = someOthervalue>else: > self.monitor = monitor> get some values from database> value1 = somevalue> value2 = someothervalue>> now i could call it like this:> > new_monitor = sensor.Sensor('', 'XJ191')> or> new_monitor = sensor.Sensor('3433', '')> to load based on the other variable.>> i think that this would work, but i was thinking that there must be a > cleaner way to do it.Well, the code is basically ok, but I'd propose the following (it willhelp using the instances):class Sensor_Object(object):sensid = Nonemonitor = None ...Basically, provide class variables shadowing your "main" instanceattributes. I've also renamed id to sensid as id is an builtinfunction. (it's legal and ok to use id, but some tools like pylint like to complain about that style of shadowing.)The benefit is easy, in other methods, you can use code like this:if self.sensid is not None: instead of the more clumsyif hasattr(self, "sensid"): Andreas> any suggestions ?>> sk> ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] email content-type: text/plain
hey there all, i am using the email package and the phone provider i am trying to get a text message thru has sent me an email that says that they are looking for a tag that says 'content-type text/plain' i have tried about everything i can think of to get it in there, but everything i have tried has failed. here is what i have so far: address = '[EMAIL PROTECTED]' message = 'some text that needs to be delivered via text message' msg = MIMEText(message) msg['Subject'] = 'pivots' msg['From'] = '[EMAIL PROTECTED]' msg['To'] = address server.sendmail(msg['From'],msg['To'], msg.as_string()) any ideas ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] email content-type: text/plain
use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is what i am after. i am a bit confused here. It defaults to plain, but there is not anything in the message headers that say what type it is. Should i use MIMEText(message, 'text/plain') ? thanks sk On 11/16/06, Chris Hengge <[EMAIL PROTECTED]> wrote: Not sure if I'm really helping, but I want to try for all the help I've gotten... I took this from: http://docs.python.org/lib/module-email.message.html ## *class MIMEText*( _text[, _subtype[, _charset]]) Module: email.mime.text A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtypeis the minor type and defaults to plain. _charset is the character set of the text and is passed as a parameter to the MIMENonMultipart constructor; it defaults to us-ascii. No guessing or encoding is performed on the text data. # Going off this, I'd say you need to change: msg = MIMEText(message) to: msg = MIMEText(message, 'someTypeThatIsn'tPlain') On 11/16/06, shawn bright <[EMAIL PROTECTED]> wrote: > > hey there all, > i am using the email package and the phone provider i am trying to get a > text message thru has sent me an email that says that they are looking for a > tag that says 'content-type text/plain' > > i have tried about everything i can think of to get it in there, but > everything i have tried has failed. > > here is what i have so far: > address = '[EMAIL PROTECTED]' > message = 'some text that needs to be delivered via text message' > msg = MIMEText(message) > msg['Subject'] = 'pivots' > msg['From'] = '[EMAIL PROTECTED]' > msg['To'] = address > server.sendmail(msg['From'],msg['To'], msg.as_string()) > > any ideas ? > thanks > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] email content-type: text/plain
ok, will try this out tomorrow at work. thanks. sk On 11/16/06, Python <[EMAIL PROTECTED]> wrote: On Thu, 2006-11-16 at 15:57 -0600, shawn bright wrote: > use MIMEText(message, 'someTypeThatIsn'tPlain') ? but type/plain is > what i am after. > i am a bit confused here. It defaults to plain, but there is not > anything in the message headers that say what type it is. Should i use > MIMEText(message, 'text/plain') ? NO. server.sendmail takes a list of recipients. So rather than specifying msg['To'] for the recipients, use [address,'[EMAIL PROTECTED]'] You'll see exactly what you are sending. My emails that get sent with Python code pretty much like yours have the proper MIME tag: Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Do you have access to the server log files? Could something else be going wrong? My (works with email to text messaging and paging services) code: import urllib, urllib2, smtplib, pprint import email.MIMEText as MIMEText (snipped the dull parts) msg = MIMEText.MIMEText(msg_text) if subject: msg['Subject'] = subject msg['From'] = from_addy # to_addy is a list of recipients msg['To'] = ','.join(to_addy) server = smtplib.SMTP( mail_server) server.sendmail( from_addy, to_addy, msg.as_string()) server.close() > > thanks > sk > > On 11/16/06, Chris Hengge <[EMAIL PROTECTED]> wrote: > Not sure if I'm really helping, but I want to try for all the > help I've gotten... > I took this from: http://docs.python.org/lib/module- > email.message.html > ## > class MIMEText( > _text[, _subtype[, _charset]]) > Module: email.mime.text > > A subclass of MIMENonMultipart, the MIMEText class is used to > create MIME objects of major type text. _text is the string > for the payload. _subtype is the minor type and defaults to > plain. _charset is the character set of the text and is passed > as a parameter to the MIMENonMultipart constructor; it > defaults to us-ascii. No guessing or encoding is performed on > the text data. > > ##### > > Going off this, I'd say you need to change: > > msg = MIMEText(message) > > > to: > > msg = MIMEText(message, 'someTypeThatIsn'tPlain') > > On 11/16/06, shawn bright <[EMAIL PROTECTED]> wrote: > hey there all, > i am using the email package and the phone provider i > am trying to get a text message thru has sent me an > email that says that they are looking for a tag that > says 'content-type text/plain' > > i have tried about everything i can think of to get it > in there, but everything i have tried has failed. > > here is what i have so far: > address = '[EMAIL PROTECTED]' > message = 'some text that needs to be delivered via > text message' > msg = MIMEText > (message) > msg['Subject'] = 'pivots' > msg['From'] = '[EMAIL PROTECTED]' > msg['To'] = address > server.sendmail(msg['From'],msg['To'], msg.as_string > ()) > > any ideas ? > thanks > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] shebang question
Hey there all, what is the difference between #!/usr/bin/python and #!/usr/bin/env python ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] shebang question
well thanks for all the info, gents, i appreciate it a lot ! sk On 11/26/06, زياد بن عبدالعزيز الباتلي <[EMAIL PROTECTED]> wrote: "john maclean" <[EMAIL PROTECTED]> On Sun, 26 Nov 2006 01:34:28 + wrote: > From what I can tell/remember, the first works in the *nix environment > if python is in your $PATH, ... Actually, no. The first will try to feed the script to the executable "/usr/bin/python". If that doesn't exist (or is not executable) it'll fail. > ...the latter will find python "somehere" on your system by looking at > wher the executables should be. True, assuming there's "/usr/bin/env" on your system (and is executable) and that "python" is found in your "$PATH" (and is executable). The problem is that Python is not installed in the same place on all OSes! Some will install it under "/usr/local", others under "/opt". The idea of "/usr/bin/env" is that it's always installed there (or it should be!). So, you don't need to figure out where is python (or perl, ruby, make, sed, awk, or any other executable that "feeds" on scripts/text files) installed as long as it's in your "$PATH". (Of course, "env" have other uses. As long as I can tell, this is not the intended use of "env". See "info env" for more information, or if you don't have "info" see the manual.) Ziyad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to permanently add a module path
lo there, i am working with python in ubuntu, my app has some modules that i would like to import from anywhere. i can sys.path.append(my_module_dir)but it only lasts as long as that python session. how can i add a directory to the import path permantly ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to permanently add a module path
thanks, i usually intend to, getting used to gmail. thanks for all the help, all working now. shawn On 12/22/06, Christopher Arndt <[EMAIL PROTECTED]> wrote: shawn bright schrieb: > ok, > i am on ubuntu and there is no /etc/profile.d directory > i put this in the /etc/environment file > > PYTHONPATH=/usr/lib/python2.4/site-packages/pivotrac > export PYTHONPATH > > but it doesn't seem to be working. > There is no master python config file somewhere where all these are listed ? > i wonder becuase i add modules via apt, and they are put where they need > to be. Ok, I see, you're trying to add you module in the standard site modules path (/usr/lib/pythonX.Y/site-packages on Unices). This is an entirely different matter. You have two possibilities: 1) Turn your module directory into a paackage by adding a '__init__.py' file to it. This file may be empty. You can then iumport from your module like this: from pivotrac import mymodule For more information on Python module packages, see here: http://www.python.org/doc/current/tut/node8.html#SECTION00840 2) You can add a .pth file to the site-packages directory that points to your module directory. E.g. ass a file pivotrac.pth to /usr/lib/python2.4/site-packages/ that just contains one line: pivotrac For more information about .pth files, see here: http://www.python.org/doc/current/lib/module-site.html With both methods you don't need to change PYTHONPATH at all. Chris P.S. Please don't answer privately to somebody writing on the list, unless asked to do so. Reply to the list instead. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about importing threads
Hello there all. i have an app that has grown to about 4000 lines. It uses 6 threads and a GTK2 GUI. i was wondering if i could split it into seperate files that i could import. Each thread is a class. i did not think that this would be a problem, but some of the threads pass information to views and buffers. If i had a thread outside of the main file, could i pass a gtk object to it so that it could write to it when it needed too? and one last thing. If i did this, would i be able to only import the class when i started the thread, and then re-import it if i started the thread later . If so, this would allow me to work on a thread without having to restart the main program, and i could let the other threads keep running. As i find bugs, i could squash them without loosing any functionality of the other threads. Then if i wanted to stop or restart a thread by clicking a button, i could just re-import the class. is this ok ? thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
Kent, Thanks. this is great. Yes, when i start the thread, i also pass the gtk object to it. kinda like this. serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) serial_1.start() so i am wanting to change that, but i do not exactly know how to stop a thread once i have it running, so that i could start another one. anyway, thanks for the link and the info, i am going to get started on testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. thanks again shawn On 12/30/06, Kent Johnson <[EMAIL PROTECTED]> wrote: shawn bright wrote: > Hello there all. > i have an app that has grown to about 4000 lines. It uses 6 threads and > a GTK2 GUI. > i was wondering if i could split it into seperate files that i could > import. Each thread is a class. That should be fine. > i did not think that this would be a problem, but some of the threads > pass information to views and buffers. How do the threads find out about the views and buffers? If they are global objects then you will have a problem. If they are passed to the threads as parameters then it should be fine. > If i had a thread outside of the main file, could i pass a gtk object to > it so that it could write to it when it needed too? Yes. > and one last thing. If i did this, would i be able to only import the > class when i started the thread, and then re-import it if i started the > thread later . If so, this would allow me to work on a thread without > having to restart the main program, and i could let the other threads > keep running. As i find bugs, i could squash them without loosing any > functionality of the other threads. Then if i wanted to stop or restart > a thread by clicking a button, i could just re-import the class. > > is this ok ? You can use reload() to update a module that has been changed. You will also have to recreate any objects that were created from classes in the module so they become instances of the modified module. You might be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Kent > > thanks > shawn > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
great help, and great link, thanks again. shawn On 12/30/06, Kent Johnson <[EMAIL PROTECTED]> wrote: shawn bright wrote: > Kent, Thanks. > this is great. Yes, when i start the thread, i also pass the gtk object > to it. > kinda like this. > > serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) > serial_1.start() > > so i am wanting to change that, but i do not exactly know how to stop a > thread once i have it running, so that i could start another one. The usual way to stop a thread is to set a flag that the thread checks. Here is an example using a threading.Event as a flag: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 > anyway, thanks for the link and the info, i am going to get started on > testing this right away. This long a .py script is becomming a headache > and i think it will be easier by far if it is pulled apart somewhat. Yes, 4000 lines is pretty long for one file IMO. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
Thanks, Alan. Yes, the thing is getting to be a pain to deal with at this size, i am in-process of splitting out the classes into their own files. Thanks for your help. shawn On 12/30/06, Alan Gauld <[EMAIL PROTECTED]> wrote: "shawn bright" <[EMAIL PROTECTED]> wrote i > testing this right away. This long a .py script is becomming a > headache and > i think it will be easier by far if it is pulled apart somewhat. As a general rule of thumb, any Python script (or any programming language file for that matter!) that gets longer than 4 or 5 hundred lines should be looked at closely in terms of splitting it into modules. There are a few (very few) times where I've seen a thousand line file that was justified, but nearly any time you get beyond 500 lines you should be splitting things up - especially in high level languages like Python where the methods/functions tend to be short anyway. FWIW A quick check of the Python standard library shows the average file size there to be: 459 lines(*) And that's pretty high IMHO! There are 19 files over a thousand lines and the biggest file is over 3000 lines... which seems way too big to me! But that's out of 188 files... (*) Cygwin; Python 2.4 In case you want to repeat for your version I used: >>> libs = [len(open(f).readlines()) for f in glob('*.py')] >>> print sum(libs)/len(libs) >>> print max(libs) >>> print len([s for s in libs if s>1000]) Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to know if a file exists
hello there, i am writing an app for linux. what command would be easiest to test and see if a certain file exist ? i was going to do something like this try: file = open('/path/to/file', 'rb') return True except: return False but i thought that there would be an easier way. thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to know if a file exists
thanks, luke, Andre. appreciate it a lot shawn On 1/3/07, Andre Roberge <[EMAIL PROTECTED]> wrote: On 1/4/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote: > > shawn bright wrote: > > hello there, > > i am writing an app for linux. what command would be easiest to test > > and see if a certain file exist ? > > i was going to do something like this > > try: > > file = open('/path/to/file', 'rb') > > return True > > except: > > return False > You should except IOError here, just to be clear and such. > > > > but i thought that there would be an easier way. > The os module has some function for checking if files exist, I think. Yes, check out access(): http://docs.python.org/lib/os-file-dir.html André Or you could do > if targetfile not in os.listdir(directory): return False > else: return True > > But your original solution is okay. > HTH, > -Luke > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to stop a thread
hello there all, i have a python reference book that got me started knowing how to use threads, i can declare one as a class, and start it like this class SomeThread(threading.Thread): run_process = SomeThread() run_process.start() but how do i kill it ? This part is not in my book. Basically the thread works, and runs in a while loop. Is there a way to destroy the instance of it after creation ? thanks all shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to stop a thread
i can do that, will use my config file, thanks much and thanks for the link. shawn On 1/4/07, Kent Johnson <[EMAIL PROTECTED]> wrote: shawn bright wrote: > hello there all, > > i have a python reference book that got me started knowing how to use > threads, i can declare one as a class, and start it like this > > class SomeThread(threading.Thread): > > > run_process = SomeThread() > run_process.start() > > but how do i kill it ? This part is not in my book. Basically the thread > works, and runs in a while loop. Is there a way to destroy the instance > of it after creation ? A thread dies when it's run() method exits, so you have to contrive a way to make run() exit. The usual way is to set a flag that the thread checks. Here is an example using a threading.Event as a flag: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] need help with sending email
lo there all. i am in a tight spot because i need to send an email that it mime encoded plain-text ( not html or anything ) no attachements, no images, just text from a string. like message = 'some message' all the tutorials i find out there, and the cookbook recipies are for sending multipart messages, attachments, etc.. this needs to be simple, but needs to be able to reach a large variety of cell phone text message receivers. anyone know of a good tutorial or recipe out there ? thanks, shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help with sending email
right, thanks, Mike. i can send an email fine. Some of the providers we are trying to reach will reject anything that is not content type: text-plain thats what i need to know how to add. thanks again shawn On 1/5/07, Mike Hansen <[EMAIL PROTECTED]> wrote: > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of shawn bright > Sent: Friday, January 05, 2007 10:18 AM > To: tutor-python > Subject: [Tutor] need help with sending email > > lo there all. > > i am in a tight spot because i need to send an email that it > mime encoded plain-text ( not html or anything ) > no attachements, no images, just text from a string. like > message = 'some message' > all the tutorials i find out there, and the cookbook recipies > are for sending multipart messages, attachments, etc.. > this needs to be simple, but needs to be able to reach a > large variety of cell phone text message receivers. > > anyone know of a good tutorial or recipe out there ? > > thanks, > shawn > > This might help: http://effbot.org/librarybook/smtplib.htm Also, the docs on smtplib: http://docs.python.org/lib/module-smtplib.html Mike - NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor