Re: [Tutor] Using the time module to extract a semi-random number
On Wed, Sep 16, 2009 at 6:43 PM, Laurii wrote: > The exercise to modify a number guessing program from a fixed number "number > = 78" to using the time module and use the seconds at the time the program > is used to be the number. (i.e. if the clock on your computer says 7:35:25 > then it would take the 25 and place it in "number". time.localtime().tm_sec will give you the number of seconds as an integer without any conversions. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python queue
On Wed, Sep 16, 2009 at 8:04 PM, Jeff Peery wrote: > > Hello, > Does anyone know if there is there a way to look at a queue's contents? Or > prevent duplicate messages from being put into a queue? The docs don't show > anything useful. The reason is that I'm collecting and drawing data. one > thread collects, and one thread draws. each time one sample is collected by > the collector thread, a "draw message" is put into the queue to notify the > drawing thread. the dataset is shared between the threads and is continuously > growing as data is appended. The queue is used to notify the drawing thread > that it should draw. I use threading.Lock() to prevent any "sharing issues". > > The problem is that if the data collector thread is putting messages into the > queue faster than the drawing thread is getting them, then the drawing thread > is forced to redraw more times than it needs to and appears slow. However > since the dataset is shared the drawing thread only needs to draw once to be > updated for all the new samples. For example if 10 samples have been appended > by the data collector thread while the drawing thread drew once, then there > are now 10 messages for the drawing thread to get. yet it only needs to draw > once to reflect the 10 samples. so there are 9 redraws that are a waste of > energy. It sounds like what you really want is a flag. The collector thread sets the flag when data is available, the draw thread clears the flag when it starts to draw. If the flag is set multiple times before the draw, it still only triggers one draw. Take a look at threading.Event, it might work better than Queue. You could try to use qsize() to avoid putting an item in the queue if there is already something there, but you may have to introduce additional locks to avoid race conditions. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] python queue
Hello, Does anyone know if there is there a way to look at a queue's contents? Or prevent duplicate messages from being put into a queue? The docs don't show anything useful. The reason is that I'm collecting and drawing data. one thread collects, and one thread draws. each time one sample is collected by the collector thread, a "draw message" is put into the queue to notify the drawing thread. the dataset is shared between the threads and is continuously growing as data is appended. The queue is used to notify the drawing thread that it should draw. I use threading.Lock() to prevent any "sharing issues". The problem is that if the data collector thread is putting messages into the queue faster than the drawing thread is getting them, then the drawing thread is forced to redraw more times than it needs to and appears slow. However since the dataset is shared the drawing thread only needs to draw once to be updated for all the new samples. For example if 10 samples have been appended by the data collector thread while the drawing thread drew once, then there are now 10 messages for the drawing thread to get. yet it only needs to draw once to reflect the 10 samples. so there are 9 redraws that are a waste of energy. I was hoping there was some feature in the queue class the would prevent or discard a duplicate message. This way my drawing thread won't draw more than it needs to. thanks! Jeff ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using the time module to extract a semi-random number
Hi Katt, The following does the trick for me: number = int(time.strftime("%S", time.localtime())) There may be better ways to do it though. -Mal On Thu, Sep 17, 2009 at 8:43 AM, Laurii wrote: > Hello all, > > I am currently reading through the Tutorial for Non-Programers by Josh > Cogliati. I have had great success until now. > > The exercise to modify a number guessing program from a fixed number "number > = 78" to using the time module and use the seconds at the time the program > is used to be the number. (i.e. if the clock on your computer says 7:35:25 > then it would take the 25 and place it in "number". > > The following is what I have so far: > #* > # > # hilow2.py > # > # This program asks the user to guess a > # number. If it is wrong the program tells > # the user if it is higher or lower. The > # first one had a fixed assigned number. > # This program takes the last two digits > # of the time and assigns it as the random > # number. > # > #* > #*.h header files** > #* > #**modules* > from time import time, ctime > #* > #**define lists/dictionaries** > #* > #define functions* > #* > #*define global variables*** > the_time = ctime() > number = the_time > guess = 0 > guess_try = 0 > #* > #Main Program** > while guess != number: > guess = input("Guess a number:") > if guess != number: > if guess > number : > print "To High" > elif guess < number: > print "To Low" > guess_try = guess_try + 1 > print "Bingo! You are correct." > print "It only took you",guess_try,"tries." > #* > > I think it has to do with the fact that I am using the wrong time function > and am not familiar with how to cut out the seconds and send it to the > variable number. > > I believe I should use the strftime(format[,t]) but am not sure how to. All > help is appreciated. > > Thanks in advance, > > Katt > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using the time module to extract a semi-random number
Hello all, I am currently reading through the Tutorial for Non-Programers by Josh Cogliati. I have had great success until now. The exercise to modify a number guessing program from a fixed number "number = 78" to using the time module and use the seconds at the time the program is used to be the number. (i.e. if the clock on your computer says 7:35:25 then it would take the 25 and place it in "number". The following is what I have so far: #* # #hilow2.py # #This program asks the user to guess a #number. If it is wrong the program tells #the user if it is higher or lower. The #first one had a fixed assigned number. #This program takes the last two digits #of the time and assigns it as the random #number. # #* #*.h header files** #* #**modules* from time import time, ctime #* #**define lists/dictionaries** #* #define functions* #* #*define global variables*** the_time = ctime() number = the_time guess = 0 guess_try = 0 #* #Main Program** while guess != number: guess = input("Guess a number:") if guess != number: if guess > number : print "To High" elif guess < number: print "To Low" guess_try = guess_try + 1 print "Bingo! You are correct." print "It only took you",guess_try,"tries." #* I think it has to do with the fact that I am using the wrong time function and am not familiar with how to cut out the seconds and send it to the variable number. I believe I should use the strftime(format[,t]) but am not sure how to. All help is appreciated. Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert doc to txt on Ubuntu
2009/9/16 Carnell, James E : > > I am needing to access the text in hundreds of Microsoft .doc files on an > Ubuntu OS. I looked at win32 , but only saw support for windows. I am going > through all of these files to create a fairly simple text delimited file for > a spreadsheet. > > A) Batch convert to text files so I can access them > B) import some module that allows me to decode this format > C) Open Office allows batch conversion to .odc ,but still don't know how to > access > D) Buy a 24 pack, some Twinkies, and go watch David Hasselhoff reruns > > Opening .txt documents works fine. > > Currently get: > > inFile = open("myTestFile.doc", "r") > testRead = inFile.read() > > Traceback (most recent call last): > File "", line 1, in > test = inFile.read() > File "/usr/lib/python3.0/io.py", line 1728, in read > decoder.decode(self.buffer.read(), final=True)) > File "/usr/lib/python3.0/io.py", line 1299, in decode > output = self.decoder.decode(input, final=final) > File "/usr/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid > data > > Any help greatly appreciated Thanks bunches. > > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > FYI, open office .odc files are zip archives of xml files. It should be trivial to access the information from them, assuming OO is sensible in converting from the bloated .doc format. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDLE colon = syntax error
Carnell, James E wrote: I searched through archives and wasn't able to find the solution. Using IDLE, python 3, Ubuntu (default installations). Using command line: > if 1 == 1: print "equal" > equal Using IDLE: >if 1 == 1: print "equal" >SyntaxError: invalid syntax line 2 Just for kicks in IDLE: >ord(':') #see if it gives me some wack ASCII code >58 Oh well, I imagine this is easy, but I just don't know... (what I get for using a new computer and OS today) In Python 3, print is not a statement, but a function. So you need parentheses around its argument(s). The first time, you were presumably using a 2.x Python. You can check with import sys print (sys.version) Incidentally, 3.1 is much more stable than 3.0. And most of us do also keep a 2.x around, for all those things that aren't ready for 3.x DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] IDLE colon = syntax error
I searched through archives and wasn't able to find the solution. Using IDLE, python 3, Ubuntu (default installations). Using command line: > if 1 == 1: print "equal" > equal Using IDLE: >if 1 == 1: print "equal" >SyntaxError: invalid syntax line 2 Just for kicks in IDLE: >ord(':') #see if it gives me some wack ASCII code >58 Oh well, I imagine this is easy, but I just don't know... (what I get for using a new computer and OS today) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert doc to txt on Ubuntu
On Wed, Sep 16, 2009 at 3:03 PM, Carnell, James E < jecarn...@saintfrancis.com> wrote: > > I am needing to access the text in hundreds of Microsoft .doc files on an > Ubuntu OS. I looked at win32 , but only saw support for windows. I am going > through all of these files to create a fairly simple text delimited file for > a spreadsheet. > > A) Batch convert to text files so I can access them > B) import some module that allows me to decode this format > C) Open Office allows batch conversion to .odc ,but still don't know how to > access > D) Buy a 24 pack, some Twinkies, and go watch David Hasselhoff reruns > > Opening .txt documents works fine. > > Currently get: > > inFile = open("myTestFile.doc", "r") > testRead = inFile.read() > > Traceback (most recent call last): > File "", line 1, in > test = inFile.read() > File "/usr/lib/python3.0/io.py", line 1728, in read > decoder.decode(self.buffer.read(), final=True)) > File "/usr/lib/python3.0/io.py", line 1299, in decode > output = self.decoder.decode(input, final=final) > File "/usr/lib/python3.0/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > invalid data > > Any help greatly appreciated Thanks bunches. > > ubuntu comes with antiword, a program that does exactly this. I usually use > it through through the commands module in python. > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Convert doc to txt on Ubuntu
I am needing to access the text in hundreds of Microsoft .doc files on an Ubuntu OS. I looked at win32 , but only saw support for windows. I am going through all of these files to create a fairly simple text delimited file for a spreadsheet. A) Batch convert to text files so I can access them B) import some module that allows me to decode this format C) Open Office allows batch conversion to .odc ,but still don't know how to access D) Buy a 24 pack, some Twinkies, and go watch David Hasselhoff reruns Opening .txt documents works fine. Currently get: inFile = open("myTestFile.doc", "r") testRead = inFile.read() Traceback (most recent call last): File "", line 1, in test = inFile.read() File "/usr/lib/python3.0/io.py", line 1728, in read decoder.decode(self.buffer.read(), final=True)) File "/usr/lib/python3.0/io.py", line 1299, in decode output = self.decoder.decode(input, final=final) File "/usr/lib/python3.0/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data Any help greatly appreciated Thanks bunches. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
> Ansuman Dash wrote: > >Now I am trying to validate that the command is executed successfully. > >I have written following script to validate the log file which is created > >after running the command. Notice what's happening here: > >for line in f.readlines(): > >a=line This sets a to EACH line from the file, overwriting the previous one. What you end up with after that executes is a holding the LAST line in the file. > >if "Request timed out.." not in a: > >print("Ping is not successful.") > >pLogger.info("Ping is not successful.") Also... this looks backwards. If "Request timed out.." is NOT found then the ping was NOT successful? -- Steve Willoughby| Using billion-dollar satellites st...@alchemy.com | to hunt for Tupperware. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
(Don't top-post; it makes reading the thread quite confusing) Ansuman Dash wrote: Hi, Thank you very much for the quick response. Code is working fine. Now I am trying to validate that the command is executed successfully. I have written following script to validate the log file which is created after running the command. if os.access("C:/Python25/Own.log", os.F_OK): f = open("C:/Python25/Own.log") time.sleep(30) try: for line in f.readlines(): a=line if "Request timed out.." not in a: print("Ping is not successful.") pLogger.info("Ping is not successful.") else: print ("Ping is successful.") pLogger.info("Ping is successful.") finally: f.close() else: pLogger.info("File doesn't exist") = But it is not working, even if ping is successfully it is printing "Ping is not successful.". Can you please point out where I am making mistake. Thanks, AD On Wed, Sep 16, 2009 at 12:55 PM, Patrick Sabin wrote: Ansuman Dash schrieb: Hello Everybody, In Python scripting, how can I execute a command (which can be run from spcific directory) and then retrieve the result (after executing the command it give the command is executed successfull or not), so that I can validate it. Thanks, AD import os import subprocess os.chdir('/your/directory') p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) out = p.stdout.read() print out - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor As Sander says, your if/else is backwards.Presumably the message "Request timed out" is there only when it's unsuccessful, not when it works. But you have another, even more subtle problem. If the log file is more than one line, you're only checking the last one. Unless you know it's the last one that'll contain the line, you need to move the "in" test inside the for loop. There are other things to fine-tune, but these are the important ones. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] ImportError: cannot import name log
Hi, Below is the content of __init__.py import sys from django.core.signals import got_request_exception from . import log logger = log._get_logger() def got_request_exception_callback(sender, **kwargs): """Logging all unhandled exceptions.""" type, exception, traceback = sys.exc_info() logger.error(unicode(exception)) got_request_exception.connect(got_request_exception_callback) My question here is that what does *from . import log* doing I can see a module name log in the same folder. This import statement is throwing an error ImportError: cannot import name log. Thanks for all your help -- Cheers, Vishwajeet http://www.singhvishwajeet.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: utf locale sorting
On Wed, Sep 16, 2009 at 11:45 AM, Igor Mavrović - ma...@irb wrote: > Sorry Kent, I should have put it in the original message... > This is the way I call the sorted function: > > # resultSet looks like: [[("DN", {"":["", ...], ...})], ...] > > resultSetSortedByCn = sorted(resultSet, key=lambda x:(x[0][1]["sn"], > x[0][1]["givenName"])) > resultSetSortedByOu = sorted(resultSet, key=lambda x:(x[0][1]["ou"], > x[0][1]["sn"], x[0][1]["givenName"])) > > I have to use it like this for obvious reasons (sort by org-unit, surname > and then name). Therefore Rich's suggestion: > > print sorted(words, key=lambda o: locale.strxfrm(o[0])) > > can't work 'cause strxfrm's argument must be a string, not a tuple... How about this (assuming both arguments need to be transformed)? key=lambda x:(locale.strxfrm(x[0][1]["sn"]), locale.strxfrm(x[0][1]["givenName"])) Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: utf locale sorting
Sorry Kent, I should have put it in the original message... This is the way I call the sorted function: # resultSet looks like: [[("DN", {"":["", ...], ...})], ...] resultSetSortedByCn = sorted(resultSet, key=lambda x:(x[0][1]["sn"], x[0][1]["givenName"])) resultSetSortedByOu = sorted(resultSet, key=lambda x:(x[0][1]["ou"], x[0][1]["sn"], x[0][1]["givenName"])) I have to use it like this for obvious reasons (sort by org-unit, surname and then name). Therefore Rich's suggestion: print sorted(words, key=lambda o: locale.strxfrm(o[0])) can't work 'cause strxfrm's argument must be a string, not a tuple... What do you think? Igor - Original Message - From: Rich Lovely To: Igor Mavrović - ma...@irb Cc: tutor@python.org Sent: Wednesday, September 16, 2009 4:58 PM Subject: Re: [Tutor] Fw: utf locale sorting The key argument of sorted() and the like takes a function object, so you could do something like the following: def keyfunc(value): keyVal = value[0] #Or whatever lookups are needed return locale.strxfrm(keyVal) then you can call sorted with: print sorted(words, key=keyfunc) You could also do the same with a lambda: print sorted(words, key=lambda o: locale.strxfrm(o[0])) Hope that helps -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. - Original Message - From: Kent Johnson To: Igor Mavrović - ma...@irb Cc: tutor@python.org Sent: Wednesday, September 16, 2009 4:33 PM Subject: Re: [Tutor] Fw: utf locale sorting On Wed, Sep 16, 2009 at 9:51 AM, Igor Mavrović - ma...@irb wrote: Hi, I know about the use of locale module: import locale locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") print sorted(words, key=locale.strxfrm) but I have specific and complicated data structure (list of lists containing strings, tuples and dictionaries) due to LDAP search result data. So I use the 'key' option to get to the neaded attributes, and can't use it for the locale setting. How can I sort this monster list by attribute values inside it, and still get the correct sorting order? The key= parameter can be any function. What are you using now? Just add the call to locale.strxfrm() to your key function. If you are currently using operator.itemgetter or operator.attrgetter you will have to change to explicit attribute access. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: utf locale sorting
2009/9/16 Igor Mavrović - ma...@irb : > Hi, > > I know about the use of locale module: > import locale locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") print sorted(words, key=locale.strxfrm) > > but I have specific and complicated data structure (list of lists containing > strings, tuples and dictionaries) due to LDAP search result data. > So I use the 'key' option to get to the neaded attributes, and can't use it > for the locale setting. How can I sort this monster list by attribute values > inside it, and still get the correct sorting order? > > Anyone? Thanks in advance! > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The key argument of sorted() and the like takes a function object, so you could do something like the following: def keyfunc(value): keyVal = value[0] #Or whatever lookups are needed return locale.strxfrm(keyVal) then you can call sorted with: print sorted(words, key=keyfunc) You could also do the same with a lambda: print sorted(words, key=lambda o: locale.strxfrm(o[0])) Hope that helps -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: utf locale sorting
On Wed, Sep 16, 2009 at 9:51 AM, Igor Mavrović - ma...@irb wrote: > Hi, > > I know about the use of locale module: > import locale locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") print sorted(words, key=locale.strxfrm) > > but I have specific and complicated data structure (list of lists containing > strings, tuples and dictionaries) due to LDAP search result data. > So I use the 'key' option to get to the neaded attributes, and can't use it > for the locale setting. How can I sort this monster list by attribute values > inside it, and still get the correct sorting order? The key= parameter can be any function. What are you using now? Just add the call to locale.strxfrm() to your key function. If you are currently using operator.itemgetter or operator.attrgetter you will have to change to explicit attribute access. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] collecting certain data from a textfile
Please always reply-all so a copy goes to the Tutor list. Olli Virta wrote: Hi! Thanks for advice. I was thinking, if is there was other ways to get the wanted data out, than with that strip() method. Say what if I had to use it hundred times. Are you concerned with ease of coding or with performance. We usually don't worry about performance until in practice the program takes "too long". Regarding coding: create tuples of slices: as = (slice(1,38), slice(54,88)) bs = (slice(77,96), slice(1,16)) cs = (slice(23,33), slice123,133)) slices = (as, bs, cs) create a tuple of lines: (untested) a=f2.readline() if not a: break b=f2.readline() c=f2.readline() lines = (a,b,c) iterate over the lines and their respective slices: data2 = [] for x in range(len(lines)): for s in slices[x]: data2.append(lines[x][s].strip() OV 2009/9/15 bob gailer mailto:bgai...@gmail.com>> Olli Virta wrote: Hi! I got this simple but effective piece of code. It picks certain wanted pieces of data from a textfile based on database records and puts all of them them in a new textfile in certain order. I was wondering, could it be possible to make it otherwise in case that there's much more rows in that textfile and/or there's much more bits of data to collect? Otherwise is always possible! What is the problem? Why do you want it "otherwise"? data = open('data.txt','r') f1 = data.readlines() data.close() There is no need to do the above! You don't need a line count to control the loop. f2 = open('data.txt','r') Drop next lline: i=0 f3 = [] Change next two lines: while i < len(f1): a=f2.readline() To: while True: a=f2.readline() if not a: break b=f2.readline() c=f2.readline() data2 = ( a[1:38].strip()+';'+ a[54:88].strip()+';'+ b[77:96].strip()+';'+ b[1:16].strip()+';'+ c[23:33].strip()+';'+ c[123:133].strip()+';' ) wanted = (data2) If you are concerned about enough memory, write data2 to the file instead of collecting in a list. f3.append(wanted + "\n") Drop next line: i += 3 f4 = open('wanted.txt', 'w') f4.write(''.join(f3)) f2.close() f4.close() -- Bob Gailer Chapel Hill NC 919-636-4239 -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] strings and replace
On Wed, Sep 16, 2009 at 10:33 AM, Jojo Mwebaze wrote: > Hello There Again > > Might be a silly question but it has played me for the last two days! > > I have a string 'mystring' (pasted below), what i want to do is to change > the values of of NAXIS1 (=1024) and NAXIS2 (=2048) to some other values! > say NAXIS1 = 999 and NAXIS2 = 888. > > These old values that i want to change are not know forehand so i can not > use > string.replace(1024, 999) # > > i also have tried > re.sub(r'(\d{4})', ' '+str(999), mystring) > > but this changes all occurrences of any 4 digit number in the string and > also sets both NAXIS1 and NAXIS2 to the same value! Just include NAXIS1/2 in the regexp. Something like re.sub(r'NAXIS1 \(=\d{4}\)', 'NAXIS1 (=999)', mystring) Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] strings and replace
Hello There Again Might be a silly question but it has played me for the last two days! I have a string 'mystring' (pasted below), what i want to do is to change the values of of NAXIS1 (=1024) and NAXIS2 (=2048) to some other values! say NAXIS1 = 999 and NAXIS2 = 888. These old values that i want to change are not know forehand so i can not use >>> string.replace(1024, 999) # i also have tried >>> re.sub(r'(\d{4})', ' '+str(999), mystring) but this changes all occurrences of any 4 digit number in the string and also sets both NAXIS1 and NAXIS2 to the same value! i also tried >>> naxis = re.findall(r'(\d{4})',mystring[:360]) >>> mystring.replace(naxis[0], ' '+str(999)) >>> mystring.replace(naxis[1],' '+str(888)) # the empty quotes are to keep the len(mystring) the same before and after replacement i am sure there must be a better ways to do it Any ideas, i appreciate! Cheers Johnson - mystring = "SIMPLE =T / Fits format BITPIX = -32 / bits per pixel NAXIS =2 / single image NAXIS1 = 1024 / x size NAXIS2 = 2048 / y size AIRMEND =1.516 / no comment AIRMSTRT= 1.516 / no comment DATE= '2005-01-15T12:32:00' / no comment DATE-OBS= '2005-01-15T12:26:00' / no commentEXPTIME =360.0 / no comment OBJECT = 'herculesfield9 ' / no comment INSTRUME= 'MDM8K ' / no comment TELESCOP= 'MDM 2.4m ' / no comment TEL_LAT =31.95 / no comment TEL_LONG= -111.6167 / no comment TEL_ELEV= 1938.5 / no comment TEL_ZONE= 7.0 / no comment CHIP_ID = 2 / no comment FILT_ID = 'R ' / no comment CTYPE1 = 'RA---TAN ' / no comment CRVAL1 =241.320458333 / no comment CRPIX1 = -127.0 / no comment CTYPE2 = 'DEC--TAN ' / no comment CRVAL2 =16.733139 / no comment CRPIX2 = 1525.0 / no comment CD1_1 = 0.0 / no comment CD1_2 = -9.611e-05 / no comment CD2_1 =9.611e-05 / no comment CD2_2 = 0.0 / no comment STATMIN = 3179.140625 / no comment STATMAX = 3760.86035156 / no comment STATMEAN=3473.74743563 / no comment STATDEV =56.3806567048 / no comment STATMED = 3469.74121094 / no comment DATAMD5 = 'c8f7fd1759dcc82a42347e8e7eaf51db' / MD5 checksum END " ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fw: utf locale sorting
Hi, I know about the use of locale module: import locale locale.setlocale(locale.LC_ALL, "hr_HR.UTF8") print sorted(words, key=locale.strxfrm) but I have specific and complicated data structure (list of lists containing strings, tuples and dictionaries) due to LDAP search result data. So I use the 'key' option to get to the neaded attributes, and can't use it for the locale setting. How can I sort this monster list by attribute values inside it, and still get the correct sorting order? Anyone? Thanks in advance! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Executing a command from a specific directory
On Wed, 2009-09-16 at 18:03 +0530, Ansuman Dash wrote: > if "Request timed out.." not in a: > print("Ping is not successful.") > pLogger.info("Ping is not successful.") This will check for the string "Request timed out.." is NOT in a. Now when the ping is successfull the string will not be in a. I suspect you are looking for the logic being reversed so remove the not. Greets Sander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Executing a command from a specific directory
Hi, Thank you very much for the quick response. Code is working fine. Now I am trying to validate that the command is executed successfully. I have written following script to validate the log file which is created after running the command. if os.access("C:/Python25/Own.log", os.F_OK): f = open("C:/Python25/Own.log") time.sleep(30) try: for line in f.readlines(): a=line if "Request timed out.." not in a: print("Ping is not successful.") pLogger.info("Ping is not successful.") else: print ("Ping is successful.") pLogger.info("Ping is successful.") finally: f.close() else: pLogger.info("File doesn't exist") = But it is not working, even if ping is successfully it is printing "Ping is not successful.". Can you please point out where I am making mistake. Thanks, AD On Wed, Sep 16, 2009 at 12:55 PM, Patrick Sabin wrote: > Ansuman Dash schrieb: > > >> Hello Everybody, >> >> In Python scripting, how can I execute a command (which can be run from >> spcific directory) and then retrieve the result (after executing the command >> it give the command is executed successfull or not), so that I can validate >> it. >> >> Thanks, >> AD >> >> >> > import os > import subprocess > > os.chdir('/your/directory') > p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) > out = p.stdout.read() > print out > > - Patrick > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Still Trying to Understand GAE
On Sun, Sep 13, 2009 at 9:59 AM, ad...@gg-lab.net wrote: > Hi All, > > i've started earning python sone months ago (on Google App Engine > unfortunately). > > I have some doubts reagrding "import", and have asked a similar > question here months ago, but without finding a solution. > > So: > > with import i can import modules or single functions. And this is ok. > Then: as i have understood from all the books i readm in each package > directory i have the __init__.py file that decides what import with > it. In other words if my package skel is like: > > /gg/ > /gg/sub1/ > /gg/sub1/file.py > /gg/sub2/ > /gg/sub2/file.py > > and i use "import gg", nothing is imported. To import sub1 and sub2, i can: > > - Put in /gg/ a __init__.py file that tells to import them > - Use "from gg import sub1" > > Ok now the $1 Billion question: google app engine has the same schema > than my "gg" package, an empty __init__.py file, but if i use "import > google" it also imports all subdirectories. And i can't understand > wiìhy it does so. In general, import foo does not import subpackages of foo unless they are specifically imported in foo/__init__.py, so dir(foo) will not show the subpackages. However if you import foo import foo.bar then dir(foo) will include 'bar'. Here is an example from the std lib: In [1]: import distutils In [2]: dir(distutils) Out[2]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__'] In [3]: import distutils.cmd In [4]: dir(distutils) Out[4]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__', 'archive_util', 'cmd', 'dep_util', 'dir_util', 'errors', 'file_util', 'log', 'spawn', 'util'] My guess is that the startup for GAE is importing the subpackages so they then appear as imported modules. To access your sub-package, just import it normally. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] : breaking out of a function that takes too long
On Wed, Sep 16, 2009 at 6:07 AM, C or L Smith wrote: >>> Serdar wrote: > ... >>> So again, is there a way to place a time limit on the execution of a >>> function, after which you can break out of it and then retry it or >>> move along with the rest of your program? > > At http://tinyurl.com/rbre9n you can find a recipe that tells you how to > decorate a function so it will return after a given amount of time. According > to the comments, this will leave the process still running, but at least the > whole program won't hang. I've used it successfully from time to time. All that recipe really does is to tell you that the function has taken too long. It doesn't stop it. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Still Trying to Understand GAE
ad...@gg-lab.net wrote: The "google" directoy has an empty __init__.py file (well, if we want to be completely correct it contains some commented -#- lines). Same for "appengine", "net" and "pyglib". As they all have an __init__.py file, they should be consiedered as modules from the python interpreter. So, if i run "import google" it imports all google's submodules. Well, now, the problem: if i create another directory (module) in the google dir, it doesn't get imported. Of course i've put in it some .py files and an empty __init__.py file. I would guess that additions have been made to the list of modules in sys.path. Where the code that is making these additions is located is another matter. Often, people manipulate sys.path from within __init__.py files but, as you have seen, this isn't the case for the google package - all the __init__.py are empty. To verify, navigate to the GAE directory, the one containing the 'google' package, and start a python interactive session. Then do --- import google --- dir(google) You don't get 'appengine', 'net' etc. in the output. So the google package *is* the same as your own package. The confusion is probably coming from the fact that you are doing your imports from 'within' an already running process - the appserver, and this process has had a chance to manipulate sys.path before your code runs. Look at dev_appserver.py in the sdk and google/appengine/tools/dev_appserver.py - don't ask me what that code is doing, but perhaps there is a clue there, let us know if you find it! Regards ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parsing html tables and using numpy for subsequent processing
David Kim wrote: Hello all, I've finally gotten around to my 'learn how to parse html' project. For those of you looking for examples (like me!), hopefully it will show you one potentially thickheaded way to do it. [...] The code can be found at pastebin: http://financialpython.pastebin.com/f4efd8930 The original html can be found at http://www.dtcc.com/products/derivserv/data/index.php (I am pulling and parsing tables from all three sections). Doing something similar at the minute if you want to compare: http://bitbucket.org/djerdo/tronslenk/src/tip/data/scrape_translink.py Not very pretty, but I imagine there are very few pretty examples of this kind of thing. I'll add more comments...honest. Nothing obviously wrong with your code to my eyes. Regards g. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wordscramble.py
David wrote: kreglet wrote: This is my first Python project. I am doing this to help me learn the language. I was wondering if someone could give me some advice as I have a lot of questions. 1. I would like to have someone look over the code and tell me how to improve it. I am sure that a lot of it can be done better than the way that I have it written. Is anyone that would be willing to do this? In no specific order: 1. A file is its own iterator, instead of this: for line in f.readlines(): line=line.strip("\r\n") wordlist.append(line) you can have: for line in f: line=line.strip("\r\n") wordlist.append(line) 2. You are mixing spaces and tabs! PEP 8 (Style guidelines) prefers the use of 4-spaces. Among other things, it also says to use TitleCase for class names. 3. The star-import is discouraged for a good reason. from scrmod import * import only what you needed from scrmod import this, that or import the module import scrmod 4. instead of x=random.randint(0, c-1), you can use x=random.randrange(0, c); btw, do you know about random.shuffle(), random.? 2. Although it works as is I would like some advice on improving it. ie. Making it look better, play better, etc. I happen to come accross words such as these: DéTENTE which, I guess, might cause problems with the gameplay? 3. I switched from Windows to Linux about 2 months ago. I read that Python is a cross platform language. What would need to be done to make this program run in windows too? Usually there is nothing special you need to do. If your program only interacts with the stdin/stdout/stderr and/or a cross-platform window manager (Tkinter, gtk, qt) and/or the standard library; then you can almost be sure that your program will run cross-platform without change. A certain care need to be taken for path handling; make sure to use os.path instead of trying to manipulate paths yourself. Naturally, if you used third-party modules, you must make sure that they support all your target platforms. Creating self-installer is a bit tricky. 4. Once it is finished, I would like to make it installable for people other than programmers. How? These are a few of the things that I would like to accomplish. The code can be found at pastebin.com: http://pastebin.com/m1ab9a734 Wordscramble.py http://pastebin.com/d2686ec4scrmod.py http://pastebin.com/m4f611e0c wordlist.py I got it to work on linux but first had to use dos2unix to remove the ^M. I am new to programing myself so can not be of much help but to make it a python program I have used distutils; http://wiki.python.org/moin/Distutils/Tutorial Now to get it cross platform I have no idea. -david ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] : breaking out of a function that takes too long
>> Serdar wrote: ... >> So again, is there a way to place a time limit on the execution of a >> function, after which you can break out of it and then retry it or >> move along with the rest of your program? At http://tinyurl.com/rbre9n you can find a recipe that tells you how to decorate a function so it will return after a given amount of time. According to the comments, this will leave the process still running, but at least the whole program won't hang. I've used it successfully from time to time. /c ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing a command from a specific directory
"Ansuman Dash" wrote In Python scripting, how can I execute a command (which can be run from spcific directory) and then retrieve the result (after executing the command it give the command is executed successfull or not), so that I can validate it. There are sweveral ways to do this but the preferred route is using the subprocess module. You can see examples of several of the options in the Using the OS topic in my tutorial, under the heading "Manipulating Processes". HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parsing html tables and using numpy for subsequentprocessing
"David Kim" wrote > The code can be found at pastebin: > http://financialpython.pastebin.com/f4efd8930 Nothing to do with the parsing but I noticed: def get_files(path): ''' Get a list of all files in a given directory. Returns a list of filename strings. ''' files = os.listdir(path) return files Since you are just returning the result of listdir you could achieve the same effect by simply aliasing listdir: get_files = os.listdir Much less typing! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Executing a command from a specific directory
Ansuman Dash schrieb: Hello Everybody, In Python scripting, how can I execute a command (which can be run from spcific directory) and then retrieve the result (after executing the command it give the command is executed successfull or not), so that I can validate it. Thanks, AD import os import subprocess os.chdir('/your/directory') p = subprocess.Popen("ls -l", shell=True, stdout=subprocess.PIPE) out = p.stdout.read() print out - Patrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor