[Tutor] ssl error when trying to connect to https (also using timeoutsocket.py)
Hello all, in my code i am importing timeoutsocket in order to set the time out of a connection. When i try to acces an https site I get the error: "TypeError: ssl() argument 1 must be _socket.socket, not _socketobject" when I am not using the timeoutsocket module, I don't have any problems. how can i solve this ? (I still need to be able to set the timeout of a connection...) thanks, Tsila ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing a list, dict or tuple to MySQLdb?
On Wed, Mar 07, 2007, Alan Wardroper wrote: >I'm parsing some data to feed to a MySQL database, and would like to be >able to pass in a list (a dictionary or a series of tuples) in the >cursor.execute() or cursor.executemany() statement, but everything I've >tried raises errors. I'm sure it's a matter of correct formatting the >list as a sequence... > >CODE: >import sys, MySQLdb >conn = MySQLdb.connect (host = "localhost", user = "user", psswd = >"" db = "testdb") >cursor = conn.cursor() > >infile = open(sys.argv[2], 'r') >list_of_tuples = [] >for line in infile: >tuple = (line.split()[0], line.split()[1]) >list_of_tuples.append(tuple) > >cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE >field2 = %s", (list_of_tuples) I think what you want is ...(*list_of_tuples) similar to the syntax used when calling functions with position arguments from a list. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 Few skills are so well rewarded as the ability to convince parasites that they are victims. -- Thomas Sowell ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Passing a list, dict or tuple to MySQLdb?
I'm parsing some data to feed to a MySQL database, and would like to be able to pass in a list (a dictionary or a series of tuples) in the cursor.execute() or cursor.executemany() statement, but everything I've tried raises errors. I'm sure it's a matter of correct formatting the list as a sequence... CODE: import sys, MySQLdb conn = MySQLdb.connect (host = "localhost", user = "user", psswd = "" db = "testdb") cursor = conn.cursor() infile = open(sys.argv[2], 'r') list_of_tuples = [] for line in infile: tuple = (line.split()[0], line.split()[1]) list_of_tuples.append(tuple) cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE field2 = %s", (list_of_tuples) """ example data: ID123445 somestring1 ID223445 somestring2 ID323445 somestring3 ID423445 somestring4 ID523445 somestring5 """ Naively, I thought this would result in an execute statement like: cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE field2 = %s", ('ID123445', 'somestring1'), ('ID223445', 'somestring2'), ('ID323445', 'somestring3'), ('ID423445', 'somestring4'), ('ID523445', 'somestring5')) But what I get are bunch of errors, last of which is: TypeError: not ll arguments converted during string formatting Or pass in a list of values to use in a SELECT...WHERE...IN (list) statement: ids_to_include = ['ID123445', 'ID223445', 'ID323445'] cursor.execute("UPDATE sometable SET field1 = 'some standard value' WHERE field2 IN (%s)", (ids_to_include)) I also tried another similar thing, where I tried to pass in the name of one of the fields as a dictionary key with the value as the corresponding value, but it also didn't work--it looked like the key was bounded in quotes before passing to MySQL, so the db didn't recognise the fieldname: for key in dict.keys(): cursor.execute("INSERT INTO sometable (%s) values (%s)", (key, dict[key])) Any pointers? Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 37, Issue 22
-- Forwarded message -- From: Tim Golden <[EMAIL PROTECTED]> To: Date: Wed, 07 Mar 2007 15:48:20 + Subject: Re: [Tutor] Printing labels Steve Maguire wrote: > I am a Python beginner. For my first task I wanted to fix a program that I > originally wrote in Excel with VBA. I want to create a mySQL database > holding my DVD collection, edit it in Python, and print labels for the > cases > with an index for filing and a catalog of all the titles their indices. > > To print the labels the way I want, I will need extended control over the > printer: positioning the printer precisely and changing fonts, colors, and > background colors. Is there a public python library that could give me > this > level of control? Best bet is probably using Reportlab (http://reportlab.org) to generate PDF. Their platypus layout scheme is very flexible, and you may even find someone's already done labels as an example. TJG Thanks Tim. I'll check that out right away. Steve ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help:find a string in a text and replace it with a anotherstring
> -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of mastjeptor regli > Sent: Wednesday, March 07, 2007 10:34 AM > To: tutor@python.org > Subject: [Tutor] help:find a string in a text and replace it > with a anotherstring > > Hi,folks. > At first ,I have a question that I want to ask for > help,it is how can I search a specific string in a text (such > a in a word document) and replace it with another string? > Second,if the text is changed dynamicly,can I use a > variable string(has been assigned a string) to search in the > text and replace it with another variable string.for example, > Regex Substitution: s/email/e-mail ,if the string of "email" > and "e-mail" are both changed from time to time,can we apply > variable string (which has been assigned a value of string > type) instead of constant string of "email" and "e-mail" to > construct a regex substitution expression ? > Please reply with experience in using regular > expression or python library functions to find and replace a > string in a text to help me. Thank you for your attention. > You might not need regular expressions. You can use replace method. In [11]: x = "Bozo" In [12]: z = "Bozo The Clown" In [13]: y = "Krusty" In [14]: z.replace(x,y) Out[14]: 'Krusty The Clown' You could probably populate a dictionary of the words you want to replace and their replacements. Then use the replace method on the strings. Note that Word documents are binary gibberish, so you'd need to use win32 python windows stuff making this more complicated. On plain text files, it wouldn't be too bad. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help:find a string in a text and replace it with a another string
Hi,folks. At first ,I have a question that I want to ask for help,it is how can I search a specific string in a text (such a in a word document) and replace it with another string? Second,if the text is changed dynamicly,can I use a variable string(has been assigned a string) to search in the text and replace it with another variable string.for example, *Regex Substitution:* s/email/e-mail ,if the string of "email" and "e-mail" are both changed from time to time,can we apply variable string (which has been assigned a value of string type) instead of constant string of "email" and "e-mail" to construct a regex substitution expression ? Please reply with experience in using regular expression or python library functions to find and replace a string in a text to help me. Thank you for your attention. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] recommendation for good OO book?
> -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On > Behalf Of Jeff Peery > Sent: Wednesday, March 07, 2007 10:15 AM > To: tutor@python.org > Subject: [Tutor] recommendation for good OO book? > > Hello, I've been using python for a few years now and I > really like it. Although i am beginning to realize I really > don't utilize this object oriented stuff in a good way. Does > anyone have a favorite book regarding the basics/intro to > object oriented programming, how to write good OO code?? > > thanks, > Jeff > I liked The Object Oriented Thought Process. It uses Java and C#(I think) as examples. I then reread the chapters in Learning Python on OO to get a better understanding of the Python way of doing it. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] recommendation for good OO book?
Hello, I've been using python for a few years now and I really like it. Although i am beginning to realize I really don't utilize this object oriented stuff in a good way. Does anyone have a favorite book regarding the basics/intro to object oriented programming, how to write good OO code?? thanks, Jeff - Don't get soaked. Take a quick peek at the forecast with theYahoo! Search weather shortcut.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing labels
Steve Maguire wrote: > I am a Python beginner. For my first task I wanted to fix a program that I > originally wrote in Excel with VBA. I want to create a mySQL database > holding my DVD collection, edit it in Python, and print labels for the > cases > with an index for filing and a catalog of all the titles their indices. > > To print the labels the way I want, I will need extended control over the > printer: positioning the printer precisely and changing fonts, colors, and > background colors. Is there a public python library that could give me > this > level of control? Best bet is probably using Reportlab (http://reportlab.org) to generate PDF. Their platypus layout scheme is very flexible, and you may even find someone's already done labels as an example. TJG ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Printing labels
I am a Python beginner. For my first task I wanted to fix a program that I originally wrote in Excel with VBA. I want to create a mySQL database holding my DVD collection, edit it in Python, and print labels for the cases with an index for filing and a catalog of all the titles their indices. To print the labels the way I want, I will need extended control over the printer: positioning the printer precisely and changing fonts, colors, and background colors. Is there a public python library that could give me this level of control? Thanks Steve ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] trouble with objects, instances, type, and None in BeautifulSoup (and in general?)
Still learning, please bear with me if my lingo is a little off. But I think I have a better handle on my problem. My objective: 1. get a starting point on a web page, walk down the page until hitting an HR tag 2. Along the way, test for certain markers that allow me to get various strings and compile them. For example, the name of a speaker always appear within a B tag. Please don't help me with this one . . . (yet) My approach: - get the series of starting points on a page then use a "for in" loop - within that loop (and here is where the trouble occurs) look for an HR in the .name of the current node. at that point go to the next node. My trouble: - the .name and .string methods trip me up: --- .name can flunk when a Soup returns a NavigableString --- .string can return None I've tried "do while" and even recursion and various conditionals but keep messing up. So if anyone can show me what is wrong with my code and/or my approach, that would be great. Maybe a simple type conversion is needed somewhere? Would love help with this part and then try objective #2 on my own. Here's some code showing the recursion + ugly conditionals attempt: - - - - - - - def findName(start_point): """ unnecessary use of recursion? perhaps. moves down HTML try returning a name only when it exists. written to avoid NavigableObject. """ print "--- running findName ---" if start_point.name: if start_point.name == "None": print "You got None, baby!" nextNode = start_point.next print nextNode findName(nextNode) else: print "got a name?" return start_point.name else: print "not a name" print "going to next node" nextNode = start_point.next findName(nextNode) quotations = quotepage.findAll('a', attrs = {'name' : re.compile("^qt")}) for q in quotations: """ testing for .next since current position has a name I need a failure to challenge the function """ position = q.next my_nextname = findName(position) print my_nextname - - - - - - - Thanks for any help! - Clay ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] BeautifulSoup and Python 2.5
This seems to be a problem with BeautifulSoup and Python 2.5. I spent some time looking at it this morning and tracked down one problem. Below is the email I sent to the BeautifulSoup maintainer. I doubt that either of these problems will actually be a problem in practice. I suggest you install it by copying the .py file to site-packages and go ahead and use it. Kent == Hi, BeautifulSoup has a few problems with Python 2.5. Running the tests gives this output: ./Users/kent/Desktop/Downloads/BeautifulSoup-3.0.3/BeautifulSoup.py:1654: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal elif data[:3] == '\xef\xbb\xbf': /Users/kent/Desktop/Downloads/BeautifulSoup-3.0.3/BeautifulSoup.py:1657: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal elif data[:4] == '\x00\x00\xfe\xff': /Users/kent/Desktop/Downloads/BeautifulSoup-3.0.3/BeautifulSoup.py:1660: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal elif data[:4] == '\xff\xfe\x00\x00': ...F... == FAIL: testQuotedAttributeValues (__main__.QuoteMeOnThat) -- Traceback (most recent call last): File "BeautifulSoupTests.py", line 382, in testQuotedAttributeValues '') File "BeautifulSoupTests.py", line 19, in assertSoupEquals self.assertEqual(str(c(toParse, convertEntities=convertEntities)), rep) AssertionError: '' != '' -- Ran 52 tests in 0.208s FAILED (failures=1) The UnicodeWarnings seem to be caused by a change in how Python handles mixed string comparisons. In Python 2.4, the comparison u'' == '\xef\xbb\xbf' raises UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) In Python 2.5, the same comparison prints a warning but doesn't raise an exception. For more information about this change, see the section starting "A new warning, UnicodeWarning," on this page: http://docs.python.org/whatsnew/other-lang.html The affected code is in UnicodeDammit._toUnicode(). When BeautifulSoup() is called with no text data, as happens a few times in the test suite, _toUnicode() is called with an empty unicode string and triggers this warning. One way to fix this is to have UnicodeDammit.__init__() explicitly check for an empty string and just return u"". Here is a suggested rewrite of the initial portion of UnicodeDammit.__init__(): def __init__(self, markup, overrideEncodings=[], smartQuotesTo='xml'): self.markup, documentEncoding, sniffedEncoding = \ self._detectEncoding(markup) self.smartQuotesTo = smartQuotesTo self.triedEncodings = [] if markup=="" or isinstance(markup, unicode): self.originalEncoding = None self.unicode = unicode(markup) return Note that I have also changed the way this works if markup is already unicode; the current implementation is incorrect, it returns a value which is not allowed in __init__(). I don't know enough about the way BeautifulSoup works to figure out the second one... Best regards, Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] path to use for setting the environment variable PYTHONDOCS?
At 03:15 AM 3/7/2007, Kent Johnson wrote: >Dick Moores wrote: > > At 02:41 PM 3/6/2007, Alan Gauld wrote: > > > >> "Dick Moores" <[EMAIL PROTECTED]> wrote > >> > >>> Sorry, topic and keyword documentation is not available because the > >>> Python > >>> HTML documentation files could not be found. If you have installed > >>> them, > >>> please set the environment variable PYTHONDOCS to indicate their > >>> location. > >>> > >>> > >>> I have Python 2.5. Where are the HTML documentation files? > >> No idea, but I suspect the answer will be platform specific. > >> Which platform are you using? > > > > Sorry, Win XP. > >I don't think the Windows installer for Python includes the HTML docs. >You can download them from here: >http://docs.python.org/download.html Thanks, Kent. Got 'em and installed 'em. Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] path to use for setting the environment variable PYTHONDOCS?
Dick Moores wrote: > At 02:41 PM 3/6/2007, Alan Gauld wrote: > >> "Dick Moores" <[EMAIL PROTECTED]> wrote >> >>> Sorry, topic and keyword documentation is not available because the >>> Python >>> HTML documentation files could not be found. If you have installed >>> them, >>> please set the environment variable PYTHONDOCS to indicate their >>> location. >>> >>> >>> I have Python 2.5. Where are the HTML documentation files? >> No idea, but I suspect the answer will be platform specific. >> Which platform are you using? > > Sorry, Win XP. I don't think the Windows installer for Python includes the HTML docs. You can download them from here: http://docs.python.org/download.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble understanding the python environment in OSX
probably it is not the same issue but ... I've got a problem with BeautifulSoup that I've never encounter before ( I've got a new computer and a brand new installation Python 2.5 (r25:51908, Sep, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 ) When I run BeautifulSoupTests.py ( If I am not mistaken, the BeautifulSoup installer also run this test and it's why I think that Clay's Unicode problem is somehow related ..) I obtain the following message : Microsoft Windows XP [Version 5.1.2600] (C) Copyright Microsoft Corp. C:\programmes\python25\Lib\site-packages>BeautifulSoupTests.py .C:\programmes\python25\Lib\site-packages\Beauti fulSoup.py:1654: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal elif data[:3] == '\xef\xbb\xbf': C:\programmes\python25\Lib\site-packages\BeautifulSoup.py:1657: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpret ing them as being unequal elif data[:4] == '\x00\x00\xfe\xff': C:\programmes\python25\Lib\site-packages\BeautifulSoup.py:1660: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpret ing them as being unequal elif data[:4] == '\xff\xfe\x00\x00': ...F... == FAIL: testQuotedAttributeValues (__main__.QuoteMeOnThat) -- Traceback (most recent call last): File "C:\programmes\python25\Lib\site-packages\BeautifulSoupTests.py", line 38 2, in testQuotedAttributeValues '') File "C:\programmes\python25\Lib\site-packages\BeautifulSoupTests.py", line 19 , in assertSoupEquals self.assertEqual(str(c(toParse, convertEntities=convertEntities)), rep) File "C:\programmes\python25\Lib\site-packages\unittest.py", line 273, in fail UnlessEqual raise self.failureException, (msg or '%s != %s' % (first, second)) AssertionError: != -- Ran 52 tests in 0.300s FAILED (failures=1) but I am not sure that this failure come from a Python installation problem as a matter of fact when I installed Emule, I did receive a strange warning emule has detected that your current code page "1252 (ANSI-Latin I )" is not the same as your system's code page "1252 (ANSI-Latin I )". For converting non-Unicode data to Unicode, you need to specify which code page to use emule's code contains (http://www.koders.com/cpp/fid558EFC295DED6419B3F3DEA41F94A2BAFE2470DE.aspx) #ifdef _UNICODE if (theApp.GetProfileInt(_T("eMule"), _T("SetLanguageACP"), 0) != 0) return true; int iSetSysACP = theApp.GetProfileInt(_T("eMule"), _T("SetSystemACP"), -1); if (iSetSysACP != -1) return true; iSetSysACP = 0; LCID lcidSystem = GetSystemDefaultLCID(); // Installation, or altered by user in control panel (WinXP) LCID lcidUser = GetUserDefaultLCID(); // Installation, or altered by user in control panel (WinXP) // get the ANSI codepage which is to be used for all non-Unicode conversions. LANGID lidSystem = LANGIDFROMLCID(lcidSystem); // get user's sorting preferences //UINT uSortIdUser = SORTIDFROMLCID(lcidUser); //UINT uSortVerUser = SORTVERSIONFROMLCID(lcidUser); // we can't use the same sorting paramters for 2 different Languages.. UINT uSortIdUser = SORT_DEFAULT; UINT uSortVerUser = 0; // create a thread locale which gives full backward compability for users which had run ANSI emule on // a system where the system's code page did not match the user's language.. LCID lcid = MAKESORTLCID(lidSystem, uSortIdUser, uSortVerUser); LCID lcidThread = GetThreadLocale(); if (lcidThread != lcid) { CString str = _T("eMule has detected that your system's codepage is not the same as eMule's current codepage. Do you want eMule to use your system's codepage for converting non-Unicode data to Unicode?\r\n") _T("\r\n") _T("If you want eMule to use your system's codepage for converting non-Unicode data, click 'Yes'. (This will give you more backward compatibility when reading older *.met files created with non-Unicode eMule versions.)\r\n") _T("\r\n") _T("If you want eMule to use the current codepage for converting non-Unicode data, click 'No'. (If you are using eMule the first time or if you don't care about this issue at all, chose this option. This is recommended.)\r\n") _T("\r\n") _T("If you want to cancel and create backup of all your config files or visit our forum to learn more about this issue, click 'Cancel'.\r\n"); in