Re: [Tutor] Printing
On Mon, 26 Dec 2005, John Corry wrote: Thanks for the prompt reply. This is exactly what I am looking for. However, I have tried the code on the page and I can't get it to work. ... Traceback (most recent call last): File c:\python24\jhc.py, line12, in ? 0 pywintypes.error: (2, 'ShellExecute', 'The system cannot find the file specified .') Odd. Works for me. Just for the heck of it, try using a known filename, instead of making a randomly-named one, and try closing the file first: import win32api filename = testprint.txt fileobj=open (filename, w) fileobj.write (This is a test) fileobj.close() win32api.ShellExecute ( 0, print, filename, None, ., 0 ) Then you can confirm at least, that your file is being created. What version python are you using? I'm using activestate's: C:\test\printpython ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regex
Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@:::192.168.0.1 ,TYPE=ALL_DENY,HOST_ADDRESS=:::195.145.94.75,HOST_INFO=::: 195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO= Hi Will, Observation: the output above looks comma delimited, at least the stuff after the 'TCPWRAP:' part. self.twist_fail_re = rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') The line given as example doesn't appear to have whitespace in the places that the regular expression expects. It does contain commas as delimiters between the key/value pairs encoded in the line. There's more information on regular expressions here: http://www.amk.ca/python/howto/regex/ that should help you get started. As an aside: the structure of the log line above is simple enough that you might not even need regexes --- regular string methods might just be powerful enough. For example, strings have a 'split()' method to break a string into a list of substrings: ## 'hello,world,this,is,a,test'.split(,) ['hello', 'world', 'this', 'is', 'a', 'test'] ## If you have more questions, please feel free to ask. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regex
Danny Yoo wrote: Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@:::192.168.0.1 ,TYPE=ALL_DENY,HOST_ADDRESS=:::195.145.94.75,HOST_INFO=::: 195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO= Hi Will, Observation: the output above looks comma delimited, at least the stuff after the 'TCPWRAP:' part. self.twist_fail_re = rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s') The line given as example doesn't appear to have whitespace in the places that the regular expression expects. It does contain commas as delimiters between the key/value pairs encoded in the line. Expanding on Danny's comment... \S*\s matches any amount of non-whitespace followed by one whitespace. This doesn't match your sample. It looks like you want to match non-comma followed by comma. For example this will match the first field: SERVICE=[^,]*, Presumably you will want to pull out the value of the field so enclose it in parenthesis to make a group: SERVICE=([^,]*), Another thing I notice about your regex is it doesn't include all the fields in the sample, for example TYPE. If the fields are always the same you can just include them in your regex. If they vary you can try to make the regex skip them, use a different regex for each field, or try Danny's approach of using str.split() to break apart the data. The Regex Demo program that comes with Python is handy for creating and testing regexes. Look in C:\Python24\Tools\Scripts\redemo.py or the equivalent. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to call mysqlcommand in Python , mysqldump for backup
Hi I am trying to execute some MySQL commands using some python scripts I want to do a mysqldump of my database john to a file backup.date.sql the normal command to take a dump is mysqldump john backup.sql I tried python , by importing import os but I am stuck in how to call mysqldump in python and execute it Help and guidance requested Thanks Joseph ___ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.yahoo.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to call mysqlcommand in Python , mysqldump for backup
ooh ooh, i know this one, i have python do this for me every day ! target_dir = '/path/to/where/you/want/to/dump' os.system(mysqldump --add-drop-table -c -u user -ppassword database table +target_dir+/table.bak.sql) dont forget the p in front of your password ! hope this helps On Tue, 2005-12-27 at 13:07 +, John Joseph wrote: Hi I am trying to execute some MySQL commands using some python scripts I want to do a “mysqldump” of my database “john” to a file backup.date.sql the normal command to take a dump is mysqldump john backup.sql I tried python , by importing “import os” but I am stuck in how to call “mysqldump” in python and execute it Help and guidance requested Thanks Joseph ___ NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! http://uk.cars.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] code review please
Hello, Although I've been coding in PHP and ASP and _javascript_ for a couple of years now, I'm relatively new to Python. For learning exercises, I'm writing small Python programs that do limited things, but hopefully do them well. The following program takes a text file, reads through it, and any word longer than four characters will have the internal letters scrambled, but the first and last letters of the word will remain unchanged. Here's what happened when I ran the program on a file called example.txt. Before: This is a sample of text that has been scrambled, before and after. After: Tihs is a sapmle of txet taht has been sblrmcead, broefe and aetfr. The code follows, so any comments and/or suggestions as to what I did right or wrong, or what could be done better will be appreciated. thanks, William #!/usr/bin/env python #filename: wScramble.py #filelocation: /home/william/programming/code/python #filedate: 12/25/2005 import sys import random def fileScramble(fileName): newFile = file('scrambled.txt', 'w') newRow = '' for line in fileName: newRow = '' tempList = line.split(' ') for word in tempList: newRow = newRow + ' ' + wordScramble(word) newRow = newRow + '\n' newFile.write(newRow) newFile.close() def wordScramble(word): punctuation = ['.', ',', ':', ';', '(', ')'] if len(word) 4: return word elif len(word) == 4 and word[-1] in punctuation or word[0] in punctuation: return word elif len(word) == 4: word = word[0] + word[2] + word[1] + word[3] return word else: (fCut, fLetter) = getLetter(word, 0, 'forward') (lCut, lLetter) = getLetter(word, -1, 'back') tempWord = list(word) del tempWord[:fCut + 1] del tempWord[lCut:] random.shuffle(tempWord) middleString = .join(tempWord) scrambledWord = fLetter + middleString + lLetter return scrambledWord def getLetter(string, number, direction): if direction == 'forward': increment = 1 else: increment = -1 if string[number].isalpha() == True: if direction == 'forward': return (number, string[:number + 1]) else: return (number, string[number:]) elif string[number].isalpha() == False: return getLetter(string, number + increment, direction) if __name__ == __main__: try: if sys.argv[1].isspace() == True: print No file was given to the program to process.\n-- Program quitting --\n else: try: f = open(sys.argv[1]) fileScramble(f) f.close() except IOError: print That file does not exist, or you do not have permission to access it.\n-- Program quitting --\n except IndexError: print No file was given to the program to process.\n-- Program quitting --\n ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing
On Tue, 27 Dec 2005, John Corry wrote: I am saving the code to c:\python24\jhc2.py The code creates the file c:\python24\testprint.txt John, I would *very* strongly advise not to store your code in c:\python24 or any subdirectory in it. That is where Python itself lives, and it's very possible that you could create a file with the same name as a Python-supplied file, and the file you create will start getting erroneously used instead of the correct one. I don't know that this is your problem, but it's certainly a factor I would eliminate. Can you tell us what other files, and their names, you may have added there? I have a directory named C:\test where I do my coding. I generally create a subdirectory with some memorable name and work there. For example, for testing your problem out, I have C:\ test\ print\ testpr.py testpr2.py testprint.txt There may be some differences between what's installed in your Python installation and in mine. I'm a big fan of Activestate's ActivePython. It includes most of the Win32-specific stuff you'll need already. You may end up needing to re-install Python if you've put too much into the Python24 directory; if so, I'd suggest you re-install from the Activestate version. It's also free, and made to target Windows. I don't know of any downsides to using it instead of the Windows release from Python.org, and it just works. http://www.activestate.com/Products/ActivePython/?pysbx=1 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] code review please
Hi William, Here are some constructive comments on the program; if you have questions on any of it, please feel free to ask. def fileScramble(fileName): We may want to rename fileName to something else, as it isn't being treated as a filename, but more like a file-like object. Good names help to clarify programs. I had expected the input here to be a string, and to see it be a file-like object was a little disorienting at first. [within fileScramble() ...] newFile = file('scrambled.txt', 'w') newRow = '' for line in fileName: It's possible that the lines here still have their trailing newlines: you might want to rstrip() them out before further processing. def wordScramble(word): punctuation = ['.', ',', ':', ';', '(', ')'] if len(word) 4: return word elif len(word) == 4 and word[-1] in punctuation or word[0] in punctuation: The complexity of the elif is a bit high. Do you mean: ((len(word) == 4 and word[-1] in punctuation) or word[0] in punctuation) or do you mean: len(word) == 4 and (word[-1] in punctuation or word[0] in punctuation) Explicit parenthesization is a good idea here, since there are two possible ways of parsing the expression. It's unambiguous to the computer of course, but since it's ambiguous for humans, let's make it explicit what we mean. def getLetter(string, number, direction): if direction == 'forward': increment = 1 else: increment = -1 if string[number].isalpha() == True: The above if statement can be simplified to: if string[number].isalpha(): ... because comparing True to True is a bit redundant. In fact, since either string[number].isalpha() is True or it isn't, this allows us simplify the block: if string[number].isalpha() == True: ... elif string[number].isalpha() == False: ... so that we use a simpler if/else: if string[number].isalpha(): ... else: ... Looking into the __main__, I see: try: f = open(sys.argv[1]) fileScramble(f) f.close() except IOError: print That file does not exist, or you do not have In the exception handler, we may want to also show the message of the exception too, just in case another kind of IOError has occurred. According to: http://www.python.org/doc/lib/module-exceptions.html we can grab at the 'errno' and 'strerror' attributes of the exception object to display more detailed information --- I'd recommend including those in the error output, since that's useful debugging information. Similarly, the try/except for IndexError seems too pervasive: rather than wrap it around the whole program, we may want to limit its extent to just around the sys.argv access. Otherwise, any other IndexError has the potential of being misattributed. Much of the program does indexing of some sort, so that's why this concerns me. Alternatively, doing the explicit length check: if not sys.argv[1:]: print some kind of usage message raise SystemExit might be sufficient. Unless we really want to hide errors from the user, I'd avoid the exception handlers altogether: if bad things happen, the default exception handler gives a fairly good stack trace that aids debugging. But if we do want to handle the exceptions manually, we should try to make sure that useful information is preserved in the error messages: it's a terrible thing to get an error message that says Something bad happened. when we can do much better. *grin* I hope this critique helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sets and Python; new shiny tool syndrome?
Hi all, I just tried out sets for the first time, and I'm finding multiple uses for them, particularly for replacing and simplifying what would normally be one or two list comprehensions i.e. def parseKws(self, kw_data): ignoreSet = set(['import', 'from', 'as', ' ', '']) kws = set([]) for line in kw_data: line = line.rstrip(\n) if , in line: line = line.replace(,, ) if ; in line: line = line.replace(;, ) l = set(line.split( )) k = l.difference(ignoreSet) kws.update(k) instead of l = line.split( ) k = [ item for item in l if not (item in ignoreSet or item in kws) ] kws.extend(k) (Above just gets module names from various import statements.) However, I'm reminded of the joke about you can tell what chapter someone reading the Patterns book by the Gang of Four is up to by what new pattern they're trying to use the next day, no matter the problem. Are there any drawbacks to sets that I need to watch out for? Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sets and Python; new shiny tool syndrome?
I just tried out sets for the first time, and I'm finding multiple uses for them, particularly for replacing and simplifying what would normally be one or two list comprehensions i.e. def parseKws(self, kw_data): ignoreSet = set(['import', 'from', 'as', ' ', '']) kws = set([]) for line in kw_data: line = line.rstrip(\n) if , in line: line = line.replace(,, ) if ; in line: line = line.replace(;, ) Hi Liam, Quick comment: the two if statements there can be simplified by just doing the replacement straight-out: # line = line.replace(,, ) line = line.replace(;, ) # The reason is that if those characters aren't present, no harm is done. But looking at the code, I'm curious: it looks like you're trying to tokenize the keywords out of Python source? If so, you may want to look at the 'tokenize' module: http://www.python.org/doc/lib/module-tokenize.html as it'll handle some of the especially tricky cases like handling string literals. However, I'm reminded of the joke about you can tell what chapter someone reading the Patterns book by the Gang of Four is up to by what new pattern they're trying to use the next day, no matter the problem. Are there any drawbacks to sets that I need to watch out for? Use them when they're appropriate, and don't use them when they're not. *grin* It really is problem sensitive: if order matters, then sets probably aren't appropriate. But sets are such a pervasive concept that few problems don't provide opportunities to take advantage of them. Happy holidays to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing
At 08:52 AM 12/26/2005, John Corry wrote: Thanks for the prompt reply. This is exactly what I am looking for. However, I have tried the code on the page and I can't get it to work. import tempfile import win32api filename = tempfile.mktemp (.txt) open (filename, w).write (This is a test) win32api.ShellExecute ( 0, print, filename, None, ., 0 ) Also beware that the file must have an extension associated with an application that recognizes the print command. e.g. if the file is named foo.doc and .doc is registered as belonging to MS Word, then this will open MSword, open the file, print the file and close Word. It is the equivalent of right-clicking the file in the explorer and then choosing Print from the context menu. I am using the Pythoncard code editor and I get the following error: Traceback (most recent call last): File c:\python24\jhc.py, line12, in ? 0 pywintypes.error: (2, 'ShellExecute', 'The system cannot find the file specified .') I have played about with it and saved it in various places but I can't get it to work. Any suggestions? Do I need to import other modules? Do I need to use Pythonwin? Thanks, John. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Danny Yoo Sent: 24 December 2005 19:33 To: John Corry Cc: Tutor Subject: Re: [Tutor] Printing I have downloaded win32, win32com, Preppy and PIL. I have had a go at using them but can't get them to work. At the moment I can't even print the text file. Is there a good helpguide/FAQ page which deals with printing text files or is there simple code which prints a text file? Hi John, Let's see... ok, found it! Tim Golden has written a small introduction to printing: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html His recommendation is to use the ShellExecute function in win32api to send off documents to your printer. Best of wishes! ___ 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] Writing/reading lists to a file
Hi, Is there any easy way of writing lists to a file and more importantly, reading it back as a list of lists rather than as a list of strings. Eg: t = [t1, PASS, 31] f = open(pass.txt,a+) f.write(str(t) + \n) f.write(str(t) + \n) f.close() At this stage, the file contains two lines. Now, if I use the readlines() function to read it back, heres what I get: f = open(pass.txt,r+) r = f.readlines() r [['t1', 'PASS', 31]\n, ['t1', 'PASS', 31]\n, ['t1', 'PASS', 31]\n] r[0] ['t1', 'PASS', 31]\n So, r[0] is now a string. Is there ant direct way of extracting the list from this string? Or alternatively, can I read the file as a list of lists rather than list of strings (which is what readlines() appears to do). Thanks, Hans ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sets and Python; new shiny tool syndrome?
On 12/28/05, Danny Yoo [EMAIL PROTECTED] wrote: I just tried out sets for the first time, and I'm finding multiple uses for them, particularly for replacing and simplifying what would normally be one or two list comprehensions i.e. def parseKws(self, kw_data): ignoreSet = set(['import', 'from', 'as', ' ', '']) kws = set([]) for line in kw_data: line = line.rstrip(\n) if , in line: line = line.replace(,, ) if ; in line: line = line.replace(;, ) Hi Liam, Quick comment: the two if statements there can be simplified by just doing the replacement straight-out: # line = line.replace(,, ) line = line.replace(;, ) # The reason is that if those characters aren't present, no harm is done. But looking at the code, I'm curious: it looks like you're trying to tokenize the keywords out of Python source? If so, you may want to look at the 'tokenize' module: http://www.python.org/doc/lib/module-tokenize.html as it'll handle some of the especially tricky cases like handling string literals. Thanks Danny, I'm writing a little database to stash my code snippets in, and my thinking tends to go along the lines of That code I did that use imaplib... so I'm linking module names to the stored files; that said, I'll use tokenizer next time I try and write a wxPython frontend for IronPython and save myself a lot of grief! However, I'm reminded of the joke about you can tell what chapter someone reading the Patterns book by the Gang of Four is up to by what new pattern they're trying to use the next day, no matter the problem. Are there any drawbacks to sets that I need to watch out for? Use them when they're appropriate, and don't use them when they're not. *grin* It really is problem sensitive: if order matters, then sets probably aren't appropriate. But sets are such a pervasive concept that few problems don't provide opportunities to take advantage of them. Good to know; I'm very glad that they're part of Python. They're making my job a whole lot simpler. Happy holidays to you! And likewise. :) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing/reading lists to a file
Hi Hans, If you're looking to store lists as lists, may I recommend the cPickle module? It's good for most times when you want to store an object as an object. import cPickle a = [1,2,3] b = [4,5,6] c = [7,8,9] d = [a,b,c] d [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print d[0][1] 2 f = file(filetosaveto,wb) cPickle.dump(d, f) f.close() del d f = file(filetosaveto,rb) newD = cPickle.load(f) f.close() newD [[1, 2, 3], [4, 5, 6], [7, 8, 9]] newD[0][1] 2 Regards, Liam Clarke On 12/28/05, Hans Dushanthakumar [EMAIL PROTECTED] wrote: Hi, Is there any easy way of writing lists to a file and more importantly, reading it back as a list of lists rather than as a list of strings. Eg: t = [t1, PASS, 31] f = open(pass.txt,a+) f.write(str(t) + \n) f.write(str(t) + \n) f.close() At this stage, the file contains two lines. Now, if I use the readlines() function to read it back, heres what I get: f = open(pass.txt,r+) r = f.readlines() r [['t1', 'PASS', 31]\n, ['t1', 'PASS', 31]\n, ['t1', 'PASS', 31]\n] r[0] ['t1', 'PASS', 31]\n So, r[0] is now a string. Is there ant direct way of extracting the list from this string? Or alternatively, can I read the file as a list of lists rather than list of strings (which is what readlines() appears to do). Thanks, Hans ___ 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] code review please
Eakin, W wrote: The code follows, so any comments and/or suggestions as to what I did right or wrong, or what could be done better will be appreciated. def fileScramble(fileName): newFile = file('scrambled.txt', 'w') newRow = '' for line in fileName: newRow = '' tempList = line.split(' ') for word in tempList: newRow = newRow + ' ' + wordScramble(word) newRow = newRow + '\n' newFile.write(newRow) This seem pretty verbose to me. Using tempList doesn't IMO add anything, it might as well be for word in line.split(' '): or for word in line.split(): since you probably want to split on tabs also and this will strip the trailing newlines as a bonus. I usually prefer a list comprehension to an accumulation loop when possible so I would actually write it as newWords = [ wordScramble(word) for word in line.split() ] newRow = ' '.join(newWords) + '\n' or even newRow = ' '.join(wordScramble(word) for word in line.split()) + '\n' though that might be a little too terse for easy comprehension. newFile.close() def wordScramble(word): punctuation = ['.', ',', ':', ';', '(', ')'] if len(word) 4: return word elif len(word) == 4 and word[-1] in punctuation or word[0] in punctuation: return word elif len(word) == 4: word = word[0] + word[2] + word[1] + word[3] return word Rather than repeating the test for len(word) == 4, I would write elif len(word) == 4: if word[-1] in punctuation or word[0] in punctuation: return word else: word = word[0] + word[2] + word[1] + word[3] return word This also breaks up the long conditional that Danny complained about. else: (fCut, fLetter) = getLetter(word, 0, 'forward') (lCut, lLetter) = getLetter(word, -1, 'back') tempWord = list(word) del tempWord[:fCut + 1] del tempWord[lCut:] I think this is the same as tempWord = list(word[fCut+1:lCut]) random.shuffle(tempWord) middleString = .join(tempWord) scrambledWord = fLetter + middleString + lLetter return scrambledWord def getLetter(string, number, direction): I found it very hard to understand what this function does. A better name and a comment would help a lot. You might consider having separate getFirstLetter() and getLastLetter() since much of getLetter() is taken up with the conditionals and compensating for trying to do two things. def getFirstLetter(string, number=0): if string[number].isalpha() == True: return (number, string[:number + 1]) else: return getFirstLetter(string, number + 1) Even better would be to use a simple loop to find the index of the first letter, and split the string into three sections in the caller. BTW thinking of writing this as a loop brings to mind some problems - what will your program do with 'words' such as 555-1212 or Ha! ? if direction == 'forward': increment = 1 else: increment = -1 if string[number].isalpha() == True: if direction == 'forward': return (number, string[:number + 1]) else: return (number, string[number:]) elif string[number].isalpha() == False: return getLetter(string, number + increment, direction) if __name__ == __main__: try: if sys.argv[1].isspace() == True: print No file was given to the program to process.\n-- Program quitting --\n else: try: f = open(sys.argv[1]) fileScramble(f) f.close() except IOError: print That file does not exist, or you do not have permission to access it.\n-- Program quitting --\n except IndexError: print No file was given to the program to process.\n-- Program quitting --\n ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor