title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python, regex split and special character
647,655
<p>How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result.</p> <p>Example code:</p> <pre><code># -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").split(s) print " s&gt; "+s print " wordlist&gt; "+str(l) for i in l: print " word&gt; "+i </code></pre> <p>The output is :</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicit word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; tutto </code></pre> <p>while I'm looking for an output like:</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicità word&gt; word&gt; è word&gt; word&gt; tutto </code></pre> <p>To be noted that s is a string that is returned from another method so I cannot force the encoding like</p> <pre><code>s=u"La felicità è tutto" </code></pre> <p>On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.</p> <p>Thanks.</p> <p>Alessandro</p>
11
2009-03-15T11:24:44Z
647,674
<p>Try defining an encoding for the regular expression:</p> <pre><code>l=re.compile("\W", re.UNICODE).split(s) </code></pre>
4
2009-03-15T11:36:49Z
[ "python", "regex", "unicode", "split" ]
python, regex split and special character
647,655
<p>How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result.</p> <p>Example code:</p> <pre><code># -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").split(s) print " s&gt; "+s print " wordlist&gt; "+str(l) for i in l: print " word&gt; "+i </code></pre> <p>The output is :</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicit word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; tutto </code></pre> <p>while I'm looking for an output like:</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicità word&gt; word&gt; è word&gt; word&gt; tutto </code></pre> <p>To be noted that s is a string that is returned from another method so I cannot force the encoding like</p> <pre><code>s=u"La felicità è tutto" </code></pre> <p>On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.</p> <p>Thanks.</p> <p>Alessandro</p>
11
2009-03-15T11:24:44Z
647,775
<p>I think it's overkill to use a regexp in this case. If the only thing you want to do is split the string on whitespace characters I recommend using the <code>split</code> method on the string</p> <pre><code>s = 'La felicità è tutto' words = s.split() </code></pre>
3
2009-03-15T12:59:43Z
[ "python", "regex", "unicode", "split" ]
python, regex split and special character
647,655
<p>How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result.</p> <p>Example code:</p> <pre><code># -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").split(s) print " s&gt; "+s print " wordlist&gt; "+str(l) for i in l: print " word&gt; "+i </code></pre> <p>The output is :</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicit word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; tutto </code></pre> <p>while I'm looking for an output like:</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicità word&gt; word&gt; è word&gt; word&gt; tutto </code></pre> <p>To be noted that s is a string that is returned from another method so I cannot force the encoding like</p> <pre><code>s=u"La felicità è tutto" </code></pre> <p>On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.</p> <p>Thanks.</p> <p>Alessandro</p>
11
2009-03-15T11:24:44Z
647,879
<p>Well, after some further tests on Andrew Hare answer I've seen that character as ()[]- and so on are no more considered as separator while I want to split a sentence (maintaining all the separator) in words composed with ensemble of alphanumerical values set eventually expanded with accented chars (that is, everything marked as alphanumeric in unicode). So, the solution of kgiannakakis is more correct but it miss a conversion of string s into unicode format.</p> <p>Take this extension of the first example:</p> <pre><code># -*- coding: utf-8 -*- import re s="(La felicità è tutto)"#no explicit unicode given string (UTF8) l=re.compile("([\W])",re.UNICODE).split(unicode(s,'utf-8'))#split on s converted to unicode from utf8 print " string&gt; "+s print " wordlist&gt; "+str(l) for i in l: print " word&gt; "+i </code></pre> <p>The output now is :</p> <pre><code> string&gt; (La felicità è tutto) wordlist&gt; [u'', u'(', u'La', u' ', u'felicit\xe0', u' ', u'\xe8', u' ', u'tutto', u')', u''] word&gt; word&gt; ( word&gt; La word&gt; word&gt; felicità word&gt; word&gt; è word&gt; word&gt; tutto word&gt; ) word&gt; </code></pre> <p>That is exactly what I'm looking for.</p> <p>Cheers :)</p> <p>Alessandro</p>
0
2009-03-15T14:22:00Z
[ "python", "regex", "unicode", "split" ]
python, regex split and special character
647,655
<p>How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result.</p> <p>Example code:</p> <pre><code># -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").split(s) print " s&gt; "+s print " wordlist&gt; "+str(l) for i in l: print " word&gt; "+i </code></pre> <p>The output is :</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicit word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; word&gt; Ã word&gt; word&gt; ? word&gt; word&gt; word&gt; tutto </code></pre> <p>while I'm looking for an output like:</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto'] word&gt; La word&gt; word&gt; felicità word&gt; word&gt; è word&gt; word&gt; tutto </code></pre> <p>To be noted that s is a string that is returned from another method so I cannot force the encoding like</p> <pre><code>s=u"La felicità è tutto" </code></pre> <p>On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.</p> <p>Thanks.</p> <p>Alessandro</p>
11
2009-03-15T11:24:44Z
3,234,376
<p>using a unicode regular expression will work, provided you give it a unicode string to start with (which you haven't in the provided example). Try this:</p> <pre><code>s=u"La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)",re.UNICODE).split(s) print " s&gt; "+s print " wordlist&gt; "+str(l) for i in l: print " word&gt; "+i </code></pre> <p>Results:</p> <pre><code> s&gt; La felicità è tutto wordlist&gt; [u'La', u' ', u'felicit\xe0', u' ', u'\xe8', u' ', u'tutto'] word&gt; La word&gt; word&gt; felicità word&gt; word&gt; è word&gt; word&gt; tutto </code></pre> <p>Your string <code>s</code> is created as a <code>str</code> type, and will probably be in utf-8 coding, which is different than unicode.</p>
3
2010-07-13T05:17:58Z
[ "python", "regex", "unicode", "split" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
647,774
<p>The reason for why <code>r'\'</code> is syntactical incorrect is that although the string expression is raw the used quotes (single or double) always have to be escape since they would mark the end of the quote otherwise. So if you want to express a single quote inside single quoted string, there is no other way than using <code>\'</code>. Same applies for double quotes.</p> <p>But you could use:</p> <pre><code>'\\' </code></pre>
2
2009-03-15T12:59:20Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
647,787
<p>The reason is explained in the part of that section which I highlighted in bold:</p> <blockquote> <p><strong>String quotes can be escaped with a backslash,</strong> but the backslash remains in the string; for example, <code>r"\""</code> is a valid string literal consisting of two characters: a backslash and a double quote; <code>r"\"</code> is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.</p> </blockquote> <p>So raw strings are not 100% raw, there is still some rudimentary backslash-processing.</p>
61
2009-03-15T13:05:31Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
647,797
<p>That's the way it is! I see it as one of those small defects in python!</p> <p>I don't think there's a good reason for it, but it's definitely not parsing; it's really easy to parse raw strings with \ as a last character.</p> <p>The catch is, if you allow \ to be the last character in a raw string then you won't be able to put " inside a raw string. It seems python went with allowing " instead of allowing \ as the last character.</p> <p>However, this shouldn't cause any trouble.</p> <p>If you're worried about not being able to easily write windows folder pathes such as <code>c:\mypath\</code> then worry not, for, you can represent them as <code>r"C:\mypath"</code>, and, if you need to append a subdirectory name, don't do it with string concatenation, for it's not the right way to do it anyway! use <code>os.path.join</code></p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.join(r"C:\mypath", "subfolder") 'C:\\mypath\\subfolder' </code></pre>
13
2009-03-15T13:17:10Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
647,877
<p>Another user who has since deleted their answer (not sure if they'd like to be credited) suggested that the Python language designers may be able to simplify the parser design by using the same parsing rules and expanding escaped characters to raw form as an afterthought (if the literal was marked as raw).</p> <p>I thought it was an interesting idea and am including it as community wiki for posterity.</p>
1
2009-03-15T14:20:01Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
648,135
<p>Since \" is allowed inside the raw string. Then it can't be used to identify the end of the string literal. </p> <p>Why not stop parsing the string literal when you encounter the first "?</p> <p>If that was the case, then \" wouldn't be allowed inside the string literal. But it is.</p>
7
2009-03-15T16:59:09Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
648,168
<p>Comming from C it pretty clear to me that a single \ works as escape character allowing you to put special characters such as newlines, tabs and quotes into strings.</p> <p>That does indeed disallow \ as last character since it will escape the " and make the parser choke. But as pointed out earlier \ is legal.</p>
0
2009-03-15T17:14:37Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
648,671
<p>some tips :</p> <p>1) if you need to manipulate backslash for path then standard python module os.path is your friend. for example : </p> <blockquote> <p>os.path.normpath('c:/folder1/')</p> </blockquote> <p>2) if you want to build strings with backslash in it BUT without backslash at the END of your string then raw string is your friend (use 'r' prefix before your literal string). for example : </p> <pre><code>r'\one \two \three' </code></pre> <p>3) if you need to prefix a string in a variable X with a backslash then you can do this :</p> <pre><code>X='dummy' bs=r'\ ' # don't forget the space after backslash or you will get EOL error X2=bs[0]+X # X2 now contains \dummy </code></pre> <p>4) if you need to create a string with a backslash at the end then combine tip 2 and 3 :</p> <pre><code>voice_name='upper' lilypond_display=r'\DisplayLilyMusic \ ' # don't forget the space at the end lilypond_statement=lilypond_display[:-1]+voice_name </code></pre> <p>now lilypond_statement contains <code>"\DisplayLilyMusic \upper"</code></p> <p>long live python ! :)</p> <p>n3on</p>
-1
2009-03-15T22:22:05Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
5,830,053
<p>In order for you to end a raw string with a slash I suggest you can use this trick:</p> <pre><code>&gt;&gt;&gt; print r"c:\test"'\\' test\ </code></pre>
8
2011-04-29T08:57:03Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
7,986,539
<p>Another trick is to use chr(92) as it evaluates to "\". </p> <p>I recently had to clean a string of backslashes and the following did the trick:</p> <pre><code>CleanString = DirtyString.replace(chr(92),'') </code></pre> <p>I realize that this does not take care of the "why" but the thread attracts many people looking for a solution to an immediate problem.</p>
11
2011-11-02T19:54:40Z
[ "python", "string", "literals" ]
Why can't Python's raw string literals end with a single backslash?
647,769
<p>Technically, any odd number of backslashes, as described in <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">the docs</a>.</p> <pre><code>&gt;&gt;&gt; r'\' File "&lt;stdin&gt;", line 1 r'\' ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\' File "&lt;stdin&gt;", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal </code></pre> <p>It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!</p>
85
2009-03-15T12:54:53Z
19,654,184
<p>The whole misconception about python's raw strings is that most of people think that backslash (within a raw string) is just a regular character as all others. It is NOT. The key to understand is this python's tutorial sequence:</p> <blockquote> <p>When an '<strong>r</strong>' or '<strong>R</strong>' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string</p> </blockquote> <p>So any character following a backslash <strong>is</strong> part of raw string. Once parser enters a raw string (non unicode one) and encounters a backslash it knows there are 2 characters (a backslash and a char following it).</p> <p>This way:</p> <blockquote> <p><strong>r'abc\d'</strong> comprises <strong>a, b, c, \, d</strong></p> <p><strong>r'abc\'d'</strong> comprises <strong>a, b, c, \, ', d</strong></p> <p><strong>r'abc\''</strong> comprises <strong>a, b, c, \, '</strong></p> </blockquote> <p>and:</p> <blockquote> <p><strong>r'abc\'</strong> comprises <strong>a, b, c, \, '</strong> but there is no terminating quote now.</p> </blockquote> <p>Last case shows that according to documentation now a parser cannot find closing quote as the last qoute you see above is part of the string ie. backslash cannot be last here as it will 'devour' string closing char.</p>
14
2013-10-29T09:24:45Z
[ "python", "string", "literals" ]
Trapping MySQL Warnings In Python
647,805
<p>I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit <code>'DROP DATABASE IF EXISTS database_of_armaments'</code> when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.</p> <p>The try/except syntax does catch MySQL errors (eg, submission of a typo like <code>'DRP DATABASE database_of_armaments'</code>). </p> <p>I have experimented with <code>&lt;&lt;except.MySQLdb.Warning&gt;&gt;</code> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.</p> <p>To be concrete, how do I get the following (or something like it) to work.</p> <p>GIVEN: database 'database_of_armaments' does not exist.</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: &lt;&lt;WHAT DO I PUT HERE?&gt;&gt; print 'There was a MySQL warning.' &lt;&lt;AND what goes here if I want to get and manipulate information about the warning?&gt;&gt; </code></pre> <p>UPDATE:</p> <p>Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.</p> <p>So now I have to figure out what is wrong with my class coding.</p> <p>Thank you for your help.</p>
13
2009-03-15T13:25:52Z
647,811
<p>Follow these steps.</p> <ol> <li><p>Run it with <code>except Exception, e: print repr(e)</code>.</p></li> <li><p>See what exception you get.</p></li> <li><p>Change the <code>Exception</code> to the exception you actually got.</p></li> </ol> <p>Also, remember that the exception, e, is an object. You can print <code>dir(e)</code>, <code>e.__class__.__name__</code>, etc.to see what attributes it has.</p> <p>Also, you can do this interactively at the <code>&gt;&gt;&gt;</code> prompt in Python. You can then manipulate the object directly -- no guessing.</p>
14
2009-03-15T13:32:39Z
[ "python", "mysql" ]
Trapping MySQL Warnings In Python
647,805
<p>I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit <code>'DROP DATABASE IF EXISTS database_of_armaments'</code> when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.</p> <p>The try/except syntax does catch MySQL errors (eg, submission of a typo like <code>'DRP DATABASE database_of_armaments'</code>). </p> <p>I have experimented with <code>&lt;&lt;except.MySQLdb.Warning&gt;&gt;</code> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.</p> <p>To be concrete, how do I get the following (or something like it) to work.</p> <p>GIVEN: database 'database_of_armaments' does not exist.</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: &lt;&lt;WHAT DO I PUT HERE?&gt;&gt; print 'There was a MySQL warning.' &lt;&lt;AND what goes here if I want to get and manipulate information about the warning?&gt;&gt; </code></pre> <p>UPDATE:</p> <p>Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.</p> <p>So now I have to figure out what is wrong with my class coding.</p> <p>Thank you for your help.</p>
13
2009-03-15T13:25:52Z
647,820
<p>Have you tried something like this?</p> <pre><code>try: cursor.execute(some_statement) except MySQLdb.IntegrityError, e: # handle a specific error condition except MySQLdb.Error, e: # handle a generic error condition except MySQLdb.Warning, e: # handle warnings, if the cursor you're using raises them </code></pre>
4
2009-03-15T13:39:11Z
[ "python", "mysql" ]
Trapping MySQL Warnings In Python
647,805
<p>I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit <code>'DROP DATABASE IF EXISTS database_of_armaments'</code> when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.</p> <p>The try/except syntax does catch MySQL errors (eg, submission of a typo like <code>'DRP DATABASE database_of_armaments'</code>). </p> <p>I have experimented with <code>&lt;&lt;except.MySQLdb.Warning&gt;&gt;</code> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.</p> <p>To be concrete, how do I get the following (or something like it) to work.</p> <p>GIVEN: database 'database_of_armaments' does not exist.</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: &lt;&lt;WHAT DO I PUT HERE?&gt;&gt; print 'There was a MySQL warning.' &lt;&lt;AND what goes here if I want to get and manipulate information about the warning?&gt;&gt; </code></pre> <p>UPDATE:</p> <p>Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.</p> <p>So now I have to figure out what is wrong with my class coding.</p> <p>Thank you for your help.</p>
13
2009-03-15T13:25:52Z
647,834
<p>I think the exception you want to catch is a MySQLdb.ProgrammingError, and to get information about it, just add a variable to store the error data (a tuple) in after that i.e:</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except MySQLdb.ProgrammingError, e: print 'There was a MySQL warning. This is the info we have about it: %s' %(e) </code></pre>
2
2009-03-15T13:48:53Z
[ "python", "mysql" ]
Trapping MySQL Warnings In Python
647,805
<p>I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit <code>'DROP DATABASE IF EXISTS database_of_armaments'</code> when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.</p> <p>The try/except syntax does catch MySQL errors (eg, submission of a typo like <code>'DRP DATABASE database_of_armaments'</code>). </p> <p>I have experimented with <code>&lt;&lt;except.MySQLdb.Warning&gt;&gt;</code> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.</p> <p>To be concrete, how do I get the following (or something like it) to work.</p> <p>GIVEN: database 'database_of_armaments' does not exist.</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: &lt;&lt;WHAT DO I PUT HERE?&gt;&gt; print 'There was a MySQL warning.' &lt;&lt;AND what goes here if I want to get and manipulate information about the warning?&gt;&gt; </code></pre> <p>UPDATE:</p> <p>Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.</p> <p>So now I have to figure out what is wrong with my class coding.</p> <p>Thank you for your help.</p>
13
2009-03-15T13:25:52Z
5,681,593
<p>first you should turn on warnings to treat as exceptions, and only then you can catch them. see standard "warnings" module for details.</p>
1
2011-04-15T19:46:05Z
[ "python", "mysql" ]
Trapping MySQL Warnings In Python
647,805
<p>I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit <code>'DROP DATABASE IF EXISTS database_of_armaments'</code> when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.</p> <p>The try/except syntax does catch MySQL errors (eg, submission of a typo like <code>'DRP DATABASE database_of_armaments'</code>). </p> <p>I have experimented with <code>&lt;&lt;except.MySQLdb.Warning&gt;&gt;</code> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.</p> <p>To be concrete, how do I get the following (or something like it) to work.</p> <p>GIVEN: database 'database_of_armaments' does not exist.</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: &lt;&lt;WHAT DO I PUT HERE?&gt;&gt; print 'There was a MySQL warning.' &lt;&lt;AND what goes here if I want to get and manipulate information about the warning?&gt;&gt; </code></pre> <p>UPDATE:</p> <p>Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.</p> <p>So now I have to figure out what is wrong with my class coding.</p> <p>Thank you for your help.</p>
13
2009-03-15T13:25:52Z
33,024,014
<p>Plain and simple</p> <pre><code>def log_warnings(curs): for msg in curs.messages: if msg[0] == MySQLdb.Warning: logging.warn(msg[1]) cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') log_warnings(cursor) </code></pre> <p>msg[1] example :- <code>(u'Warning', 1366L, u"Incorrect integer value: '\xa3' for column 'in_userid' at row 1")</code></p>
0
2015-10-08T19:07:42Z
[ "python", "mysql" ]
Trapping MySQL Warnings In Python
647,805
<p>I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit <code>'DROP DATABASE IF EXISTS database_of_armaments'</code> when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears.</p> <p>The try/except syntax does catch MySQL errors (eg, submission of a typo like <code>'DRP DATABASE database_of_armaments'</code>). </p> <p>I have experimented with <code>&lt;&lt;except.MySQLdb.Warning&gt;&gt;</code> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax.</p> <p>To be concrete, how do I get the following (or something like it) to work.</p> <p>GIVEN: database 'database_of_armaments' does not exist.</p> <pre><code>try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: &lt;&lt;WHAT DO I PUT HERE?&gt;&gt; print 'There was a MySQL warning.' &lt;&lt;AND what goes here if I want to get and manipulate information about the warning?&gt;&gt; </code></pre> <p>UPDATE:</p> <p>Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised.</p> <p>So now I have to figure out what is wrong with my class coding.</p> <p>Thank you for your help.</p>
13
2009-03-15T13:25:52Z
38,461,265
<p>I managed to trap the mysql warning like this:</p> <pre><code>import _mysql_exceptions try: foo.bar() except _mysql_exceptions.Warning, e: pass </code></pre>
1
2016-07-19T14:23:30Z
[ "python", "mysql" ]
socket trouble in python
647,813
<p>I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some_file" when it wants to send a file, followed by the file's contents, and the string "end some_file". Here is my client code :</p> <pre><code> file = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) send_str = "send %s" % file end_str = "end %s" % file sock.send(send_str) sock.send("\n") sock.send(open(file).read()) sock.send("\n") sock.send(end_str) sock.send("\n") </code></pre> <p>The problem is this :</p> <ul> <li><p>the server receives the "send some_file" string from a recv</p></li> <li><p>at the second recv, the file's content and the "end file" strings are sent together</p></li> </ul> <p>In the server code, the buffer's size is 4096. I first noticed this bug when trying to send a file that's less than 4096k. How can I make sure that the server receives the strings independently?</p>
4
2009-03-15T13:34:19Z
647,817
<p>With socket programming, even if you do 2 independent sends, it doesn't mean that the other side will receive them as 2 independent recvs.</p> <p>One simple solution that works for both strings and binary data is to: First send the number of bytes in the message, then send the message.</p> <p>Here is what you should do for each message whether it is a file or a string:</p> <p><strong>Sender side:</strong></p> <ul> <li>Send 4 bytes that holds the number of bytes in the following send</li> <li>Send the actual data</li> </ul> <p><strong>Receiver side:</strong></p> <ul> <li>From the receiver side do a loop that blocks on a read for 4 bytes</li> <li>Then do a block on a read for the number of characters specified in the preceding 4 bytes to get the data.</li> </ul> <p>Along with the 4-byte length header I mentioned above, you could also add a constant size command type header (integer again) that describes what's in the following recv.</p> <p>You could also consider using a protocol like HTTP which already does a lot of the work for you and has nice wrapper libraries.</p>
9
2009-03-15T13:36:36Z
[ "python", "sockets" ]
socket trouble in python
647,813
<p>I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some_file" when it wants to send a file, followed by the file's contents, and the string "end some_file". Here is my client code :</p> <pre><code> file = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) send_str = "send %s" % file end_str = "end %s" % file sock.send(send_str) sock.send("\n") sock.send(open(file).read()) sock.send("\n") sock.send(end_str) sock.send("\n") </code></pre> <p>The problem is this :</p> <ul> <li><p>the server receives the "send some_file" string from a recv</p></li> <li><p>at the second recv, the file's content and the "end file" strings are sent together</p></li> </ul> <p>In the server code, the buffer's size is 4096. I first noticed this bug when trying to send a file that's less than 4096k. How can I make sure that the server receives the strings independently?</p>
4
2009-03-15T13:34:19Z
647,821
<p>TCP/IP data is buffered, more-or-less randomly.</p> <p>It's just a "stream" of bytes. If you want, you can read it as though it's delimited by '\n' characters. However, it is not broken into meaningful chunks; nor can it be. It must be a continuous stream of bytes.</p> <p>How are you reading it in C? Are you reading up to a '\n'? Or are you simply reading everything in the buffer?</p> <p>If you're reading everything in the buffer, you should see the lines buffered more-or-less randomly.</p> <p>If you read up to a '\n', however, you'll see each line one at a time.</p> <p>If you want this to really work, you should read <a href="http://www.w3.org/Protocols/rfc959/" rel="nofollow">http://www.w3.org/Protocols/rfc959/</a>. This shows how to transfer files simply and reliably: use two sockets. One for the commands, the other for the data.</p>
-3
2009-03-15T13:39:25Z
[ "python", "sockets" ]
socket trouble in python
647,813
<p>I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some_file" when it wants to send a file, followed by the file's contents, and the string "end some_file". Here is my client code :</p> <pre><code> file = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) send_str = "send %s" % file end_str = "end %s" % file sock.send(send_str) sock.send("\n") sock.send(open(file).read()) sock.send("\n") sock.send(end_str) sock.send("\n") </code></pre> <p>The problem is this :</p> <ul> <li><p>the server receives the "send some_file" string from a recv</p></li> <li><p>at the second recv, the file's content and the "end file" strings are sent together</p></li> </ul> <p>In the server code, the buffer's size is 4096. I first noticed this bug when trying to send a file that's less than 4096k. How can I make sure that the server receives the strings independently?</p>
4
2009-03-15T13:34:19Z
647,835
<p>Possibly using</p> <pre><code>sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) </code></pre> <p>will help send each packet as you want it as this disables <a href="http://en.wikipedia.org/wiki/Nagle%27s%5Falgorithm" rel="nofollow">Nagle's algorithm</a>, as most TCP stacks use this to join several packets of small-sized data together (and is on by default I believe)</p>
0
2009-03-15T13:50:01Z
[ "python", "sockets" ]
socket trouble in python
647,813
<p>I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some_file" when it wants to send a file, followed by the file's contents, and the string "end some_file". Here is my client code :</p> <pre><code> file = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) send_str = "send %s" % file end_str = "end %s" % file sock.send(send_str) sock.send("\n") sock.send(open(file).read()) sock.send("\n") sock.send(end_str) sock.send("\n") </code></pre> <p>The problem is this :</p> <ul> <li><p>the server receives the "send some_file" string from a recv</p></li> <li><p>at the second recv, the file's content and the "end file" strings are sent together</p></li> </ul> <p>In the server code, the buffer's size is 4096. I first noticed this bug when trying to send a file that's less than 4096k. How can I make sure that the server receives the strings independently?</p>
4
2009-03-15T13:34:19Z
647,865
<p>There are two much simpler ways I can think of in which you can solve this. Both involve some changes in the behaviors of both the client and the server.</p> <p>The first is to use padding. Let's say you're sending a file. What you would do is read the file, encode this into a simpler format like Base64, then send enough space characters to fill up the rest of the 4096-byte 'chunk'. What you would do is something like this:</p> <pre><code>from cStringIO import StringIO import base64 import socket import sys CHUNK_SIZE = 4096 # bytes # Extract the socket data from the file arguments filename = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) # Make the socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) # Prepare the message to send send_str = "send %s" % (filename,) end_str = "end %s" % (filename,) data = open(filename).read() encoded_data = base64.b64encode(data) encoded_fp = StringIO(encoded_data) sock.send(send_str + '\n') chunk = encoded_fp.read(CHUNK_SIZE) while chunk: sock.send(chunk) if len(chunk) &lt; CHUNK_SIZE: sock.send(' ' * (CHUNK_SIZE - len(chunk))) chunk = encoded_fp.read(CHUNK_SIZE) sock.send('\n' + end_str + '\n') </code></pre> <p>This example seems a little more involved, but it will ensure that the server can keep reading data in 4096-byte chunks, and all it has to do is Base64-decode the data on the other end (a C library for which is available <a href="http://libb64.sourceforge.net/" rel="nofollow">here</a>. The Base64 decoder ignores the extra spaces, and the format can handle both binary and text files (what would happen, for example, if a file contained the "end filename" line? It would confuse the server).</p> <p>The other approach is to prefix the sending of the file with the file's length. So for example, instead of sending <code>send filename</code> you might say <code>send 4192 filename</code> to specify that the length of the file is 4192 bytes. The client would have to build the <code>send_str</code> based on the length of the file (as read into the <code>data</code> variable in the code above), and would not need to use Base64 encoding as the server would not try to interpret any <code>end filename</code> syntax appearing in the body of the sent file. This is what happens in HTTP; the <code>Content-length</code> HTTP header is used to specify how long the sent data is. An example client might look like this:</p> <pre><code>import socket import sys # Extract the socket data from the file arguments filename = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) # Make the socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) # Prepare the message to send data = open(filename).read() send_str = "send %d %s" % (len(data), filename) end_str = "end %s" % (filename,) sock.send(send_str + '\n') sock.send(data) sock.send('\n' + end_str + '\n') </code></pre> <p>Either way, you're going to have to make changes to both the server and the client. In the end it would probably be easier to implement a rudimentary HTTP server (or to get one which has already been implemented) in C, as it seems that's what you're doing here. The encoding/padding solution is quick but creates a lot of redundantly-sent data (as Base64 typically causes a 33% increase in the quantity of data sent), the length prefix solution is also easy from the client side but may be more difficult on the server.</p>
1
2009-03-15T14:12:31Z
[ "python", "sockets" ]
File handling in Django when posting image from service call
647,888
<p>I am using <a href="http://pyamf.org/">PyAMF</a> to transfer a dynamically generated large image from Flex to Django. On the Django side i receive the encodedb64 data as a parameter:</p> <p>My Item model as an imagefield. What i have trouble to do is saving the data as the File Django Field.</p> <pre><code>def save_item(request, uname, data): """ Save a new item """ item = Item() img = cStringIO.StringIO() img.write(base64.b64decode(data)) myFile = File(img) item.preview.save('fakename.jpg', myFile, save=False) </code></pre> <p>That would not work because my File object from StringIO misses some properties such as mode, name etc.</p> <p>I also think that using StringIO will load the image data completely in memory which is bad so i may just give up on the AMF for this particular case and use POST.</p> <p>What do you think ?</p>
7
2009-03-15T14:23:25Z
648,050
<p>In <code>django.core.files.base</code> you can find the class <code>ContentFile</code>. That class extends the basic Django <code>File</code> class, so you do not need StringIO (which ContentFile though uses internally). The modified save method looks like this:</p> <pre><code>from django.core.files.base import ContentFile def save_item(request, uname, data): item = Item() myFile = ContentFile(base64.b64decode(data)) item.preview.save('fakename.jpg', myFile, save=False) </code></pre>
9
2009-03-15T16:08:11Z
[ "python", "django", "flex", "pyamf" ]
Python - test that succeeds when exception is not raised
647,900
<p>I know about <code>unittest</code> Python module.</p> <p>I know about <code>assertRaises()</code> method of <code>TestCase</code> class.</p> <p>I would like to write a test that succeeds when an exception is <strong>not</strong> raised.</p> <p>Any hints please?</p>
11
2009-03-15T14:33:34Z
647,919
<pre><code>def runTest(self): try: doStuff() except: self.fail("Encountered an unexpected exception.") </code></pre> <p>UPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before failing. You should also catch the most specific exceptions possible.</p>
18
2009-03-15T14:48:33Z
[ "python", "unit-testing", "exception", "exception-handling" ]
Python - test that succeeds when exception is not raised
647,900
<p>I know about <code>unittest</code> Python module.</p> <p>I know about <code>assertRaises()</code> method of <code>TestCase</code> class.</p> <p>I would like to write a test that succeeds when an exception is <strong>not</strong> raised.</p> <p>Any hints please?</p>
11
2009-03-15T14:33:34Z
647,949
<p>The test runner will catch all exceptions you didn't assert would be raised. Thus:</p> <pre><code>doStuff() self.assert_(True) </code></pre> <p>This should work fine. You can leave out the self.assert_ call, since it doesn't really do anything. I like to put it there to document that I didn't forget an assertion.</p>
12
2009-03-15T15:03:50Z
[ "python", "unit-testing", "exception", "exception-handling" ]
Python - test that succeeds when exception is not raised
647,900
<p>I know about <code>unittest</code> Python module.</p> <p>I know about <code>assertRaises()</code> method of <code>TestCase</code> class.</p> <p>I would like to write a test that succeeds when an exception is <strong>not</strong> raised.</p> <p>Any hints please?</p>
11
2009-03-15T14:33:34Z
4,711,722
<p>I use this pattern for the kind of assertion you've asked:</p> <pre><code>with self.assertRaises(Exception): try: doStuff() except: pass else: raise Exception </code></pre> <p>It will fail exactly when exception is raised by doStuff().</p>
4
2011-01-17T09:39:07Z
[ "python", "unit-testing", "exception", "exception-handling" ]
wxPython auinotebook.GetSelection() return index to the first page
647,906
<p>Why do 'GetSelection()' return the index to the first page and not the last created in 'init' and 'new_panel'? It do return correct index in the 'click' method.</p> <p>The output should be 0 0 1 1 2 2, but mine is 0 0 0 0 0 0.</p> <p>Running latest version of python and wxpython in ArchLinux.</p> <p>Ørjan Pettersen</p> <pre><code>#!/usr/bin/python #12_aui_notebook1.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) self.nb = wx.aui.AuiNotebook(self) self.new_panel('Page 1') print self.nb.GetSelection() self.new_panel('Page 2') print self.nb.GetSelection() self.new_panel('Page 3') print self.nb.GetSelection() def new_panel(self, nm): pnl = wx.Panel(self) pnl.identifierTag = nm self.nb.AddPage(pnl, nm) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) pnl.SetFocus() # Have focused the last panel. print self.nb.GetSelection() pnl.Bind(wx.EVT_LEFT_DOWN, self.click) def click(self, event): print 'Mouse click' print self.nb.GetSelection() print self.nb.GetPageText(self.nb.GetSelection()) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '12_aui_notebook1.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop() </code></pre>
1
2009-03-15T14:37:49Z
648,520
<p>I ran your example and got the correct output:</p> <pre><code>0 0 1 1 2 2 </code></pre> <p>I'm using the latest windows release of wxPython</p>
0
2009-03-15T20:50:15Z
[ "python", "wxpython", "wxwidgets" ]
wxPython auinotebook.GetSelection() return index to the first page
647,906
<p>Why do 'GetSelection()' return the index to the first page and not the last created in 'init' and 'new_panel'? It do return correct index in the 'click' method.</p> <p>The output should be 0 0 1 1 2 2, but mine is 0 0 0 0 0 0.</p> <p>Running latest version of python and wxpython in ArchLinux.</p> <p>Ørjan Pettersen</p> <pre><code>#!/usr/bin/python #12_aui_notebook1.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) self.nb = wx.aui.AuiNotebook(self) self.new_panel('Page 1') print self.nb.GetSelection() self.new_panel('Page 2') print self.nb.GetSelection() self.new_panel('Page 3') print self.nb.GetSelection() def new_panel(self, nm): pnl = wx.Panel(self) pnl.identifierTag = nm self.nb.AddPage(pnl, nm) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) pnl.SetFocus() # Have focused the last panel. print self.nb.GetSelection() pnl.Bind(wx.EVT_LEFT_DOWN, self.click) def click(self, event): print 'Mouse click' print self.nb.GetSelection() print self.nb.GetPageText(self.nb.GetSelection()) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '12_aui_notebook1.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop() </code></pre>
1
2009-03-15T14:37:49Z
649,556
<p>The solution was pretty simple. The problem seemed to be that creating the new page didn't generate a page change event. The solution is:</p> <pre><code>self.nb.AddPage(pnl, nm, select=True) </code></pre> <p>Adding 'select=True' will trigger a page change event. So problem solved.</p> <p>Another solution is to add this line:</p> <pre><code>self.nb.SetSelection(self.nb.GetPageCount()-1) </code></pre> <p>They both do the same. Trigger a page change event to the last added page.</p> <pre><code>def new_panel(self, nm): pnl = wx.Panel(self) pnl.identifierTag = nm self.nb.AddPage(pnl, nm, select=True) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) #self.nb.SetSelection(self.nb.GetPageCount()-1) pnl.SetFocus() # Have focused the last panel. print self.nb.GetSelection() </code></pre>
1
2009-03-16T07:27:45Z
[ "python", "wxpython", "wxwidgets" ]
How to make a list comprehension with the group() method in python?
648,276
<p>I'm trying to write a little script to clean my directories. In fact I have:</p> <pre><code>pattern = re.compile(format[i]) ... current_f.append(pattern.search(str(ls))) </code></pre> <p>and I want to use a list comprehension but when I try:</p> <pre><code>In [25]: [i for i in current_f.group(0)] </code></pre> <p>I get:</p> <pre><code>AttributeError: 'list' object has no attribute 'group' </code></pre> <p>So how to make a list comprehension using group()? Is there another way to do what I want.</p> <p>Thanks in advance.</p>
3
2009-03-15T18:21:24Z
648,287
<p>Are you trying to do this?:</p> <pre><code>[f.group(0) for f in current_f] </code></pre>
7
2009-03-15T18:27:53Z
[ "python", "list", "group", "list-comprehension" ]
Clashing guidelines
648,299
<p>While coding in Python it's better to code by following the guidelines of PEP8.</p> <p>And while coding for Symbian it's better to follow its coding standards.</p> <p>But when I code for PyS60 which guidelines should I follow? Till now I have been following PEP8, but <a href="http://wiki.forum.nokia.com/index.php/A%5F100%25%5FPython%5Fimplemented%5FListbox%5Fbase%5Fclass" rel="nofollow">this code</a> shows the opposite. Do I need to rework my code?</p>
1
2009-03-15T18:35:19Z
648,444
<p>Use the style of the API(s) you're interfacing the most. That's a simple rule that works in most places (where you can see the code, i.e. Java/C# is a bit hard(er).. :)</p>
1
2009-03-15T20:02:29Z
[ "python", "symbian", "coding-style", "pys60", "pep8" ]
Clashing guidelines
648,299
<p>While coding in Python it's better to code by following the guidelines of PEP8.</p> <p>And while coding for Symbian it's better to follow its coding standards.</p> <p>But when I code for PyS60 which guidelines should I follow? Till now I have been following PEP8, but <a href="http://wiki.forum.nokia.com/index.php/A%5F100%25%5FPython%5Fimplemented%5FListbox%5Fbase%5Fclass" rel="nofollow">this code</a> shows the opposite. Do I need to rework my code?</p>
1
2009-03-15T18:35:19Z
648,598
<p>"Do I need to rework my code?"</p> <p>Does it add value to rework you code?</p> <p>How many folks will help you develop code who </p> <p>A) don't know PEP 8</p> <p>B) only know PyS60 coding standards because that's the only code they've ever seen.</p> <p>and</p> <p>C) cannot be taught anything different than the PyS60 coding standards?</p> <p>List all the people who you'll work with that meet all three criteria. Then decide which is cheaper: rework your code or fire them.</p>
2
2009-03-15T21:43:10Z
[ "python", "symbian", "coding-style", "pys60", "pep8" ]
Clashing guidelines
648,299
<p>While coding in Python it's better to code by following the guidelines of PEP8.</p> <p>And while coding for Symbian it's better to follow its coding standards.</p> <p>But when I code for PyS60 which guidelines should I follow? Till now I have been following PEP8, but <a href="http://wiki.forum.nokia.com/index.php/A%5F100%25%5FPython%5Fimplemented%5FListbox%5Fbase%5Fclass" rel="nofollow">this code</a> shows the opposite. Do I need to rework my code?</p>
1
2009-03-15T18:35:19Z
648,948
<p>I don't see anything in your code sample that is obviously bogus. It's not the style I'd use, but neither is it hard to read, and it's not so far from PEP8 that I'd call it “the opposite”.</p> <p>PEP8 shouldn't be seen as hard-and-fast law to which all code must conform, character by rigid character. It is a baseline for readable Python. When you go a little bit Java-programmer and get that antsiness about making the spacing around every operator consistent, go back and read the start of PEP8 again. The bit with the hobgoblin.</p> <p>Don't get hung up on lengthy ‘reworking’ of code that is functional, readable, and at least in the same general vicinity as PEP8.</p>
2
2009-03-16T01:20:42Z
[ "python", "symbian", "coding-style", "pys60", "pep8" ]
Clashing guidelines
648,299
<p>While coding in Python it's better to code by following the guidelines of PEP8.</p> <p>And while coding for Symbian it's better to follow its coding standards.</p> <p>But when I code for PyS60 which guidelines should I follow? Till now I have been following PEP8, but <a href="http://wiki.forum.nokia.com/index.php/A%5F100%25%5FPython%5Fimplemented%5FListbox%5Fbase%5Fclass" rel="nofollow">this code</a> shows the opposite. Do I need to rework my code?</p>
1
2009-03-15T18:35:19Z
677,935
<p>i'd say use PEP8, but as mentioned above, don't get too hung up on it. when coding IN symbian c++ you should use symbian coding standards, but not necessarily if your program is merely running on the platform. don't get confused between symbian the OS and symbian c++ the (psuedo) language.</p>
0
2009-03-24T15:31:13Z
[ "python", "symbian", "coding-style", "pys60", "pep8" ]
Clashing guidelines
648,299
<p>While coding in Python it's better to code by following the guidelines of PEP8.</p> <p>And while coding for Symbian it's better to follow its coding standards.</p> <p>But when I code for PyS60 which guidelines should I follow? Till now I have been following PEP8, but <a href="http://wiki.forum.nokia.com/index.php/A%5F100%25%5FPython%5Fimplemented%5FListbox%5Fbase%5Fclass" rel="nofollow">this code</a> shows the opposite. Do I need to rework my code?</p>
1
2009-03-15T18:35:19Z
915,208
<p>Your example code is just that person's personal style. It's NOT following official PyS60 coding convension, there is no such a thing! Write whatever style gives you the best results.</p> <p>Having said that I would recommend using PEP8, but only if you plan to use pylint to give you some additional confidence in your project.</p> <p>I've done nothing but PyS60 stuff, never real python. Used pylint to speedup development time and to automatically point me some potential defects before I run into them in real life.</p>
0
2009-05-27T11:25:57Z
[ "python", "symbian", "coding-style", "pys60", "pep8" ]
A trivial Python SWIG error question
648,482
<p>I am trying to get Python running with swig to do C/C++. I am running the tutorial <a href="http://www.swig.org/tutorial.html">here</a>, 'building a python module'. When I do the call</p> <pre><code>gcc -c example.c example_wrap.c -I /my_correct_path/python2.5 </code></pre> <p>I get an error:</p> <pre><code>my_correct_path/python2.5/pyport.h:761:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." example_wrap.c: In function 'SWIG_Python_ConvertFunctionPtr': example_wrap.c:2034: warning: initialization discards qualifiers from pointer target type example_wrap.c: In function 'SWIG_Python_FixMethods': example_wrap.c:3232: warning: initialization discards qualifiers from pointer target type </code></pre> <p>It actually does create an example.o file, but it doesn't work. I am using python2.5 not 2.1 as in the example, is this a problem? The error (everything else is just a 'warning') says something about wrong platform. This is a 64bit machine; is this a problem? Is my gcc configured wrong for my machine? How do I get past this? </p> <p>UPDATE: I am still having problems. How do I actually implement this "fix"?</p>
5
2009-03-15T20:27:49Z
2,909,020
<p>I found this thread looking for an answer for the same "LONGBIT" error while installing python readline for 32bit python on 64bit centos. The link doesn't have the direct answer, so I had to google further for the answer (which might be straight-forward for seasoned linux users/devs). For future reference, the solution is to force 32-bit by using "-m32" in CFLAGS environment variable. </p> <pre><code>bash-3.2$ easy_install readline Searching for readline Reading http://pypi.python.org/simple/readline/ Reading http://www.python.org/ Best match: readline 2.6.4 Downloading http://pypi.python.org/packages/source/r/readline/readline-2.6.4.tar.gz#md5=7568e8b78f383443ba57c9afec6f4285 Processing readline-2.6.4.tar.gz Running readline-2.6.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-mqr9wH/readline-2.6.4/egg-dist-tmp-p3apfF In file included from /usr/local/python2.6/include/python2.6/Python.h:58, from Modules/readline.c:8: /usr/local/python2.6/include/python2.6/pyport.h:685:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." error: Setup script exited with error: command 'gcc' failed with exit status 1 </code></pre> <p>I then tried with CFLAGS=-m32:</p> <pre><code>bash-3.2$ CFLAGS=-m32 easy_install readline Searching for readline Reading http://pypi.python.org/simple/readline/ Reading http://www.python.org/ Best match: readline 2.6.4 Downloading http://pypi.python.org/packages/source/r/readline/readline-2.6.4.tar.gz#md5=7568e8b78f383443ba57c9afec6f4285 Processing readline-2.6.4.tar.gz Running readline-2.6.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-uauVci/readline-2.6.4/egg-dist-tmp-YY0tQa In file included from /usr/include/features.h:352, from /usr/include/limits.h:27, from /usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h:122, from /usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h:7, from /usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h:11, from /usr/local/python2.6/include/python2.6/Python.h:19, from Modules/readline.c:8: /usr/include/gnu/stubs.h:7:27: error: gnu/stubs-32.h: No such file or directory error: Setup script exited with error: command 'gcc' failed with exit status 1 </code></pre> <p>The latest error is due to not having glibc-devel package for 32bit (thanks to <a href="http://gcc.gnu.org/ml/fortran/2008-09/msg00120.html">this thread</a>). I also had to install ncurses-devel.i386 and then easy_install went through and ipython recognized it. My life felt ruined until I got this working for the sake of ipython.</p> <pre><code>bash-3.2$ CFLAGS=-m32 easy_install readline Searching for readline Reading http://pypi.python.org/simple/readline/ Reading http://www.python.org/ Best match: readline 2.6.4 Downloading http://pypi.python.org/packages/source/r/readline/readline-2.6.4.tar.gz#md5=7568e8b78f383443ba57c9afec6f4285 Processing readline-2.6.4.tar.gz Running readline-2.6.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-dHly4D/readline-2.6.4/egg-dist-tmp-oIEDYl Adding readline 2.6.4 to easy-install.pth file Installed /home/hari/bin/python/lib/python2.6/site-packages/readline-2.6.4-py2.6-linux-x86_64.egg Processing dependencies for readline Finished processing dependencies for readline </code></pre>
7
2010-05-25T22:36:08Z
[ "python", "swig" ]
A trivial Python SWIG error question
648,482
<p>I am trying to get Python running with swig to do C/C++. I am running the tutorial <a href="http://www.swig.org/tutorial.html">here</a>, 'building a python module'. When I do the call</p> <pre><code>gcc -c example.c example_wrap.c -I /my_correct_path/python2.5 </code></pre> <p>I get an error:</p> <pre><code>my_correct_path/python2.5/pyport.h:761:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." example_wrap.c: In function 'SWIG_Python_ConvertFunctionPtr': example_wrap.c:2034: warning: initialization discards qualifiers from pointer target type example_wrap.c: In function 'SWIG_Python_FixMethods': example_wrap.c:3232: warning: initialization discards qualifiers from pointer target type </code></pre> <p>It actually does create an example.o file, but it doesn't work. I am using python2.5 not 2.1 as in the example, is this a problem? The error (everything else is just a 'warning') says something about wrong platform. This is a 64bit machine; is this a problem? Is my gcc configured wrong for my machine? How do I get past this? </p> <p>UPDATE: I am still having problems. How do I actually implement this "fix"?</p>
5
2009-03-15T20:27:49Z
17,958,342
<p>I had the same error when trying to install a Python package, but fixed it.<br> The "LONG_BIT" error was:</p> <pre><code>$ easy_install astropy /my_path/epd/epd-7.3-2-rh5-x86/include/python2.7/pyport.h:849:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." error: Setup script exited with error: command 'gcc' failed with exit status 1 </code></pre> <p>As you are suggesting, Alex, I had to install the correct version of Python's epd to match the requirement of my machine and that of the package I wanted to install. There were parallel versions of Python running and I think this is where the confusion and error came from. Go to <a href="https://www.enthought.com/products/epd/package-index/" rel="nofollow">Enthought's Repository</a> (click "Log in to the repository" -> Installers) and install the correct version.</p> <p>Make sure you clean things up (or ask someone who knows what they are doing to do this for you) by removing the old Python versions. Then of course change your .cshrc path to point to the new version and source the file correctly. I had no problems after I did this.</p> <p>I realize this questions was asked 4 years ago!</p>
2
2013-07-30T22:09:36Z
[ "python", "swig" ]
A trivial Python SWIG error question
648,482
<p>I am trying to get Python running with swig to do C/C++. I am running the tutorial <a href="http://www.swig.org/tutorial.html">here</a>, 'building a python module'. When I do the call</p> <pre><code>gcc -c example.c example_wrap.c -I /my_correct_path/python2.5 </code></pre> <p>I get an error:</p> <pre><code>my_correct_path/python2.5/pyport.h:761:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." example_wrap.c: In function 'SWIG_Python_ConvertFunctionPtr': example_wrap.c:2034: warning: initialization discards qualifiers from pointer target type example_wrap.c: In function 'SWIG_Python_FixMethods': example_wrap.c:3232: warning: initialization discards qualifiers from pointer target type </code></pre> <p>It actually does create an example.o file, but it doesn't work. I am using python2.5 not 2.1 as in the example, is this a problem? The error (everything else is just a 'warning') says something about wrong platform. This is a 64bit machine; is this a problem? Is my gcc configured wrong for my machine? How do I get past this? </p> <p>UPDATE: I am still having problems. How do I actually implement this "fix"?</p>
5
2009-03-15T20:27:49Z
19,668,382
<p>I actually found this thread twice, a couple years apart, both while trying to install <code>libxml2</code> from source. The library's <code>configure</code> script actually has a <code>--without-python</code> option, which I used instead of trying to fix the error.</p>
0
2013-10-29T20:25:24Z
[ "python", "swig" ]
how can i figure if a vim buffer is listed or unlisted from vim's python api?
648,638
<p>for a tool i need to figure all vim buffers that are still listed (there are listed and unlisted buffers)</p> <p>unfortunately <code>vim.buffers</code> contains all buffers and there doesnt seem to be an attribute to figure if a buffer is listed or unlisted</p> <p>the vim command of what i want to do is</p> <pre><code>:buffers </code></pre> <p>unfortunately all thats possible with the vim python api is emulating</p> <pre><code>:buffers! </code></pre> <p>but without the metadata about listed/unlisted thats we need</p>
2
2009-03-15T22:03:57Z
648,645
<p>Here is how you can manage this using just Vim language.</p> <pre><code>function s:buffers_list() let result = [] for buffer_number in range(1, bufnr('$')) if !buflisted(buffer_number) continue endif call add(result, buffer_number) endfor return result endfunction </code></pre>
5
2009-03-15T22:09:08Z
[ "python", "vim" ]
how can i figure if a vim buffer is listed or unlisted from vim's python api?
648,638
<p>for a tool i need to figure all vim buffers that are still listed (there are listed and unlisted buffers)</p> <p>unfortunately <code>vim.buffers</code> contains all buffers and there doesnt seem to be an attribute to figure if a buffer is listed or unlisted</p> <p>the vim command of what i want to do is</p> <pre><code>:buffers </code></pre> <p>unfortunately all thats possible with the vim python api is emulating</p> <pre><code>:buffers! </code></pre> <p>but without the metadata about listed/unlisted thats we need</p>
2
2009-03-15T22:03:57Z
1,638,543
<p>Using Vim's python api:</p> <pre><code>listedBufs = [] for b in vim.buffers: listed = vim.eval('buflisted(bufnr("%s"))' % b.name) if int(listed) &gt; 0: listedBufs.append(b) </code></pre> <p>or if you don't mind sacrificing some readability:</p> <pre><code>listedBufs = [b for b in vim.buffers if int(vim.eval('buflisted(bufnr("%s"))' % b.name)) &gt; 0] </code></pre>
3
2009-10-28T16:48:55Z
[ "python", "vim" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
648,721
<p>Since they are generator expressions, you can bind each to it's own name to make it more readable without any change in performance. Changing it to a nested loop would likely be detrimental to performance.</p> <pre><code>irange = (i for i in xrange(10)) jrange = (j for j in irange) krange = (k for k in jrange) </code></pre> <p>It really doesn't matter which you choose, I think the multi-line example is more readable, in general.</p>
3
2009-03-15T22:40:38Z
[ "python", "list-comprehension", "generator-expression" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
648,723
<p>In the case of your example, I would probably write it as:</p> <pre><code>foos = (i for i in xrange(10)) bars = (j for j in foos) bazs = (k for k in bars) </code></pre> <p>Given more descriptive names, I think this would probably be quite clear, and I can't imagine there being any measurable performance difference.</p> <p>Perhaps you're thinking more of expressions like:</p> <pre><code>(x for x in xs for xs in ys for ys in lst) </code></pre> <p>-- actually, that's not even valid. You have to put things in the other order:</p> <pre><code>(x for ys in lst for xs in ys for x in xs) </code></pre> <p>I might write that as a quick way of flattening a list, but in general I think you're write: the time you save by typing less is usually balanced by the extra time you spend getting the generator expression right.</p>
5
2009-03-15T22:41:06Z
[ "python", "list-comprehension", "generator-expression" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
648,724
<p>If you're worried about too much complexity on one line, you could split it:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>I've always found line continuations to look a little weird in Python, but this does make it easier to see what each one is looping over. Since an extra assignment/lookup is not going to make or break anything, you could also write it like this:</p> <pre><code>gen1 = (i for i in xrange(10)) gen2 = (j for j in gen1) gen3 = (k for k in gen2) </code></pre> <p>In practice, I don't think I've ever nested a comprehension more than 2-deep, and at that point it was still pretty easy to understand.</p>
11
2009-03-15T22:41:50Z
[ "python", "list-comprehension", "generator-expression" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
648,886
<p>Check <a href="http://www.python.org/dev/peps/pep-0202/">PEP 202</a> which was where list comprehensions syntax was introduced to the language.</p> <p>For understanding your example, there is a simple rule from Guido himself:</p> <ul> <li>The form [... for x... for y...] nests, with the last index varying fastest, just like nested for loops.</li> </ul> <p>Also from PEP 202, which serves to answer your question:</p> <pre> Rationale List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used. </pre> <p>If you had a situation like that, you could find it to be more elegant. IMHO, though, multiple nested list comprehensions may be less clear in your code than nested for loops, since <code>for</code> loops are easily parsed visually. </p>
16
2009-03-16T00:39:51Z
[ "python", "list-comprehension", "generator-expression" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
650,254
<p>The expression:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>is equivalent to:</p> <pre><code>(i for i in xrange(10)) </code></pre> <p>that is almost the same:</p> <pre><code>xrange(10) </code></pre> <p>The last variant is more elegant than the first one.</p>
0
2009-03-16T12:38:54Z
[ "python", "list-comprehension", "generator-expression" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
22,677,755
<p>I find it can be useful and elegant in situations like these where you have code like this:</p> <pre><code>output = [] for item in list: if item &gt;= 1: new = item += 1 output.append(new) </code></pre> <p>You can make it a one-liner like this:</p> <pre><code>output = [item += 1 for item in list if item &gt;= 1] </code></pre>
0
2014-03-27T03:34:58Z
[ "python", "list-comprehension", "generator-expression" ]
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
<p>I see this kind of thing sometimes:</p> <pre><code>(k for k in (j for j in (i for i in xrange(10)))) </code></pre> <p>Now this really bends my brain, and I would rather it wasn't presented in this way.</p> <p>Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop?</p> <p><strong>Edit:</strong> Thanks for the examples of ways to simplify this. It's not actually what I asked for, I was wondering if there were any times when it was elegant.</p>
9
2009-03-15T22:22:52Z
34,982,418
<p>Caveat: elegance is partly a matter of taste.</p> <p>List comprehensions are never more <em>clear</em> than the corresponding expanded for loop. For loops are also more <em>powerful</em> than list comprehensions. So why use them at all?</p> <p>What list comprehensions are is <strong>concise</strong> -- they allow you to do something in a single line.</p> <p>The time to use a list comprehension is when you need a certain list, it can be created on the fly fairly easily, and you don't want or need intermediate objects hanging around. This might happen when you need to package some objects in the current scope into a single object that you can feed into a function, like below:</p> <pre><code>list1 = ['foo', 'bar'] list2 = ['-ness', '-ity'] return filterRealWords([str1+str2 for str1 in list1 for str2 in list2]) </code></pre> <p>This code is about as readable than the expanded version, but it is far shorter. It avoids creating/naming an object that is only used once in the current scope, which is arguably more elegant.</p>
1
2016-01-24T22:38:46Z
[ "python", "list-comprehension", "generator-expression" ]
Print out list of function parameters in Python
648,679
<p>Is there a way to print out a function's parameter list? For example:</p> <pre><code>def func(a, b, c): pass print_func_parametes(func) </code></pre> <p>Which will produce something like:</p> <pre><code>["a", "b", "c"] </code></pre>
4
2009-03-15T22:24:37Z
648,689
<p>Use the inspect module.</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.getargspec(func) (['a', 'b', 'c'], None, None, None) </code></pre> <p>The first part of returned tuple is what you're looking for.</p>
17
2009-03-15T22:27:58Z
[ "python" ]
Print out list of function parameters in Python
648,679
<p>Is there a way to print out a function's parameter list? For example:</p> <pre><code>def func(a, b, c): pass print_func_parametes(func) </code></pre> <p>Which will produce something like:</p> <pre><code>["a", "b", "c"] </code></pre>
4
2009-03-15T22:24:37Z
648,702
<p>Read the source. Seriously. Python programs and libraries are provided as source. You can read the source.</p>
6
2009-03-15T22:31:48Z
[ "python" ]
Print out list of function parameters in Python
648,679
<p>Is there a way to print out a function's parameter list? For example:</p> <pre><code>def func(a, b, c): pass print_func_parametes(func) </code></pre> <p>Which will produce something like:</p> <pre><code>["a", "b", "c"] </code></pre>
4
2009-03-15T22:24:37Z
648,922
<p>You might also try the built-in <code>help()</code> function, which will provide you not only with a list of the named parameters, but also a description of <code>func()</code> if you provided a docstring:</p> <pre><code>&gt;&gt;&gt; def func(a, b, c): ... """do x to a,b,c and return the result""" ... pass ... &gt;&gt;&gt; help(func) </code></pre> <p>gives you </p> <pre> Help on function func in module __main__: func(a, b, c) do x to a,b,c and return the result </pre> <p>Most modules are provided with at least some sort of built-in documentation.</p>
2
2009-03-16T01:03:58Z
[ "python" ]
Why are Python objects of different types ordered by type names?
649,191
<p>From Python docs: <a href="http://docs.python.org/library/stdtypes.html#comparisons" rel="nofollow">http://docs.python.org/library/stdtypes.html#comparisons</a></p> <blockquote> <p>Implementation note: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.</p> </blockquote> <p>Is there any reason for choosing to do this over raising an exception?</p>
2
2009-03-16T03:46:00Z
649,198
<p>It can be useful for objects of different types to be collected into a single, sorted list, in a definite order. By giving all objects a stable sort order, this behavior is default.</p>
1
2009-03-16T03:49:49Z
[ "python" ]
Why are Python objects of different types ordered by type names?
649,191
<p>From Python docs: <a href="http://docs.python.org/library/stdtypes.html#comparisons" rel="nofollow">http://docs.python.org/library/stdtypes.html#comparisons</a></p> <blockquote> <p>Implementation note: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.</p> </blockquote> <p>Is there any reason for choosing to do this over raising an exception?</p>
2
2009-03-16T03:46:00Z
649,199
<p>About four lines up from that line you quoted:</p> <blockquote> <p>Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily <strong>(so that sorting a heterogeneous array yields a consistent result).</strong></p> </blockquote> <p>You don't want to raise exceptions when sorting a list of differently typed objects.</p>
5
2009-03-16T03:51:00Z
[ "python" ]
In Python, is it possible to access the class which contains a method, given only a method object?
649,329
<p>I'm pretty new to Python, and haven't been able to find an answer to this question from searching online.</p> <p>Here is an example decorator that does nothing (yet)</p> <pre><code>def my_decorator(text): def wrap(f): # grab magic f.parent_class_object.my_var and append text def wrap_f(*args, **kwargs): f(*args, **kwargs) return wrap_f return wrap </code></pre> <p>Here is an example class</p> <pre><code>class MyClass: my_var = [] @my_decorator('sometext') def my_func() # do some super cool thing </code></pre> <p>In my decorator i'd like to access the class object for <code>MyClass</code> and add in 'sometext' to the <code>MyClass.my_var</code> list. My goal is to populate my_var with decorated values at <strong>module load</strong> time, not function call time.</p> <p>Is there a way i can navigate from <code>f</code> to <code>MyClass</code> in order to do this? I know that *args[0] is the instance of MyClass, but that is only available when the function is called.</p>
2
2009-03-16T05:08:54Z
649,358
<p>It is not possible to read it from a function inside a class decorator, since the "methods" are still normal function while the class is being compiled. Also, the class name has not been defined while it is being compiled.</p> <p>What you could do is supply the <code>my_var</code> list to the decorator.</p> <pre><code>class MyClass: my_var = [] @my_decorator(my_var, 'sometext') def my_func() # do some super cool thing </code></pre> <p><code>my_var</code> is still a normal variable by then.</p>
3
2009-03-16T05:21:55Z
[ "python", "decorator" ]
Iterability in Python
649,549
<p>I am trying to understand Iterability in Python.</p> <p>As I understand, <code>__iter__()</code> should return an object that has <code>next()</code> method defined which must return a value or raise <code>StopIteration</code> exception. Thus I wrote this class which satisfies both these conditions.</p> <p>But it doesn't seem to work. What is wrong?</p> <pre><code>class Iterator: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i &lt; 5: return self.i else: raise StopIteration if __name__ == __main__: ai = Iterator() b = [i for i in ai] print b </code></pre>
4
2009-03-16T07:20:51Z
649,555
<p><code>i</code> will never become greater than 5 if you don't increment it in <code>next()</code></p>
4
2009-03-16T07:27:40Z
[ "iterator", "python" ]
Iterability in Python
649,549
<p>I am trying to understand Iterability in Python.</p> <p>As I understand, <code>__iter__()</code> should return an object that has <code>next()</code> method defined which must return a value or raise <code>StopIteration</code> exception. Thus I wrote this class which satisfies both these conditions.</p> <p>But it doesn't seem to work. What is wrong?</p> <pre><code>class Iterator: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i &lt; 5: return self.i else: raise StopIteration if __name__ == __main__: ai = Iterator() b = [i for i in ai] print b </code></pre>
4
2009-03-16T07:20:51Z
649,566
<p>Your Iterator class is correct. You just have a typo in this statement:</p> <pre><code>if __name__ ==' __main__': </code></pre> <p>There's a leading whitespace in the ' __main__' string. That's why your code is not executed at all.</p>
9
2009-03-16T07:38:39Z
[ "iterator", "python" ]
Iterability in Python
649,549
<p>I am trying to understand Iterability in Python.</p> <p>As I understand, <code>__iter__()</code> should return an object that has <code>next()</code> method defined which must return a value or raise <code>StopIteration</code> exception. Thus I wrote this class which satisfies both these conditions.</p> <p>But it doesn't seem to work. What is wrong?</p> <pre><code>class Iterator: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i &lt; 5: return self.i else: raise StopIteration if __name__ == __main__: ai = Iterator() b = [i for i in ai] print b </code></pre>
4
2009-03-16T07:20:51Z
649,873
<p>I think in most cases it might be enough to write a <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-yield-statement" rel="nofollow">generator function that uses yield</a> instead of writing a full-fledged iterator. </p>
4
2009-03-16T10:28:03Z
[ "iterator", "python" ]
Iterability in Python
649,549
<p>I am trying to understand Iterability in Python.</p> <p>As I understand, <code>__iter__()</code> should return an object that has <code>next()</code> method defined which must return a value or raise <code>StopIteration</code> exception. Thus I wrote this class which satisfies both these conditions.</p> <p>But it doesn't seem to work. What is wrong?</p> <pre><code>class Iterator: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i &lt; 5: return self.i else: raise StopIteration if __name__ == __main__: ai = Iterator() b = [i for i in ai] print b </code></pre>
4
2009-03-16T07:20:51Z
650,692
<p>Your current code seems to work. Instead i'll show you some more iterators/generators.</p> <p>the simplest builtin with exactly your behavior.</p> <pre><code>Iterator2 = xrange(2,5) </code></pre> <p>A direct translation of your class to a generator</p> <pre><code>def Iterator3(): i = 1 while i &lt; 5: i += 1 yield i </code></pre> <p>a generator composed from generators in the python standard library</p> <pre><code>import itertools Iterator4 = itertools.takewhile( lambda y : y &lt; 5, itertools.count(2) ) </code></pre> <p>a simple generator expression (not very exciting...)</p> <pre><code>Iterator5 = ( x for x in [2, 3, 4] ) </code></pre>
1
2009-03-16T14:36:31Z
[ "iterator", "python" ]
Iterability in Python
649,549
<p>I am trying to understand Iterability in Python.</p> <p>As I understand, <code>__iter__()</code> should return an object that has <code>next()</code> method defined which must return a value or raise <code>StopIteration</code> exception. Thus I wrote this class which satisfies both these conditions.</p> <p>But it doesn't seem to work. What is wrong?</p> <pre><code>class Iterator: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i &lt; 5: return self.i else: raise StopIteration if __name__ == __main__: ai = Iterator() b = [i for i in ai] print b </code></pre>
4
2009-03-16T07:20:51Z
36,095,850
<p>Your code has two problems:</p> <ul> <li><code>if name == '__main__'</code>: (missing quotes)</li> <li><code>def next . . .</code>: you don't increment <code>i</code> anywhere</li> </ul>
0
2016-03-18T23:19:08Z
[ "iterator", "python" ]
Directory checksum with python?
649,623
<p>So I'm in the middle of web-based filesystem abstraction layer development. Just like file browser, except it has some extra features like freaky permissions etc. </p> <p>I would like users to be notified somehow about directory changes. So, i.e. when someone uploads a new file via FTP, certain users should get a proper message. It is not required for the message to be extra detailed, I don't really need to show the exact resource changed. The parent directory name should be enough.</p> <p>What approach would you recommend?</p>
3
2009-03-16T08:22:52Z
649,636
<p>If your server is Linux you can do this with something like <a href="http://pyinotify.sourceforge.net/" rel="nofollow">inotify</a></p> <p>If the only updates are coming from FTP, then another solution I've used in the past is to write an add-on module to <a href="http://www.proftpd.org/features.html" rel="nofollow">ProFTPD</a> that performs the "notification" once upload is complete.</p>
2
2009-03-16T08:29:11Z
[ "python", "file", "filesystems", "checksum" ]
Directory checksum with python?
649,623
<p>So I'm in the middle of web-based filesystem abstraction layer development. Just like file browser, except it has some extra features like freaky permissions etc. </p> <p>I would like users to be notified somehow about directory changes. So, i.e. when someone uploads a new file via FTP, certain users should get a proper message. It is not required for the message to be extra detailed, I don't really need to show the exact resource changed. The parent directory name should be enough.</p> <p>What approach would you recommend?</p>
3
2009-03-16T08:22:52Z
649,638
<p>See this question: <a href="http://stackoverflow.com/questions/479762/how-to-quickly-find-added-removed-files">http://stackoverflow.com/questions/479762/how-to-quickly-find-added-removed-files</a></p> <p>But if you can control the upload somehow (i.e. use HTTP POST instead of FTP), you could simply send a notification after the upload has completed. This has the additional benefit that it would be simple to make sure users never see a partial file.</p>
1
2009-03-16T08:29:47Z
[ "python", "file", "filesystems", "checksum" ]
Directory checksum with python?
649,623
<p>So I'm in the middle of web-based filesystem abstraction layer development. Just like file browser, except it has some extra features like freaky permissions etc. </p> <p>I would like users to be notified somehow about directory changes. So, i.e. when someone uploads a new file via FTP, certain users should get a proper message. It is not required for the message to be extra detailed, I don't really need to show the exact resource changed. The parent directory name should be enough.</p> <p>What approach would you recommend?</p>
3
2009-03-16T08:22:52Z
649,665
<p>A simple approach would be to monitor/check the last modification date of the working directory (using os.stat() for example). </p> <p>Whenever a file in a directory is modified, the working directory's (the directory the file is in) last modification date changes as well.</p> <p>At least this works on the filesystems I am working on (ufs, ext3). I'm not sure if all filesystems do it this way.</p>
0
2009-03-16T08:47:34Z
[ "python", "file", "filesystems", "checksum" ]
Do Python lists have an equivalent to dict.get?
650,340
<p>I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?</p> <pre><code>if 13 in intList: i = intList.index(13) </code></pre> <p>In the case of dictionaries, there's a <code>get</code> function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?</p>
7
2009-03-16T13:04:46Z
650,350
<p>You answered it yourself, with the <code>index()</code> method. That will throw an exception if the index is not found, so just catch that:</p> <pre><code>def getIndexOrMinusOne(a, x): try: return a.index(x) except ValueError: return -1 </code></pre>
12
2009-03-16T13:07:46Z
[ "python", "list" ]
Do Python lists have an equivalent to dict.get?
650,340
<p>I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?</p> <pre><code>if 13 in intList: i = intList.index(13) </code></pre> <p>In the case of dictionaries, there's a <code>get</code> function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?</p>
7
2009-03-16T13:04:46Z
650,359
<p>It looks like you'll just have to catch the exception...</p> <pre><code>try: i = intList.index(13) except ValueError: i = some_default_value </code></pre>
7
2009-03-16T13:10:07Z
[ "python", "list" ]
Do Python lists have an equivalent to dict.get?
650,340
<p>I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?</p> <pre><code>if 13 in intList: i = intList.index(13) </code></pre> <p>In the case of dictionaries, there's a <code>get</code> function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?</p>
7
2009-03-16T13:04:46Z
650,364
<p>Just put what you got in a function and use it:) </p> <p>You can either use <code>if i in list: return list.index(i)</code> or the <code>try/except</code>, depending on your preferences.</p>
-1
2009-03-16T13:11:07Z
[ "python", "list" ]
Do Python lists have an equivalent to dict.get?
650,340
<p>I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?</p> <pre><code>if 13 in intList: i = intList.index(13) </code></pre> <p>In the case of dictionaries, there's a <code>get</code> function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?</p>
7
2009-03-16T13:04:46Z
650,368
<p>No, there isn't a direct match for what you asked for. There was <strong><a href="http://mail.python.org/pipermail/python-dev/2006-July/067263.html" rel="nofollow">a discussion a while back</a></strong> on the Python mailing list about this, and people reached the conclusion that it was probably a code smell if you needed this. Consider using a <em>dict</em> or <em>set</em> instead if you need to test membership that way.</p>
3
2009-03-16T13:12:22Z
[ "python", "list" ]
Do Python lists have an equivalent to dict.get?
650,340
<p>I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?</p> <pre><code>if 13 in intList: i = intList.index(13) </code></pre> <p>In the case of dictionaries, there's a <code>get</code> function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?</p>
7
2009-03-16T13:04:46Z
650,373
<p>You can catch the ValueError exception, or you can do:</p> <pre><code>i = intList.index(13) if 13 in intList else -1 </code></pre> <p>(Python 2.5+)</p> <p>BTW. if you're going to do a big batch of similar operations, you might consider building inverse dictionary value -> index.</p> <pre><code>intList = [13,1,2,3,13,5,13] indexDict = defaultdict(list) for value, index in zip(intList, range(len(intList))): indexDict[value].append(index) indexDict[13] [0, 4, 6] </code></pre>
2
2009-03-16T13:13:41Z
[ "python", "list" ]
How to make a singleton class with Python Flup fastcgi server?
650,518
<p>I use flup as fastcgi server for Django.</p> <p>Please explain to me how can I use singleton? I'm not sure I understand threading models for Flup well.</p>
1
2009-03-16T13:55:46Z
986,981
<p>If you use a forked server, you will not be able to have a singleton at all (at least no singleton that lifes longer than your actual context).</p> <p>With a threaded server, it should be possibe (but I am not so much in Django and Web servers!).</p> <p>Have you tried such a code (as an additional module):</p> <pre><code># Singleton module _my_singleton = None def getSingleton(): if _my_singleton == None: _my_singleton = ... return _my_singleton </code></pre> <p>At the tree dots ("...") you have to add coding to create your singleton object, of course.</p> <p>This is no productive code yet, but you can use it to check if singletons will work at all with your framework. For singletons are only possible with some kind of "global storage" at hand. Forked servers make this more difficult.</p> <p>In the case, that "normal global storage" does not work, there is a different possibility available. You could store your singleton on the file system, using Pythons serialization facilites. But of course, this would be much more overhead in deed!</p>
0
2009-06-12T14:37:52Z
[ "python", "django", "flup" ]
Rotation based on end points
650,646
<p>I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling. </p> <p>It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing in the right direction.</p>
2
2009-03-16T14:25:00Z
650,668
<p>I would have to look up the exact functions to use, but how about making a right triangle where the hypotenuse is the line in question and the legs are axis-aligned, and using some basic trigonometry to calculate the angle of the line based on the lengths of the sides of the triangle? Of course, you will have to special-case lines that are already axis-aligned, but that should be trivial.</p> <p>Also, <a href="http://en.wikipedia.org/wiki/Slope" rel="nofollow">this Wikipedia article on slope</a> may give you some ideas.</p>
1
2009-03-16T14:29:56Z
[ "python", "geometry", "pygame" ]
Rotation based on end points
650,646
<p>I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling. </p> <p>It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing in the right direction.</p>
2
2009-03-16T14:25:00Z
650,854
<p>We're assuming that 0 degrees means the arrow is pointing to the right, 90 degrees means pointing straight up and 180 degrees means pointing to the left.</p> <p>There are several ways to do this, the simplest is probably using the atan2 function. if your starting point is (x1,y1) and your end point is (x2,y2) then the angle in degrees of the line between the two is:</p> <pre><code>import math deg=math.degrees(math.atan2(y2-y1,x2-x1)) </code></pre> <p>this will you an angle in the range -180 to 180 so you need it from 0 to 360 you have to take care of that your self.</p>
2
2009-03-16T15:14:25Z
[ "python", "geometry", "pygame" ]
Rotation based on end points
650,646
<p>I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling. </p> <p>It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing in the right direction.</p>
2
2009-03-16T14:25:00Z
651,089
<p>Here is the complete code to do it. Note that when using pygame, the y co-ordinate is measured from the top, and so we take the negative when using math functions.</p> <pre><code>import pygame import math import random pygame.init() screen=pygame.display.set_mode((300,300)) screen.fill((255,255,255)) pos1=random.randrange(300), random.randrange(300) pos2=random.randrange(300), random.randrange(300) pygame.draw.line(screen, (0,0,0), pos1, pos2) arrow=pygame.Surface((50,50)) arrow.fill((255,255,255)) pygame.draw.line(arrow, (0,0,0), (0,0), (25,25)) pygame.draw.line(arrow, (0,0,0), (0,50), (25,25)) arrow.set_colorkey((255,255,255)) angle=math.atan2(-(pos1[1]-pos2[1]), pos1[0]-pos2[0]) ##Note that in pygame y=0 represents the top of the screen ##So it is necessary to invert the y coordinate when using math angle=math.degrees(angle) def drawAng(angle, pos): nar=pygame.transform.rotate(arrow,angle) nrect=nar.get_rect(center=pos) screen.blit(nar, nrect) drawAng(angle, pos1) angle+=180 drawAng(angle, pos2) pygame.display.flip() </code></pre>
8
2009-03-16T16:12:37Z
[ "python", "geometry", "pygame" ]
Rotation based on end points
650,646
<p>I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling. </p> <p>It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing in the right direction.</p>
2
2009-03-16T14:25:00Z
656,119
<p>just to append to the above code, you'd probably want an event loop so it wouldn't quit right away:</p> <pre><code>... clock = pygame.time.Clock() running = True while (running): clock.tick() </code></pre>
0
2009-03-17T21:34:41Z
[ "python", "geometry", "pygame" ]
Python, redirecting the stream of Popen to a python function
650,877
<p>I'm new to python programming. I have this problem: I have a list of text files (both compressed and not) and I need to : - connect to the server and open them - after the opening of the file, I need to take his content and pass it to another python function that I wrote</p> <pre><code>def readLogs (fileName): f = open (fileName, 'r') inStream = f.read() counter = 0 inStream = re.split('\n', inStream) # Create a 'list of lines' out = "" # Will contain the output logInConst = "" # log In Construction curLine = "" # Line that I am working on for nextLine in inStream: logInConst += curLine curLine = nextLine # check if it is a start of a new log &amp;&amp; check if the previous log is 'ready' if newLogRegExp.match(curLine) and logInConst != "": counter = counter + 1 out = logInConst logInConst = "" yield out yield logInConst + curLine def checkFile (regExp, fileName): generatore = readLogs(fileName) listOfMatches=[] for i in generatore: #I'm now cycling through the logs # regExp must be a COMPILE regular expression if regExp.search(i): listOfMatches.append(i) return listOfMatches </code></pre> <p>in order to elaborate the info contained in those files. The function has the aim of write in just 1 line the logs that are stored in those files using 3 lines ... The function is working fine on files read from my local machine but I cannot figure out how to connect to a remote server and create these one-line logs without storing the content of each file into a string and then working with the string ... The command that I use to connect to the remote machine is :</p> <pre><code>connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0] </code></pre> <p>retList[0] and retList[2] are the user@remote and the folder name that I have to access</p> <p>Thanks to all in advance !</p> <p><strong>UPDATE:</strong></p> <p>My problem is that I have to establish an ssh connection first :</p> <pre><code>pr1=Popen(['ssh', 'siatc@lgssp101', '*~/PRD/sialt/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0] </code></pre> <p>All the files that I need to open are stored in a list, fileList[], part of them are compressed (.gz) and part are just text files !! I have tried all the procedures that u showed before bot nothing worked ... I think that I mus modify the third argument of the Popen function but I cannot figure out how to do it ! Is there anyone that can help me ???</p>
5
2009-03-16T15:19:11Z
650,994
<p>You do not have to split the stream/file into lines yourself. Just iterate:</p> <pre><code>for ln in f: # work on line in ln </code></pre> <p>This should work equally well for files (using open() for file()) and pipes (using Popen). Use the <code>stdout</code> property of the popen object to access the pipe connected to stdout of the subprocess</p> <p><strong>Example</strong></p> <pre><code>from subprocess import Popen, PIPE pp = Popen('dir', shell=True, stdout=PIPE) for ln in pp.stdout: print '#',ln </code></pre>
5
2009-03-16T15:48:11Z
[ "python", "stream", "subprocess", "yield", "popen" ]
Python, redirecting the stream of Popen to a python function
650,877
<p>I'm new to python programming. I have this problem: I have a list of text files (both compressed and not) and I need to : - connect to the server and open them - after the opening of the file, I need to take his content and pass it to another python function that I wrote</p> <pre><code>def readLogs (fileName): f = open (fileName, 'r') inStream = f.read() counter = 0 inStream = re.split('\n', inStream) # Create a 'list of lines' out = "" # Will contain the output logInConst = "" # log In Construction curLine = "" # Line that I am working on for nextLine in inStream: logInConst += curLine curLine = nextLine # check if it is a start of a new log &amp;&amp; check if the previous log is 'ready' if newLogRegExp.match(curLine) and logInConst != "": counter = counter + 1 out = logInConst logInConst = "" yield out yield logInConst + curLine def checkFile (regExp, fileName): generatore = readLogs(fileName) listOfMatches=[] for i in generatore: #I'm now cycling through the logs # regExp must be a COMPILE regular expression if regExp.search(i): listOfMatches.append(i) return listOfMatches </code></pre> <p>in order to elaborate the info contained in those files. The function has the aim of write in just 1 line the logs that are stored in those files using 3 lines ... The function is working fine on files read from my local machine but I cannot figure out how to connect to a remote server and create these one-line logs without storing the content of each file into a string and then working with the string ... The command that I use to connect to the remote machine is :</p> <pre><code>connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0] </code></pre> <p>retList[0] and retList[2] are the user@remote and the folder name that I have to access</p> <p>Thanks to all in advance !</p> <p><strong>UPDATE:</strong></p> <p>My problem is that I have to establish an ssh connection first :</p> <pre><code>pr1=Popen(['ssh', 'siatc@lgssp101', '*~/PRD/sialt/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0] </code></pre> <p>All the files that I need to open are stored in a list, fileList[], part of them are compressed (.gz) and part are just text files !! I have tried all the procedures that u showed before bot nothing worked ... I think that I mus modify the third argument of the Popen function but I cannot figure out how to do it ! Is there anyone that can help me ???</p>
5
2009-03-16T15:19:11Z
651,221
<p>Remove InStream and just use the file object.</p> <p>So that your code would read:</p> <pre><code>for nextLine in f.readlines(): . . . </code></pre> <p>Ber has it right. </p> <p>To clarify, the default iteration behavior of a file object is to return the next line. so "<strong>for nextLine in f</strong>" will give you the same results as "<strong>for nextLine in f.readlines()</strong>".</p> <p>See the file object documentation for details: <a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects" rel="nofollow">http://docs.python.org/library/stdtypes.html#bltin-file-objects</a></p>
0
2009-03-16T16:45:49Z
[ "python", "stream", "subprocess", "yield", "popen" ]
Python, redirecting the stream of Popen to a python function
650,877
<p>I'm new to python programming. I have this problem: I have a list of text files (both compressed and not) and I need to : - connect to the server and open them - after the opening of the file, I need to take his content and pass it to another python function that I wrote</p> <pre><code>def readLogs (fileName): f = open (fileName, 'r') inStream = f.read() counter = 0 inStream = re.split('\n', inStream) # Create a 'list of lines' out = "" # Will contain the output logInConst = "" # log In Construction curLine = "" # Line that I am working on for nextLine in inStream: logInConst += curLine curLine = nextLine # check if it is a start of a new log &amp;&amp; check if the previous log is 'ready' if newLogRegExp.match(curLine) and logInConst != "": counter = counter + 1 out = logInConst logInConst = "" yield out yield logInConst + curLine def checkFile (regExp, fileName): generatore = readLogs(fileName) listOfMatches=[] for i in generatore: #I'm now cycling through the logs # regExp must be a COMPILE regular expression if regExp.search(i): listOfMatches.append(i) return listOfMatches </code></pre> <p>in order to elaborate the info contained in those files. The function has the aim of write in just 1 line the logs that are stored in those files using 3 lines ... The function is working fine on files read from my local machine but I cannot figure out how to connect to a remote server and create these one-line logs without storing the content of each file into a string and then working with the string ... The command that I use to connect to the remote machine is :</p> <pre><code>connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0] </code></pre> <p>retList[0] and retList[2] are the user@remote and the folder name that I have to access</p> <p>Thanks to all in advance !</p> <p><strong>UPDATE:</strong></p> <p>My problem is that I have to establish an ssh connection first :</p> <pre><code>pr1=Popen(['ssh', 'siatc@lgssp101', '*~/PRD/sialt/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0] </code></pre> <p>All the files that I need to open are stored in a list, fileList[], part of them are compressed (.gz) and part are just text files !! I have tried all the procedures that u showed before bot nothing worked ... I think that I mus modify the third argument of the Popen function but I cannot figure out how to do it ! Is there anyone that can help me ???</p>
5
2009-03-16T15:19:11Z
797,183
<p>If you want to do something via ssh, why not use <a href="http://pyssh.sourceforge.net/" rel="nofollow">the Python SSH module</a>?</p>
0
2009-04-28T10:11:44Z
[ "python", "stream", "subprocess", "yield", "popen" ]
Python, redirecting the stream of Popen to a python function
650,877
<p>I'm new to python programming. I have this problem: I have a list of text files (both compressed and not) and I need to : - connect to the server and open them - after the opening of the file, I need to take his content and pass it to another python function that I wrote</p> <pre><code>def readLogs (fileName): f = open (fileName, 'r') inStream = f.read() counter = 0 inStream = re.split('\n', inStream) # Create a 'list of lines' out = "" # Will contain the output logInConst = "" # log In Construction curLine = "" # Line that I am working on for nextLine in inStream: logInConst += curLine curLine = nextLine # check if it is a start of a new log &amp;&amp; check if the previous log is 'ready' if newLogRegExp.match(curLine) and logInConst != "": counter = counter + 1 out = logInConst logInConst = "" yield out yield logInConst + curLine def checkFile (regExp, fileName): generatore = readLogs(fileName) listOfMatches=[] for i in generatore: #I'm now cycling through the logs # regExp must be a COMPILE regular expression if regExp.search(i): listOfMatches.append(i) return listOfMatches </code></pre> <p>in order to elaborate the info contained in those files. The function has the aim of write in just 1 line the logs that are stored in those files using 3 lines ... The function is working fine on files read from my local machine but I cannot figure out how to connect to a remote server and create these one-line logs without storing the content of each file into a string and then working with the string ... The command that I use to connect to the remote machine is :</p> <pre><code>connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0] </code></pre> <p>retList[0] and retList[2] are the user@remote and the folder name that I have to access</p> <p>Thanks to all in advance !</p> <p><strong>UPDATE:</strong></p> <p>My problem is that I have to establish an ssh connection first :</p> <pre><code>pr1=Popen(['ssh', 'siatc@lgssp101', '*~/PRD/sialt/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0] </code></pre> <p>All the files that I need to open are stored in a list, fileList[], part of them are compressed (.gz) and part are just text files !! I have tried all the procedures that u showed before bot nothing worked ... I think that I mus modify the third argument of the Popen function but I cannot figure out how to do it ! Is there anyone that can help me ???</p>
5
2009-03-16T15:19:11Z
7,638,410
<p>Try this page, best info on popen I have found so far....</p> <p><a href="http://jimmyg.org/blog/2009/working-with-python-subprocess.html" rel="nofollow">http://jimmyg.org/blog/2009/working-with-python-subprocess.html</a></p>
0
2011-10-03T17:20:53Z
[ "python", "stream", "subprocess", "yield", "popen" ]
How do you substitue a Python capture followed by a number character?
650,926
<p>When using <a href="http://docs.python.org/library/re.html" rel="nofollow">re.sub</a>, how to you handle a situation where you need a capture followed by a number in the replacement string? For example, you cannot use "\10" for capture 1 followed by a '0' character because it will be interpreted as capture 10.</p>
2
2009-03-16T15:34:43Z
650,956
<pre><code>\g&lt;1&gt;0 </code></pre> <p><a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow">http://docs.python.org/library/re.html#re.sub</a></p> <blockquote> <p>\g&lt;number> uses the corresponding group number; \g&lt;2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g&lt;2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'.</p> </blockquote>
5
2009-03-16T15:40:27Z
[ "python", "regex", "string" ]
Is it possible, with the Python Standard Library (say version 2.5) to perform MS-SQL queries which are parameterized?
650,979
<p>While the particular data I'm working with right now will not be user-generated, and will be sanitized within an inch of its life during my usual validation routines, I would like to learn how to do your basic INSERT, SELECT, etc. SQL queries while protecting myself against SQL injection attacks, just for future reference. I'd rather learn how to do things the "right" way, through parameterized queries.</p> <p>Sanitization is always nice, but I am pitting my pitiful intellect against that of seasoned hackers. Manually escaping means I am probably overlooking things, since blacklists are not as robust as whitelists. For additional clarification, I do not mean using the <code>(%s)</code> notation to pass as a parameter for building a string possibly named <code>sqlstatement</code>. I think one of the magic words I need to know is "binding."</p> <p>I am also hoping to avoid anything outside of the Python Standard Library.</p> <p>The application in question requires Microsoft SQL 2005, if that is relevant. I am using ActiveState Python and the modules dbi and odbc. Since this is Someone Else's Database, stored procedures are out.</p>
2
2009-03-16T15:44:47Z
651,034
<p><a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP 249 (DB API 2.0)</a> defines 5 paramstyles, <a href="http://pymssql.sourceforge.net/" rel="nofollow">PyMSSQL</a> uses paramstyle == pyformat. But although it looks like string interpolation, <strong>it is actually binding</strong>.</p> <p>Note difference between <strong>binding</strong>:</p> <pre><code>cur.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') </code></pre> <p>and interpolating (this is how it should <strong>NOT</strong> be done):</p> <pre><code>cur.execute('SELECT * FROM persons WHERE salesrep=%s' % 'John Doe') </code></pre> <p>See also <a href="http://wiki.python.org/moin/DbApiFaq" rel="nofollow">http://wiki.python.org/moin/DbApiFaq</a></p> <p><hr /></p> <blockquote> <p>"I am also hoping to avoid anything outside of the Python Standard Library."</p> </blockquote> <p>You're out of luck here. The only RDBMS driver that comes built-in in Python is SQLite. </p>
5
2009-03-16T15:55:32Z
[ "python", "sql", "binding", "parameters", "sql-injection" ]
Is it possible, with the Python Standard Library (say version 2.5) to perform MS-SQL queries which are parameterized?
650,979
<p>While the particular data I'm working with right now will not be user-generated, and will be sanitized within an inch of its life during my usual validation routines, I would like to learn how to do your basic INSERT, SELECT, etc. SQL queries while protecting myself against SQL injection attacks, just for future reference. I'd rather learn how to do things the "right" way, through parameterized queries.</p> <p>Sanitization is always nice, but I am pitting my pitiful intellect against that of seasoned hackers. Manually escaping means I am probably overlooking things, since blacklists are not as robust as whitelists. For additional clarification, I do not mean using the <code>(%s)</code> notation to pass as a parameter for building a string possibly named <code>sqlstatement</code>. I think one of the magic words I need to know is "binding."</p> <p>I am also hoping to avoid anything outside of the Python Standard Library.</p> <p>The application in question requires Microsoft SQL 2005, if that is relevant. I am using ActiveState Python and the modules dbi and odbc. Since this is Someone Else's Database, stored procedures are out.</p>
2
2009-03-16T15:44:47Z
651,194
<p>Try <a href="http://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a></p> <p>But if you want to have things really easy (plus tons of powerful features), take a look at <a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a> (which by the way uses pyodbc as the default "driver" for mssql)</p>
2
2009-03-16T16:37:49Z
[ "python", "sql", "binding", "parameters", "sql-injection" ]
How do I check if it's the homepage in a Plone website using ZPT?
651,009
<p>I want to change my website's header only it if's not the homepage. Is there a <em>tal:condition</em> expression for that?</p> <p>I've been reading <a href="http://plone.org/documentation/tutorial/zpt" rel="nofollow">this</a> and can't find what I'm looking for...</p> <p>thanks!</p>
3
2009-03-16T15:50:22Z
651,703
<p>how about something like <code>&lt;tal:condition="python: request.URLPATH0 == '/index_html'</code> ...>`? see <a href="http://docs.zope.org/zope2/zope2book/source/AppendixC.html#built-in-names" rel="nofollow">TALES Built-in Names</a> and the <a href="http://www.zope.org/Documentation/Books/ZopeBook/2%5F6Edition/AppendixB.stx" rel="nofollow">Zope API Reference</a> for more choices.</p>
0
2009-03-16T18:56:57Z
[ "python", "plone", "zope", "template-tal", "zpt" ]
How do I check if it's the homepage in a Plone website using ZPT?
651,009
<p>I want to change my website's header only it if's not the homepage. Is there a <em>tal:condition</em> expression for that?</p> <p>I've been reading <a href="http://plone.org/documentation/tutorial/zpt" rel="nofollow">this</a> and can't find what I'm looking for...</p> <p>thanks!</p>
3
2009-03-16T15:50:22Z
1,509,184
<p>I use something similar to ax:</p> <pre><code>&lt;tal:block define="global currentUrl request/getURL" condition="python: u'home' not in str(currentUrl)"&gt; &lt;!-- whatever --&gt; &lt;/tal:block&gt; </code></pre>
1
2009-10-02T12:15:07Z
[ "python", "plone", "zope", "template-tal", "zpt" ]
How do I check if it's the homepage in a Plone website using ZPT?
651,009
<p>I want to change my website's header only it if's not the homepage. Is there a <em>tal:condition</em> expression for that?</p> <p>I've been reading <a href="http://plone.org/documentation/tutorial/zpt" rel="nofollow">this</a> and can't find what I'm looking for...</p> <p>thanks!</p>
3
2009-03-16T15:50:22Z
1,693,676
<p>The best way is to use two really handy plone views that are intended just for this purpose. The interface that defines them is at <a href="https://svn.plone.org/svn/plone/plone.app.layout/trunk/plone/app/layout/globals/interfaces.py">https://svn.plone.org/svn/plone/plone.app.layout/trunk/plone/app/layout/globals/interfaces.py</a>, in case you want to check it out.</p> <pre><code>&lt;tal:block tal:define="our_url context/@@plone_context_state/canonical_object_url; home_url context/@@plone_portal_state/portal_url;" tal:condition="python:our_url == home_url"&gt; HERE GOES YOUR STUFF &lt;/tal:block&gt; </code></pre> <p>The great thing about @@plone_context_state and @@plone_portal_state is that they handle all sorts of weird edge cases. context/@@plone_context_state/canonical_object_url also returns the right, most basic, object's url even when you're viewing the default page in the portal root with a query string appended :-)</p>
6
2009-11-07T16:54:04Z
[ "python", "plone", "zope", "template-tal", "zpt" ]
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
<p>One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized. I suspect the answer is not a simple yes-or-no but I am not sure, so I am asking the question here on StackOverflow. </p>
16
2009-03-16T16:00:10Z
651,078
<p>C/C++ extensions to Python are not bound by the GIL. However, you really need to know what you're doing. <a href="http://docs.python.org/c-api/init.html">From <a href="http://docs.python.org/c-api/init.html">http://docs.python.org/c-api/init.html</a></a>:</p> <blockquote> <p>The global interpreter lock is used to protect the pointer to the current thread state. When releasing the lock and saving the thread state, the current thread state pointer must be retrieved before the lock is released (since another thread could immediately acquire the lock and store its own thread state in the global variable). Conversely, when acquiring the lock and restoring the thread state, the lock must be acquired before storing the thread state pointer.</p> <p>Why am I going on with so much detail about this? Because when threads are created from C, they don’t have the global interpreter lock, nor is there a thread state data structure for them. Such threads must bootstrap themselves into existence, by first creating a thread state data structure, then acquiring the lock, and finally storing their thread state pointer, before they can start using the Python/C API. When they are done, they should reset the thread state pointer, release the lock, and finally free their thread state data structure.</p> </blockquote>
7
2009-03-16T16:08:21Z
[ "c++", "python", "c", "multithreading" ]
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
<p>One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized. I suspect the answer is not a simple yes-or-no but I am not sure, so I am asking the question here on StackOverflow. </p>
16
2009-03-16T16:00:10Z
651,238
<p>Yes, calls to C extensions (C routines called from Python) are still subject to the GIL.</p> <p>However, you can <em>manually</em> release the GIL inside your C extension, so long as you are careful to re-assert it before returning control to the Python VM.</p> <p>For information, take a look at the <code>Py_BEGIN_ALLOW_THREADS</code> and <code>Py_END_ALLOW_THREADS</code> macros: <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock">http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock</a></p>
15
2009-03-16T16:51:08Z
[ "c++", "python", "c", "multithreading" ]
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
<p>One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized. I suspect the answer is not a simple yes-or-no but I am not sure, so I am asking the question here on StackOverflow. </p>
16
2009-03-16T16:00:10Z
652,452
<p>Here's a long article I wrote for python magazine that touches on the c-extension/GIL/threading thing. It's a bit long at 4000 words, but it should help.</p> <p><a href="http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/">http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/</a></p>
7
2009-03-16T22:56:36Z
[ "c++", "python", "c", "multithreading" ]
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
<p>One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized. I suspect the answer is not a simple yes-or-no but I am not sure, so I am asking the question here on StackOverflow. </p>
16
2009-03-16T16:00:10Z
733,143
<p>Check out Cython, it has similar syntax to Python but with a few constructs like "cdef", fast numpy access functions, and a "with nogil" statement (which does what it says).</p>
0
2009-04-09T07:17:20Z
[ "c++", "python", "c", "multithreading" ]
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
<p>One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized. I suspect the answer is not a simple yes-or-no but I am not sure, so I am asking the question here on StackOverflow. </p>
16
2009-03-16T16:00:10Z
36,491,019
<p>If you’re writing your extension in C++, you can use RAII to easily and legibly write code manipulating the GIL. I use this pair of RAII structlets:</p> <pre class="lang-cpp prettyprint-override"><code>namespace py { namespace gil { struct release { PyThreadState* state; bool active; release() :state(PyEval_SaveThread()), active(true) {} ~release() { if (active) { restore(); } } void restore() { PyEval_RestoreThread(state); active = false; } }; struct ensure { PyGILState_STATE* state; bool active; ensure() :state(PyGILState_Ensure()), active(true) {} ~ensure() { if (active) { restore(); } } void restore() { PyGILState_Release(state); active = false; } }; } } </code></pre> <p>… allowing the GIL to be toggled for a given block (in a semantic manner that may seem dimly familiar for any context-manager Pythonista fans):</p> <pre class="lang-cpp prettyprint-override"><code>PyObject* YourPythonExtensionFunction(PyObject* self, PyObject* args) { Py_SomeCAPICall(…); /// generally, if it starts with Py* it needs the GIL Py_SomeOtherCall(…); /// ... there are exceptions, see the docs { py::gil::release nogil; std::cout &lt;&lt; "Faster and less block-y I/O" &lt;&lt; std::endl &lt;&lt; "can run inside this block -" &lt;&lt; std::endl &lt;&lt; "unimpeded by the GIL"; } Py_EvenMoreAPICallsForWhichTheGILMustBeInPlace(…); } </code></pre> <p>… Indeed, personally also I find the ease of extending Python, and the level of control one has over the internal structures and state, a killer feature.</p>
0
2016-04-08T03:29:57Z
[ "c++", "python", "c", "multithreading" ]
A simple Python IRC client library that supports SSL?
651,053
<p>A simple Python IRC client library that supports SSL?</p>
5
2009-03-16T16:01:01Z
651,086
<p><a href="http://twistedmatrix.com/trac/wiki/TwistedWords">Twisted</a> has an IRC client (in twisted.words), and it supports SSL.</p> <p>There is an <a href="http://twistedmatrix.com/projects/words/documentation/examples/ircLogBot.py">example in the documentation</a>, just remember to do <code>reactor.connectSSL</code> instead of <code>reactor.connectTCP</code>.</p> <p>If you don't want Twisted, there is also the <a href="http://python-irclib.sourceforge.net/">Python IRC library</a>, which I notice has SSL support in the latest release.</p>
14
2009-03-16T16:12:07Z
[ "python", "irc" ]
A simple Python IRC client library that supports SSL?
651,053
<p>A simple Python IRC client library that supports SSL?</p>
5
2009-03-16T16:01:01Z
651,102
<p>How simple? Chatzilla supports SSL and as any Mozilla Platform applications, allows using Python. https://developer.mozilla.org/En/Python </p> <p>On second thought, that probably is a total overkill. A second on Ali's answer, Twisted will do.</p>
0
2009-03-16T16:15:58Z
[ "python", "irc" ]
A simple Python IRC client library that supports SSL?
651,053
<p>A simple Python IRC client library that supports SSL?</p>
5
2009-03-16T16:01:01Z
23,968,810
<p>irc3 support ssl (via asyncio) <a href="https://irc3.readthedocs.org/" rel="nofollow">https://irc3.readthedocs.org/</a></p>
0
2014-05-31T10:16:41Z
[ "python", "irc" ]
Trappings MySQL Warnings on Calls Wrapped in Classes -- Python
651,358
<p>I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes.</p> <p>I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. These seem to run queries properly, but the MySQL warnings they generate are not caught as exceptions in a try/else block. Why don't the try/else blocks catch the warnings? How would I revise the classes or method calls to catch the warnings?</p> <p>Also, I've looked through the prominent sources and can't find a discussion that helps me understand this. I'd appreciate any reference that explains this.</p> <p>Please see code below. Apologies for verbosity, I'm newbie.</p> <pre><code>#!/usr/bin/python import MySQLdb import sys import copy sys.path.append('../../config') import credentials as c # local module with dbase connection credentials #============================================================================= # CLASSES #------------------------------------------------------------------------ class dbMySQL_Connection: def __init__(self, db_server, db_user, db_passwd): self.conn = MySQLdb.connect(db_server, db_user, db_passwd) def getCursor(self, dict_flag=True): self.dbMySQL_Cursor = dbMySQL_Cursor(self.conn, dict_flag) return self.dbMySQL_Cursor def runQuery(self, qryStr, dict_flag=True): qry_res = runQueryNoCursor(qryStr=qryStr, \ conn=self, \ dict_flag=dict_flag) return qry_res #------------------------------------------------------------------------ class dbMySQL_Cursor: def __init__(self, conn, dict_flag=True): if dict_flag: dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor) else: dbMySQL_Cursor = conn.cursor() self.dbMySQL_Cursor = dbMySQL_Cursor def closeCursor(self): self.dbMySQL_Cursor.close() #============================================================================= # QUERY FUNCTIONS #------------------------------------------------------------------------------ def runQueryNoCursor(qryStr, conn, dict_flag=True): dbMySQL_Cursor = conn.getCursor(dict_flag) qry_res =runQueryFnc(qryStr, dbMySQL_Cursor.dbMySQL_Cursor) dbMySQL_Cursor.closeCursor() return qry_res #------------------------------------------------------------------------------ def runQueryFnc(qryStr, dbMySQL_Cursor): qry_res = {} qry_res['rows'] = dbMySQL_Cursor.execute(qryStr) qry_res['result'] = copy.deepcopy(dbMySQL_Cursor.fetchall()) qry_res['messages'] = copy.deepcopy(dbMySQL_Cursor.messages) qry_res['query_str'] = qryStr return qry_res #============================================================================= # USAGES qry = 'DROP DATABASE IF EXISTS database_of_armaments' dbConn = dbMySQL_Connection(**c.creds) def dbConnRunQuery(): # Does not trap an exception; warning displayed to standard error. try: dbConn.runQuery(qry) except: print "dbConn.runQuery() caught an exception." def dbConnCursorExecute(): # Does not trap an exception; warning displayed to standard error. dbConn.getCursor() # try/except block does catches error without this try: dbConn.dbMySQL_Cursor.dbMySQL_Cursor.execute(qry) except Exception, e: print "dbConn.dbMySQL_Cursor.execute() caught an exception." print repr(e) def funcRunQueryNoCursor(): # Does not trap an exception; no warning displayed try: res = runQueryNoCursor(qry, dbConn) print 'Try worked. %s' % res except Exception, e: print "funcRunQueryNoCursor() caught an exception." print repr(e) #============================================================================= if __name__ == '__main__': print '\n' print 'EXAMPLE -- dbConnRunQuery()' dbConnRunQuery() print '\n' print 'EXAMPLE -- dbConnCursorExecute()' dbConnCursorExecute() print '\n' print 'EXAMPLE -- funcRunQueryNoCursor()' funcRunQueryNoCursor() print '\n' </code></pre>
-1
2009-03-16T17:26:59Z
1,219,572
<p>On first glance at least one problem:</p> <pre><code> if dict_flag: dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor) </code></pre> <p>shouldn't that be</p> <pre><code> if dict_flag: self.dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor) </code></pre> <p>You're mixing your self/not self. Also I would wrap the </p> <pre><code>self.conn = MySQLdb.connect(db_server, db_user, db_passwd) </code></pre> <p>in a try/except block since I have a suspicion you may not be creating the database connection properly due to the import of db credentials (I'd toss in a print statement to make sure the data is actually being passed). </p>
0
2009-08-02T19:10:42Z
[ "python", "mysql" ]
Bimodal distribution in C or Python
651,421
<p>What's the easiest way to generate random values according to a bimodal distribution in C or Python?</p> <p>I could implement something like the Ziggurat algorithm or a Box-Muller transform, but if there's a ready-to-use library, or a simpler algorithm I don't know about, that'd be better.</p>
2
2009-03-16T17:42:32Z
651,457
<p>Aren't you just picking values either of two modal distributions?</p> <p><a href="http://docs.python.org/library/random.html#random.triangular" rel="nofollow">http://docs.python.org/library/random.html#random.triangular</a></p> <p>Sounds like you just toggle back and forth between two sets of parameters for your call to triangular.</p> <pre><code>def bimodal( low1, high1, mode1, low2, high2, mode2 ): toss = random.choice( (1, 2) ) if toss == 1: return random.triangular( low1, high1, mode1 ) else: return random.triangular( low2, high2, mode2 ) </code></pre> <p>This may do everything you need.</p>
4
2009-03-16T17:49:31Z
[ "python", "c", "random" ]
Bimodal distribution in C or Python
651,421
<p>What's the easiest way to generate random values according to a bimodal distribution in C or Python?</p> <p>I could implement something like the Ziggurat algorithm or a Box-Muller transform, but if there's a ready-to-use library, or a simpler algorithm I don't know about, that'd be better.</p>
2
2009-03-16T17:42:32Z
651,475
<p>There's always the old-fashioned straight-forward <a href="http://en.wikipedia.org/wiki/Rejection%5Fsampling" rel="nofollow">accept-reject algorithm</a>. If it was good enough for Johnny von Neumann it should be good enough for you ;-).</p>
2
2009-03-16T17:53:19Z
[ "python", "c", "random" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
651,764
<p>I've updated my macbook running leopard to python 2.6 and haven't had any problems with psycopg2. For that matter, I haven't had any compatibility issues anywhere with 2.6, but obviously switching to python3k isn't exactly recommended if you're concerned about backwards compatibility.</p>
1
2009-03-16T19:12:20Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
651,768
<p>You can install them side-by-side. If you've encounter problems just set python 2.5 as the standard python and use e.g. <code>python26</code> for a newer version.</p>
4
2009-03-16T19:14:10Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
651,832
<p>Read this</p> <p><a href="http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/" rel="nofollow">http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/</a></p>
3
2009-03-16T19:31:46Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
651,835
<p>I would stick with the MacPython version 2.5.x (I believe 2.5.4 currently). Here's my rationale:</p> <ol> <li>Snow Leopard may still be on the 2.5 series, so you might as well be consistent with the future OS (i.e. no point in going too far ahead).</li> <li>For most production apps, nobody is going to want to use 2.6 for another year.</li> <li>No frameworks/programs are going to leave 2.5 behind for at least 2 years.</li> </ol> <p>In other words, my approach is that the only reason to do 2.6 is for fun. If you're looking to have fun, just go for 3.0.</p>
1
2009-03-16T19:32:28Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
651,850
<p>I still use macports python25, because so many other packages depend on it, and have not updated to use python26.</p> <pre><code>$ port dependents python25 gnome-doc-utils depends on python25 mod_python25 depends on python25 postgresql83 depends on python25 gtk-doc depends on python25 at-spi depends on python25 gnome-desktop depends on python25 mercurial depends on python25 </code></pre> <p>And that's excluding the <code>py25-*</code> packages I have installed.</p>
3
2009-03-16T19:36:50Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
651,988
<p>I use both Twisted and Psycopg2 extensively on OSX, and both work fine with Python 2.6. Neither has been ported to Python 3.0, as far as I know.</p> <p>Several of Python 3.0's features have been back-ported to 2.6, so you gain quite a bit by moving from 2.5 to 2.6. But I wouldn't switch to 3.0 until all of your thirdparty libraries support it; and this may not happen for some time.</p>
1
2009-03-16T20:14:26Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to be working without a problem.</p> <p>Can anyone give some guidelines for what version I should choose, based on experience? </p> <p>Edit:</p> <p>Ok I've decided to go without reinstalling the os. Hacked around to clean up the bad PostgresPlus installation and installed another one. The official python 2.6.1 package works great, no problem installing it alongside 2.5.2. Psycopg2 works. But as expected PIL wont compile. </p> <p>I guess I'll be switching between the 2.5 from macports and the official 2.6 for different tasks, since I know the macports python has it's issues with some packages.</p> <p>Another Edit:</p> <p>I've now compiled PIL. Had to hide the whole macports directory and half the xcode libraries, so it would find the right ones. It wouldn't accept the paths I was feeding it. PIL is notorious for this on leopard.</p>
2
2009-03-16T19:00:09Z
652,441
<p>I wrote something today on this very subject, my recommendation? Run multiple version, and slap virtualenv down to compartmentalize things.</p> <p><a href="http://jessenoller.com/2009/03/16/so-you-want-to-use-python-on-the-mac/" rel="nofollow">http://jessenoller.com/2009/03/16/so-you-want-to-use-python-on-the-mac/</a></p> <p>I also wouldn't both with macports. I don't see a need for it.</p>
2
2009-03-16T22:50:30Z
[ "python", "osx" ]