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 |
|---|---|---|---|---|---|---|---|---|---|
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 904,532 | <p>The itemgetter operator can help too, if you like map-reduce style python, rather than list comprehensions, for a little variety!</p>
<pre><code># tested in 2.4
from operator import itemgetter
def column(matrix,i):
f = itemgetter(i)
return map(f,matrix)
M = [range(x,x+5) for x in range(10)]
assert column(M,1) == range(1,11)
</code></pre>
| 8 | 2009-05-24T19:57:39Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 7,578,114 | <pre><code>>>> import numpy as np
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> A
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> A[:,2] # returns the third columm
array([3, 7])
</code></pre>
<p>See also: "numpy.arange" and "reshape" to allocate memory</p>
<p>Example: (Allocating a array with shaping of matrix (3x4))</p>
<pre><code>nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
</code></pre>
| 76 | 2011-09-28T03:55:53Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 7,766,288 | <p>If you have an array like </p>
<pre><code>a = [[1, 2], [2, 3], [3, 4]]
</code></pre>
<p>Then you extract the first column like that:</p>
<pre><code>[row[0] for row in a]
</code></pre>
<p>So the result looks like this:</p>
<pre><code>[1, 2, 3]
</code></pre>
| 32 | 2011-10-14T10:21:58Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 13,518,274 | <p>check it out!</p>
<pre><code>a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
</code></pre>
<p>it is the same thing as above except somehow it is neater
the zip does the work but requires single arrays as arguments, the *a syntax unpacks the multidimensional array into single array arguments</p>
| 17 | 2012-11-22T18:25:45Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 18,545,262 | <p>Despite using <code>zip(*iterable)</code> to transpose a nested list, you can also use the following if the nested lists vary in length:</p>
<pre><code>map(None, *[(1,2,3,), (4,5,), (6,)])
</code></pre>
<p>results in:</p>
<pre><code>[(1, 4, 6), (2, 5, None), (3, None, None)]
</code></pre>
<p>The first column is thus:</p>
<pre><code>map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)
</code></pre>
| 1 | 2013-08-31T06:30:42Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 18,594,945 | <p>Well a 'bit' late ...</p>
<p>In case performance matters and your data is shaped rectangular, you might also store it in one dimension and access the columns by regular slicing e.g. ...</p>
<pre><code>A = [[1,2,3,4],[5,6,7,8]] #< assume this 4x2-matrix
B = reduce( operator.add, A ) #< get it one-dimensional
def column1d( matrix, dimX, colIdx ):
return matrix[colIdx::dimX]
def row1d( matrix, dimX, rowIdx ):
return matrix[rowIdx:rowIdx+dimX]
>>> column1d( B, 4, 1 )
[2, 6]
>>> row1d( B, 4, 1 )
[2, 3, 4, 5]
</code></pre>
<p>The neat thing is this is really fast. <strong>However</strong>, negative indexes don't work here! So you can't access the last column or row by index -1.</p>
<p>If you need negative indexing you can tune the accessor-functions a bit, e.g.</p>
<pre><code>def column1d( matrix, dimX, colIdx ):
return matrix[colIdx % dimX::dimX]
def row1d( matrix, dimX, dimY, rowIdx ):
rowIdx = (rowIdx % dimY) * dimX
return matrix[rowIdx:rowIdx+dimX]
</code></pre>
| 2 | 2013-09-03T14:33:28Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 19,592,994 | <p>One more way using matrices</p>
<pre><code>>>> from numpy import matrix
>>> a = [ [1,2,3],[4,5,6],[7,8,9] ]
>>> matrix(a).transpose()[1].getA()[0]
array([2, 5, 8])
>>> matrix(a).transpose()[0].getA()[0]
array([1, 4, 7])
</code></pre>
| 3 | 2013-10-25T14:47:27Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 23,232,138 | <pre><code>[matrix[i][column] for i in range(len(matrix))]
</code></pre>
| 3 | 2014-04-22T23:31:11Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 23,348,016 | <p>All columns from a matrix into a new list:</p>
<pre><code>N = len(matrix)
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
</code></pre>
| 0 | 2014-04-28T17:57:50Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 28,364,590 | <p>You can use this as well:</p>
<pre><code>values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]
</code></pre>
<p>Note: This is not working for built-in array and not aligned (e.g. np.array([[1,2,3],[4,5,6,7]]) )</p>
| 3 | 2015-02-06T11:18:11Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
How do you extract a column from a multi-dimensional array? | 903,853 | <p>Does anybody know how to extract a column from a multi-dimensional array in Python?</p>
| 80 | 2009-05-24T14:19:47Z | 29,165,287 | <p>I think you want to extract a column from an array such as an array below</p>
<pre><code>import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
</code></pre>
<p>Now if you want to get the third column in the format</p>
<pre><code>D=array[[3],
[7],
[11]]
</code></pre>
<p>Then you need to first make the array a matrix</p>
<pre><code>B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
</code></pre>
<p>And now you can do element wise calculations much like you would do in excel.</p>
| 1 | 2015-03-20T11:18:47Z | [
"python",
"arrays",
"multidimensional-array",
"extraction"
] |
Python: Sending a large dictionary to a server | 903,885 | <p>I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys.</p>
<p>The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments.</p>
<p>In addition to the actual data, some data related to authentication (id, password..) should be transmitted. One approach would be to simply urlencode a large dictionary containing all this and send it in a request to the server.</p>
<pre><code>urllib2.urlencode(dataPlusId)
</code></pre>
<p>But actually, the method doing the authentication and accepting the data set does not have to know much about the data. The data could be transmitted and accepted transparently and handed over to another method working with the data.</p>
<p>So my question is: What is the best way to transmit a large dictionary of data to a server in general? And, in this specific case, what is the best way to deal with authentication here?</p>
| 0 | 2009-05-24T14:30:59Z | 903,941 | <p>I think the best way is to encode your data in an appropriate transfer format (you should not use pickle, as it's not save, but it can be binary) and transfer it as a <a href="http://code.activestate.com/recipes/146306/" rel="nofollow">multipart post request</a></p>
<p>What I do not know if you can make it work with repoze.who. If it does not support sign in and function call in one step, you'll perhaps have to verify the credentials yourself.</p>
<p>If you can wrap your data in xml you could also use <a href="http://turbogears.org/2.0/docs/modules/pylons/controllers%5Fxmlrpc.html" rel="nofollow">XML-RPC</a>.</p>
| 3 | 2009-05-24T14:58:50Z | [
"python",
"turbogears"
] |
Python: Sending a large dictionary to a server | 903,885 | <p>I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys.</p>
<p>The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments.</p>
<p>In addition to the actual data, some data related to authentication (id, password..) should be transmitted. One approach would be to simply urlencode a large dictionary containing all this and send it in a request to the server.</p>
<pre><code>urllib2.urlencode(dataPlusId)
</code></pre>
<p>But actually, the method doing the authentication and accepting the data set does not have to know much about the data. The data could be transmitted and accepted transparently and handed over to another method working with the data.</p>
<p>So my question is: What is the best way to transmit a large dictionary of data to a server in general? And, in this specific case, what is the best way to deal with authentication here?</p>
| 0 | 2009-05-24T14:30:59Z | 903,942 | <p>Why don't you serialize the dictionary to a file, and upload the file? This way, the server can read the object back into a dictionary .</p>
| 2 | 2009-05-24T14:59:06Z | [
"python",
"turbogears"
] |
Python: Sending a large dictionary to a server | 903,885 | <p>I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys.</p>
<p>The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments.</p>
<p>In addition to the actual data, some data related to authentication (id, password..) should be transmitted. One approach would be to simply urlencode a large dictionary containing all this and send it in a request to the server.</p>
<pre><code>urllib2.urlencode(dataPlusId)
</code></pre>
<p>But actually, the method doing the authentication and accepting the data set does not have to know much about the data. The data could be transmitted and accepted transparently and handed over to another method working with the data.</p>
<p>So my question is: What is the best way to transmit a large dictionary of data to a server in general? And, in this specific case, what is the best way to deal with authentication here?</p>
| 0 | 2009-05-24T14:30:59Z | 903,950 | <p>Have you tried using pickle on the data ?</p>
| 1 | 2009-05-24T15:02:18Z | [
"python",
"turbogears"
] |
Python: Sending a large dictionary to a server | 903,885 | <p>I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys.</p>
<p>The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments.</p>
<p>In addition to the actual data, some data related to authentication (id, password..) should be transmitted. One approach would be to simply urlencode a large dictionary containing all this and send it in a request to the server.</p>
<pre><code>urllib2.urlencode(dataPlusId)
</code></pre>
<p>But actually, the method doing the authentication and accepting the data set does not have to know much about the data. The data could be transmitted and accepted transparently and handed over to another method working with the data.</p>
<p>So my question is: What is the best way to transmit a large dictionary of data to a server in general? And, in this specific case, what is the best way to deal with authentication here?</p>
| 0 | 2009-05-24T14:30:59Z | 903,958 | <p>Do a POST of your python data (use binary as suggested in other answers) and handle security using your webserver. Apache and Microsoft servers can both do authentication using a wide variety of methods (SSL client certs, Password, System accounts, etc...)</p>
<p>Serialising/Deserialising to text or XML is probably overkill if you're just going to turn it back to dictionary again).</p>
| 2 | 2009-05-24T15:09:32Z | [
"python",
"turbogears"
] |
Python: Sending a large dictionary to a server | 903,885 | <p>I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys.</p>
<p>The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments.</p>
<p>In addition to the actual data, some data related to authentication (id, password..) should be transmitted. One approach would be to simply urlencode a large dictionary containing all this and send it in a request to the server.</p>
<pre><code>urllib2.urlencode(dataPlusId)
</code></pre>
<p>But actually, the method doing the authentication and accepting the data set does not have to know much about the data. The data could be transmitted and accepted transparently and handed over to another method working with the data.</p>
<p>So my question is: What is the best way to transmit a large dictionary of data to a server in general? And, in this specific case, what is the best way to deal with authentication here?</p>
| 0 | 2009-05-24T14:30:59Z | 904,009 | <p>I agree with all the answers about avoiding pickle, if safety is a concern (it might not be if the sender gets authenticated before the data's unpickled -- but, when security's at issue, two levels of defense may be better than one); JSON is often of help in such cases (or, XML, if nothing else will do...!-).</p>
<p>Authentication should ideally be left to the webserver, as SpliFF recommends, and SSL (i.e. HTTPS) is generally good for that. If that's unfeasible, but it's feasible to let client and server share a "secret", then sending the serialized string in encrypted form may be best.</p>
| 4 | 2009-05-24T15:35:24Z | [
"python",
"turbogears"
] |
Python: Sending a large dictionary to a server | 903,885 | <p>I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys.</p>
<p>The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments.</p>
<p>In addition to the actual data, some data related to authentication (id, password..) should be transmitted. One approach would be to simply urlencode a large dictionary containing all this and send it in a request to the server.</p>
<pre><code>urllib2.urlencode(dataPlusId)
</code></pre>
<p>But actually, the method doing the authentication and accepting the data set does not have to know much about the data. The data could be transmitted and accepted transparently and handed over to another method working with the data.</p>
<p>So my question is: What is the best way to transmit a large dictionary of data to a server in general? And, in this specific case, what is the best way to deal with authentication here?</p>
| 0 | 2009-05-24T14:30:59Z | 904,304 | <p>I'd personally use SimpleJSON at both ends and just post the "file" (it would really just be a stream) over as multipart data.</p>
<p>But that's me. There are other options.</p>
| 2 | 2009-05-24T17:52:59Z | [
"python",
"turbogears"
] |
Chain-calling parent constructors in python | 904,036 | <p>Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code.</p>
<pre><code>class A(object):
def __init__(self):
print "Constructor A was called"
class B(A):
def __init__(self):
super(B,self).__init__()
print "Constructor B was called"
class C(B):
def __init__(self):
super(C,self).__init__()
print "Constructor C was called"
c = C()
</code></pre>
<p>This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.</p>
<p>Now, I've tried using <code>self.__class__</code> as a first argument to super(), but, obviously it doesn't work - if you put it in the constructor for C - fair enough, B's constructor gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's constructor again (this ends in an infinite recursion).</p>
<p>There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.</p>
| 211 | 2009-05-24T15:54:09Z | 904,078 | <p>The way you are doing it is indeed the recommended one (for Python 2.x). </p>
<p>The issue of whether the class is passed explicitly to <code>super</code> is a matter of style rather than functionality. Passing the class to <code>super</code> fits in with Python's philosophy of "explicit is better than implicit".</p>
| 136 | 2009-05-24T16:12:27Z | [
"python",
"oop",
"inheritance",
"constructor"
] |
Chain-calling parent constructors in python | 904,036 | <p>Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code.</p>
<pre><code>class A(object):
def __init__(self):
print "Constructor A was called"
class B(A):
def __init__(self):
super(B,self).__init__()
print "Constructor B was called"
class C(B):
def __init__(self):
super(C,self).__init__()
print "Constructor C was called"
c = C()
</code></pre>
<p>This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.</p>
<p>Now, I've tried using <code>self.__class__</code> as a first argument to super(), but, obviously it doesn't work - if you put it in the constructor for C - fair enough, B's constructor gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's constructor again (this ends in an infinite recursion).</p>
<p>There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.</p>
| 211 | 2009-05-24T15:54:09Z | 904,081 | <p>Python 3 includes an improved super() which allows use like this:</p>
<pre><code>super().__init__(args)
</code></pre>
| 134 | 2009-05-24T16:13:32Z | [
"python",
"oop",
"inheritance",
"constructor"
] |
Chain-calling parent constructors in python | 904,036 | <p>Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code.</p>
<pre><code>class A(object):
def __init__(self):
print "Constructor A was called"
class B(A):
def __init__(self):
super(B,self).__init__()
print "Constructor B was called"
class C(B):
def __init__(self):
super(C,self).__init__()
print "Constructor C was called"
c = C()
</code></pre>
<p>This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.</p>
<p>Now, I've tried using <code>self.__class__</code> as a first argument to super(), but, obviously it doesn't work - if you put it in the constructor for C - fair enough, B's constructor gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's constructor again (this ends in an infinite recursion).</p>
<p>There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.</p>
| 211 | 2009-05-24T15:54:09Z | 17,398,819 | <p>You can simply write : <br></p>
<pre><code>class A(object):
def __init__(self):
print "Constructor A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Constructor B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Constructor C was called"
</code></pre>
| 12 | 2013-07-01T06:49:56Z | [
"python",
"oop",
"inheritance",
"constructor"
] |
Reading a UTF8 CSV file with Python | 904,041 | <p>I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<a href="http://docs.python.org/library/csv.html">http://docs.python.org/library/csv.html</a>), I came up with the following code to read the CSV file since the csvreader supports only ASCII.</p>
<pre><code>def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for field1, field2, field3 in reader:
...
</code></pre>
<p>Below is an extract of the CSV file I am trying to read:</p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...
</code></pre>
<p>Even though I try to encode/decode to UTF-8, I am still getting the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".\Test.py", line 53, in <module>
for field1, field2, field3 in reader:
File ".\Test.py", line 40, in unicode_csv_reader
for row in csv_reader:
File ".\Test.py", line 46, in utf_8_encoder
yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)
</code></pre>
<p>How do I fix this?</p>
| 50 | 2009-05-24T15:56:31Z | 904,085 | <p>The <code>.encode</code> method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the <code>codecs</code> module in the standard library and <code>codecs.open</code> in particular for better general solutions for reading UTF-8 encoded text files. However, for the <code>csv</code> module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:</p>
<pre><code>import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
print field1, field2, field3
</code></pre>
<p>PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the <code>csv</code> module level), of the form <code>line.decode('whateverweirdcodec').encode('utf-8')</code> -- but probably you can just use the name of your existing encoding in the <code>yield</code> line in my code above, instead of <code>'utf-8'</code>, as <code>csv</code> is actually going to be just fine with ISO-8859-* encoded bytestrings.</p>
| 79 | 2009-05-24T16:14:49Z | [
"python",
"utf-8",
"csv",
"character-encoding"
] |
Reading a UTF8 CSV file with Python | 904,041 | <p>I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<a href="http://docs.python.org/library/csv.html">http://docs.python.org/library/csv.html</a>), I came up with the following code to read the CSV file since the csvreader supports only ASCII.</p>
<pre><code>def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for field1, field2, field3 in reader:
...
</code></pre>
<p>Below is an extract of the CSV file I am trying to read:</p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...
</code></pre>
<p>Even though I try to encode/decode to UTF-8, I am still getting the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".\Test.py", line 53, in <module>
for field1, field2, field3 in reader:
File ".\Test.py", line 40, in unicode_csv_reader
for row in csv_reader:
File ".\Test.py", line 46, in utf_8_encoder
yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)
</code></pre>
<p>How do I fix this?</p>
| 50 | 2009-05-24T15:56:31Z | 904,169 | <p>Looking at the <a href="http://www.unicode.org/charts/PDF/U0080.pdf" rel="nofollow"><code>Latin-1</code> unicode table</a>, I see the character code <code>00E9</code> "<em>LATIN SMALL LETTER E WITH ACUTE</em>". This is the accented character in your sample data. A simple test in <code>Python</code> shows that <code>UTF-8</code> encoding for this character is different from the unicode (almost <code>UTF-16</code>) encoding.</p>
<pre><code>>>> u'\u00e9'
u'\xe9'
>>> u'\u00e9'.encode('utf-8')
'\xc3\xa9'
>>>
</code></pre>
<p>I suggest you try to <code>encode("UTF-8")</code> the unicode data before calling the special <code>unicode_csv_reader()</code>.
Simply reading the data from a file might hide the encoding, so check the actual character values.</p>
| 0 | 2009-05-24T16:54:37Z | [
"python",
"utf-8",
"csv",
"character-encoding"
] |
Reading a UTF8 CSV file with Python | 904,041 | <p>I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<a href="http://docs.python.org/library/csv.html">http://docs.python.org/library/csv.html</a>), I came up with the following code to read the CSV file since the csvreader supports only ASCII.</p>
<pre><code>def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for field1, field2, field3 in reader:
...
</code></pre>
<p>Below is an extract of the CSV file I am trying to read:</p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...
</code></pre>
<p>Even though I try to encode/decode to UTF-8, I am still getting the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".\Test.py", line 53, in <module>
for field1, field2, field3 in reader:
File ".\Test.py", line 40, in unicode_csv_reader
for row in csv_reader:
File ".\Test.py", line 46, in utf_8_encoder
yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)
</code></pre>
<p>How do I fix this?</p>
| 50 | 2009-05-24T15:56:31Z | 904,382 | <p>The link to the help page is the same for python 2.6 and as far as I know there was no change in the csv module since 2.5 (besides bug fixes).
Here is the code that just works without any encoding/decoding (file da.csv contains the same data as the variable <em>data</em>). I assume that your file should be read correctly without any conversions.</p>
<p><strong>test.py:</strong></p>
<pre><code>## -*- coding: utf-8 -*-
#
# NOTE: this first line is important for the version b) read from a string(unicode) variable
#
import csv
data = \
"""0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert"""
# a) read from a file
print 'reading from a file:'
for (f1, f2, f3) in csv.reader(open('da.csv'), dialect=csv.excel):
print (f1, f2, f3)
# b) read from a string(unicode) variable
print 'reading from a list of strings:'
reader = csv.reader(data.split('\n'), dialect=csv.excel)
for (f1, f2, f3) in reader:
print (f1, f2, f3)
</code></pre>
<p><strong>da.csv:</strong></p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
</code></pre>
| 1 | 2009-05-24T18:29:41Z | [
"python",
"utf-8",
"csv",
"character-encoding"
] |
Reading a UTF8 CSV file with Python | 904,041 | <p>I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<a href="http://docs.python.org/library/csv.html">http://docs.python.org/library/csv.html</a>), I came up with the following code to read the CSV file since the csvreader supports only ASCII.</p>
<pre><code>def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for field1, field2, field3 in reader:
...
</code></pre>
<p>Below is an extract of the CSV file I am trying to read:</p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...
</code></pre>
<p>Even though I try to encode/decode to UTF-8, I am still getting the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".\Test.py", line 53, in <module>
for field1, field2, field3 in reader:
File ".\Test.py", line 40, in unicode_csv_reader
for row in csv_reader:
File ".\Test.py", line 46, in utf_8_encoder
yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)
</code></pre>
<p>How do I fix this?</p>
| 50 | 2009-05-24T15:56:31Z | 14,162,262 | <p>Using <strong>codecs.open</strong> as Alex Martelli suggested proved to be usefull to me.</p>
<pre><code>import csv, codecs
delimiter = ';'
reader = codecs.open("your_filename.csv", 'r', encoding='utf-8')
for line in reader:
row = line.split(delimiter)
#do something with your row ...
</code></pre>
| 1 | 2013-01-04T17:53:37Z | [
"python",
"utf-8",
"csv",
"character-encoding"
] |
Reading a UTF8 CSV file with Python | 904,041 | <p>I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<a href="http://docs.python.org/library/csv.html">http://docs.python.org/library/csv.html</a>), I came up with the following code to read the CSV file since the csvreader supports only ASCII.</p>
<pre><code>def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for field1, field2, field3 in reader:
...
</code></pre>
<p>Below is an extract of the CSV file I am trying to read:</p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...
</code></pre>
<p>Even though I try to encode/decode to UTF-8, I am still getting the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".\Test.py", line 53, in <module>
for field1, field2, field3 in reader:
File ".\Test.py", line 40, in unicode_csv_reader
for row in csv_reader:
File ".\Test.py", line 46, in utf_8_encoder
yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)
</code></pre>
<p>How do I fix this?</p>
| 50 | 2009-05-24T15:56:31Z | 14,786,752 | <h3>Python 2.X</h3>
<p>There is a <a href="https://github.com/jdunck/python-unicodecsv">unicode-csv</a> library which should solve your problems, with added benefit of not naving to write any new csv-related code.</p>
<p>Here is a example from their readme:</p>
<pre><code>>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ
</code></pre>
<h3>Python 3.X</h3>
<p>In python 3 this is supported out of the box by the build-in <code>csv</code> module. See this example: </p>
<pre><code>import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
</code></pre>
| 23 | 2013-02-09T09:37:14Z | [
"python",
"utf-8",
"csv",
"character-encoding"
] |
Reading a UTF8 CSV file with Python | 904,041 | <p>I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<a href="http://docs.python.org/library/csv.html">http://docs.python.org/library/csv.html</a>), I came up with the following code to read the CSV file since the csvreader supports only ASCII.</p>
<pre><code>def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
products = []
for field1, field2, field3 in reader:
...
</code></pre>
<p>Below is an extract of the CSV file I am trying to read:</p>
<pre><code>0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert
...
</code></pre>
<p>Even though I try to encode/decode to UTF-8, I am still getting the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".\Test.py", line 53, in <module>
for field1, field2, field3 in reader:
File ".\Test.py", line 40, in unicode_csv_reader
for row in csv_reader:
File ".\Test.py", line 46, in utf_8_encoder
yield line.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 68: ordinal not in range(128)
</code></pre>
<p>How do I fix this?</p>
| 50 | 2009-05-24T15:56:31Z | 24,793,945 | <p>Also checkout the answer in this post:
<a href="http://stackoverflow.com/a/9347871/1338557">http://stackoverflow.com/a/9347871/1338557</a></p>
<p>It suggests use of library called ucsv.py. Short and simple replacement for CSV written to address the encoding problem(utf-8) for Python 2.7. Also provides support for csv.DictReader</p>
<p><strong>Edit</strong>: Adding sample code that I used:</p>
<pre><code>import ucsv as csv
#Read CSV file containing the right tags to produce
fileObj = open('awol_title_strings.csv', 'rb')
dictReader = csv.DictReader(fileObj, fieldnames = ['titles', 'tags'], delimiter = ',', quotechar = '"')
#Build a dictionary from the CSV file-> {<string>:<tags to produce>}
titleStringsDict = dict()
for row in dictReader:
titleStringsDict.update({unicode(row['titles']):unicode(row['tags'])})
</code></pre>
| 1 | 2014-07-17T02:31:28Z | [
"python",
"utf-8",
"csv",
"character-encoding"
] |
python-mysql : How to get interpolated query string? | 904,042 | <p>In diagnosing SQL query problems, it would sometimes be useful to be able to see the query string after parameters are interpolated into it, using MySQLdb's safe interpolation.</p>
<p>Is there a way to get that information from either a MySQL exception object or from the connection object itself?</p>
| 2 | 2009-05-24T15:56:38Z | 904,077 | <p>Use mysql's own ability to log the queries and watch for them.</p>
| 2 | 2009-05-24T16:12:27Z | [
"python",
"mysql"
] |
python-mysql : How to get interpolated query string? | 904,042 | <p>In diagnosing SQL query problems, it would sometimes be useful to be able to see the query string after parameters are interpolated into it, using MySQLdb's safe interpolation.</p>
<p>Is there a way to get that information from either a MySQL exception object or from the connection object itself?</p>
| 2 | 2009-05-24T15:56:38Z | 907,805 | <p>Perhaps You could use the <a href="http://dev.mysql.com/doc/refman/5.1/en/slow-query-log.html" rel="nofollow">slow_query_log</a>?</p>
<p>If You cannot turn on the mysql's internal ability to log all queries, You need to write down all the queries before You execute them... You can store them in an own log-file, or in a table (or in some other system). If that would be the case, and if I were You, I'd create an wrapper for the connection with the logging ability. </p>
| 0 | 2009-05-25T19:31:40Z | [
"python",
"mysql"
] |
The wrong python interpreter is called | 904,170 | <p>I updated my python interpreter, but I think the old one is still called. When I check for the version I get:</p>
<pre><code>$ python -V
Python 3.0.1
</code></pre>
<p>But I believe the old interpreter is still being called. When I run the command:</p>
<pre><code>python myProg.py
</code></pre>
<p>The script runs properly. But when I invoke it with the command</p>
<pre><code>./myProg.py
</code></pre>
<p>I get the error message:</p>
<pre><code>AttributeError: 'str' object has no attribute 'format'
</code></pre>
<p>Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.</p>
<p>Edit: Wow, that was quick. Thanks a lot!</p>
| 9 | 2009-05-24T16:55:25Z | 904,182 | <p>run 'which python' - if this gives a different answer than /usr/bin/python, change #!/usr/bin/python to have that path instead.</p>
| 2 | 2009-05-24T16:59:07Z | [
"python",
"python-3.x"
] |
The wrong python interpreter is called | 904,170 | <p>I updated my python interpreter, but I think the old one is still called. When I check for the version I get:</p>
<pre><code>$ python -V
Python 3.0.1
</code></pre>
<p>But I believe the old interpreter is still being called. When I run the command:</p>
<pre><code>python myProg.py
</code></pre>
<p>The script runs properly. But when I invoke it with the command</p>
<pre><code>./myProg.py
</code></pre>
<p>I get the error message:</p>
<pre><code>AttributeError: 'str' object has no attribute 'format'
</code></pre>
<p>Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.</p>
<p>Edit: Wow, that was quick. Thanks a lot!</p>
| 9 | 2009-05-24T16:55:25Z | 904,183 | <p>Try <code>which python</code>. I will tell you which python interpreter is used in your environment.
If it is not <code>/usr/bin/python</code> like in the script, then your suspicion is confirmed.</p>
| 3 | 2009-05-24T16:59:26Z | [
"python",
"python-3.x"
] |
The wrong python interpreter is called | 904,170 | <p>I updated my python interpreter, but I think the old one is still called. When I check for the version I get:</p>
<pre><code>$ python -V
Python 3.0.1
</code></pre>
<p>But I believe the old interpreter is still being called. When I run the command:</p>
<pre><code>python myProg.py
</code></pre>
<p>The script runs properly. But when I invoke it with the command</p>
<pre><code>./myProg.py
</code></pre>
<p>I get the error message:</p>
<pre><code>AttributeError: 'str' object has no attribute 'format'
</code></pre>
<p>Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.</p>
<p>Edit: Wow, that was quick. Thanks a lot!</p>
| 9 | 2009-05-24T16:55:25Z | 904,185 | <p>According to the first line of the script, <code>#!/usr/bin/python</code>, you are calling the Python interpreter at <code>/usr/bin/python</code> (which is most likely the one that ships with Mac OS X). You have to change that path to the path where you installed your Python 3 interpreter (likely <code>/usr/local/bin/python</code> or <code>/opt/local/bin/python</code>); <em>or</em> you can just change that line to read <code>#!/usr/bin/env python</code>, which will call the <code>python</code> listed first in your <code>PATH</code> variable (which seems to be the newer version you installed).</p>
| 16 | 2009-05-24T16:59:38Z | [
"python",
"python-3.x"
] |
The wrong python interpreter is called | 904,170 | <p>I updated my python interpreter, but I think the old one is still called. When I check for the version I get:</p>
<pre><code>$ python -V
Python 3.0.1
</code></pre>
<p>But I believe the old interpreter is still being called. When I run the command:</p>
<pre><code>python myProg.py
</code></pre>
<p>The script runs properly. But when I invoke it with the command</p>
<pre><code>./myProg.py
</code></pre>
<p>I get the error message:</p>
<pre><code>AttributeError: 'str' object has no attribute 'format'
</code></pre>
<p>Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.</p>
<p>Edit: Wow, that was quick. Thanks a lot!</p>
| 9 | 2009-05-24T16:55:25Z | 904,188 | <p>Firstly, the recommended shebang line is:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>This will make sure the python interpreter that is invoked when you <code>./foo.py</code> is the same interpreter that is invoked when you invoke python from the command line.</p>
<p>From your description, I suspect that if you did:</p>
<pre><code>which python
</code></pre>
<p>It would not give you <code>/usr/bin/python</code>. It would give you something else, which is where the python 3 interpreter lives. You can either modify your shebang line to the above, or replace the path to the python interpreter with the path returned by <code>which</code>.</p>
| 6 | 2009-05-24T17:00:54Z | [
"python",
"python-3.x"
] |
The wrong python interpreter is called | 904,170 | <p>I updated my python interpreter, but I think the old one is still called. When I check for the version I get:</p>
<pre><code>$ python -V
Python 3.0.1
</code></pre>
<p>But I believe the old interpreter is still being called. When I run the command:</p>
<pre><code>python myProg.py
</code></pre>
<p>The script runs properly. But when I invoke it with the command</p>
<pre><code>./myProg.py
</code></pre>
<p>I get the error message:</p>
<pre><code>AttributeError: 'str' object has no attribute 'format'
</code></pre>
<p>Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.</p>
<p>Edit: Wow, that was quick. Thanks a lot!</p>
| 9 | 2009-05-24T16:55:25Z | 904,190 | <p>It's very possibly what you suspect, that the shebang line is calling the older version. Two things you might want to check:</p>
<p>1) what version is the interpreter at /usr/bin/python:</p>
<pre><code>/usr/bin/python -V
</code></pre>
<p>2) where is the python 3 interpreter you installed:</p>
<pre><code>which python
</code></pre>
<p>If you get the correct one from the command line, then replace your shebang line with this:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p><strong>Addendum:</strong> You could also replace the older version of python with a symlink to python 3, but beware that any major OS X updates (ie: 10.5.6 to 10.5.7) will likely break this:</p>
<pre><code>sudo mv /usr/bin/python /usr/bin/python25
sudo ln -s /path/to/python/3/python /usr/bin/python
</code></pre>
| 3 | 2009-05-24T17:01:38Z | [
"python",
"python-3.x"
] |
The wrong python interpreter is called | 904,170 | <p>I updated my python interpreter, but I think the old one is still called. When I check for the version I get:</p>
<pre><code>$ python -V
Python 3.0.1
</code></pre>
<p>But I believe the old interpreter is still being called. When I run the command:</p>
<pre><code>python myProg.py
</code></pre>
<p>The script runs properly. But when I invoke it with the command</p>
<pre><code>./myProg.py
</code></pre>
<p>I get the error message:</p>
<pre><code>AttributeError: 'str' object has no attribute 'format'
</code></pre>
<p>Which apparently is due to the old interpreter being called. How can I fix this? I run Mac OS X 10.5. Has it something to do with the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>I just started out with python and am not very familiar with interpreted languages, so I am not too sure what is going on.</p>
<p>Edit: Wow, that was quick. Thanks a lot!</p>
| 9 | 2009-05-24T16:55:25Z | 1,218,338 | <p>It may be a bit odd providing a Perl script to answer a Python question, but it works for Python just as well as it does for Perl. This is a script called '<code>fixin</code>', meaning 'fix interpreter'. It changes the shebang line to the correct string for your current PATH.</p>
<pre><code>#!/Users/jleffler/perl/v5.10.0/bin/perl
#
# @(#)$Id: fixin.pl,v 1.3 2003/03/11 21:20:08 jleffler Exp $
#
# FIXIN: from Programming Perl
# Usage: fixin [-s] [file ...]
# Configuration
$does_hashbang = 1; # Kernel recognises #!
$verbose = 1; # Verbose by default
# Construct list of directories to search.
@absdirs = reverse grep(m!^/!, split(/:/, $ENV{'PATH'}, 999));
# Process command line arguments
if ($ARGV[0] eq '-s')
{
shift;
$verbose = 0;
}
die "Usage: $0 [-s] [file ...]\n" unless @ARGV || !-t;
@ARGV = '-' unless @ARGV;
# Process each file.
FILE: foreach $filename (@ARGV)
{
open(IN, $filename) || ((warn "Can't process $filename: $!\n"), next);
$_ = <IN>;
next FILE unless /^#!/; # Not a hash/bang file
chop($cmd = $_);
$cmd =~ s/^#! *//;
($cmd, $arg) = split(' ', $cmd, 2);
$cmd =~ s!^.*/!!;
# Now look (in reverse) for interpreter in absolute path
$found = '';
foreach $dir (@absdirs)
{
if (-x "$dir/$cmd")
{
warn "Ignoring $found\n" if $verbose && $found;
$found = "$dir/$cmd";
}
}
# Figure out how to invoke interpreter on this machine
if ($found)
{
warn "Changing $filename to $found\n" if $verbose;
if ($does_hashbang)
{
$_ = "#!$found";
$_ .= ' ' . $arg if $arg ne '';
$_ .= "\n";
}
else
{
$_ = <<EOF;
:
eval 'exec $found $arg -S \$0 \${1+"\$@"}'
if \$running_under_some_shell;
EOF
}
}
else
{
warn "Can't find $cmd in PATH, $filename unchanged\n" if $verbose;
next FILE;
}
# Make new file if necessary
if ($filename eq '-') { select(STDOUT); }
else
{
rename($filename, "$filename.bak") ||
((warn "Can't modify $filename"), next FILE);
open(OUT, ">$filename") ||
die "Can't create new $filename: $!\n";
($def, $ino, $mode) = stat IN;
$mode = 0755 unless $dev;
chmod $mode, $filename;
select(OUT);
}
# Print the new #! line (or the equivalent) and copy the rest of the file.
print;
while (<IN>)
{
print;
}
close IN;
close OUT;
}
</code></pre>
<p>The code is derived from a script of the same name in the original Camel Book ('Programming Perl', first edition). This copy has been hacked a bit since then - and should be hacked some more. But I use it routinely -- indeed, I just copied it from one Mac to another, and since I've not installed Perl 5.10.0 on the second, I ran:</p>
<pre><code>$ perl fixin fixin
Changing fixin to /usr/bin/perl
$
</code></pre>
<p>Thereby changing from the private install Perl to the standard one.</p>
<p>Exercise for the reader - rewrite the script in Python.</p>
| 1 | 2009-08-02T07:20:35Z | [
"python",
"python-3.x"
] |
A problem with downloading a file with Python | 904,555 | <p>I try to automatically download a file by clicking on a link on the webpage.
After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button.</p>
<p>I use watsup library in the following way:</p>
<pre><code>from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog,wantedClass="Button", wantedText="Save")
clickButton(SaveButton)
</code></pre>
<p>For some reason it does not work. The interesting thing is that exactly the same
code works perfectly to click on 'Cancel' button, however it refuses to work with
'Save' or 'Open'.</p>
<p>Anybody knows what I should do?</p>
<p>Thank you very much,
Sasha</p>
| 3 | 2009-05-24T20:08:58Z | 904,662 | <p>Try this:</p>
<pre><code>from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog, wantedClass="Button", wantedText="Submit")
clickButton(SaveButton)
</code></pre>
| 0 | 2009-05-24T21:08:55Z | [
"python",
"user-interface",
"file",
"download"
] |
A problem with downloading a file with Python | 904,555 | <p>I try to automatically download a file by clicking on a link on the webpage.
After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button.</p>
<p>I use watsup library in the following way:</p>
<pre><code>from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog,wantedClass="Button", wantedText="Save")
clickButton(SaveButton)
</code></pre>
<p>For some reason it does not work. The interesting thing is that exactly the same
code works perfectly to click on 'Cancel' button, however it refuses to work with
'Save' or 'Open'.</p>
<p>Anybody knows what I should do?</p>
<p>Thank you very much,
Sasha</p>
| 3 | 2009-05-24T20:08:58Z | 906,134 | <p>It's possible that the save button is not always enabled. While it may look to your eye that it is, a program might see an initial state that you're missing. Check it's state and wait until it's enabled.</p>
<p>[EDIT] But it's possible that Robert is right and the dialog will just ignore you for security reasons. In this case, I suggest to use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> to parse the HTML, extract the URL and download the file in Python using the <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2 module</a>.</p>
| 0 | 2009-05-25T10:05:08Z | [
"python",
"user-interface",
"file",
"download"
] |
A problem with downloading a file with Python | 904,555 | <p>I try to automatically download a file by clicking on a link on the webpage.
After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button.</p>
<p>I use watsup library in the following way:</p>
<pre><code>from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog,wantedClass="Button", wantedText="Save")
clickButton(SaveButton)
</code></pre>
<p>For some reason it does not work. The interesting thing is that exactly the same
code works perfectly to click on 'Cancel' button, however it refuses to work with
'Save' or 'Open'.</p>
<p>Anybody knows what I should do?</p>
<p>Thank you very much,
Sasha</p>
| 3 | 2009-05-24T20:08:58Z | 907,869 | <p>Sasha,</p>
<p>The code at <a href="http://bytes.com/groups/python/23100-windows-dialog-box-removal" rel="nofollow">this link</a> is supposed to work. It uses ctypes instead of watsup.winGuiAuto, and relies on win32 calls. Here is the code:</p>
<pre><code>from ctypes import *
user32 = windll.user32
EnumWindowsProc = WINFUNCTYPE(c_int, c_int, c_int)
def GetHandles(title, parent=None):
'Returns handles to windows with matching titles'
hwnds = []
def EnumCB(hwnd, lparam, match=title.lower(), hwnds=hwnds):
title = c_buffer(' ' * 256)
user32.GetWindowTextA(hwnd, title, 255)
if title.value.lower() == match:
hwnds.append(hwnd)
if parent is not None:
user32.EnumChildWindows(parent, EnumWindowsProc(EnumCB), 0)
else:
user32.EnumWindows(EnumWindowsProc(EnumCB), 0)
return hwnds
</code></pre>
<p>Here's an example of calling it to click the Ok button on any window that has
the title "Downloads properties" (most likely there are 0 or 1 such windows):</p>
<pre><code>for handle in GetHandles('Downloads properties'):
for childHandle in GetHandles('ok', handle):
user32.SendMessageA(childHandle, 0x00F5, 0, 0) # 0x00F5 = BM_CLICK
</code></pre>
| 0 | 2009-05-25T19:56:23Z | [
"python",
"user-interface",
"file",
"download"
] |
A problem with downloading a file with Python | 904,555 | <p>I try to automatically download a file by clicking on a link on the webpage.
After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button.</p>
<p>I use watsup library in the following way:</p>
<pre><code>from watsup.winGuiAuto import *
optDialog = findTopWindow(wantedText="File Download")
SaveButton = findControl(optDialog,wantedClass="Button", wantedText="Save")
clickButton(SaveButton)
</code></pre>
<p>For some reason it does not work. The interesting thing is that exactly the same
code works perfectly to click on 'Cancel' button, however it refuses to work with
'Save' or 'Open'.</p>
<p>Anybody knows what I should do?</p>
<p>Thank you very much,
Sasha</p>
| 3 | 2009-05-24T20:08:58Z | 908,036 | <p>Sasha,</p>
<p>It is highly likely that the file dialog you refer to (the <a href="http://images.google.com/images?hl=en&q=save%20security%20warning" rel="nofollow">Security Warning file download dialog</a>) will NOT respond to windows messages in this manner, for security reasons. The dialog is specifically designed to respond only to a user physically clicking on the OK button with his mouse. I think you will find that the Run button will not work this way either.</p>
| 1 | 2009-05-25T20:59:28Z | [
"python",
"user-interface",
"file",
"download"
] |
How to parse malformed HTML in python | 904,644 | <p>I need to browse the DOM tree of a parsed HTML document.</p>
<p>I'm using uTidyLib before parsing the string with lxml</p>
<p>a = tidy.parseString(html_code, options)
dom = etree.fromstring(str(a))</p>
<p>sometimes I get an error, it seems that tidylib is not able to repair malformed html.</p>
<p>how can I parse every HTML file without getting an error (parsing only some parts of files that can not be repaired)?</p>
| 12 | 2009-05-24T20:59:27Z | 904,655 | <p><a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> does a good job with invalid/broken HTML</p>
<pre><code>>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<htm@)($*><body><table <tr><td>hi</tr></td></body><html")
>>> print soup.prettify()
<htm>
<body>
<table>
<tr>
<td>
hi
</td>
</tr>
</table>
</body>
</htm>
</code></pre>
| 22 | 2009-05-24T21:06:13Z | [
"python",
"html",
"lxml"
] |
How to parse malformed HTML in python | 904,644 | <p>I need to browse the DOM tree of a parsed HTML document.</p>
<p>I'm using uTidyLib before parsing the string with lxml</p>
<p>a = tidy.parseString(html_code, options)
dom = etree.fromstring(str(a))</p>
<p>sometimes I get an error, it seems that tidylib is not able to repair malformed html.</p>
<p>how can I parse every HTML file without getting an error (parsing only some parts of files that can not be repaired)?</p>
| 12 | 2009-05-24T20:59:27Z | 904,821 | <p>Since you are already using lxml, have you tried <a href="http://lxml.de/" rel="nofollow">lxml's</a> <a href="http://lxml.de/elementsoup.html" rel="nofollow">ElementSoup</a> module?</p>
<p>If ElementSoup can't repair the HTML then you'll probably need to apply your own filters first that are based on your own observations of how the data is broken.</p>
| 13 | 2009-05-24T22:52:08Z | [
"python",
"html",
"lxml"
] |
How to remove all characters after a specific character in python? | 904,746 | <p>I have a string. How do I remove all text after a certain character? (<em>In this case <code>...</code></em>) <br/>
The text after will <strong><code>...</code></strong> change so I that's why I want to remove all characters after a certain one.</p>
| 33 | 2009-05-24T21:56:49Z | 904,753 | <p>Without a RE (which I assume is what you want):</p>
<pre><code>def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
</code></pre>
<p>or, with a RE:</p>
<pre><code>import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
</code></pre>
| 5 | 2009-05-24T22:00:24Z | [
"python",
"replace",
"python-2.6"
] |
How to remove all characters after a specific character in python? | 904,746 | <p>I have a string. How do I remove all text after a certain character? (<em>In this case <code>...</code></em>) <br/>
The text after will <strong><code>...</code></strong> change so I that's why I want to remove all characters after a certain one.</p>
| 33 | 2009-05-24T21:56:49Z | 904,756 | <p>Split on your separator at most once, and take the first piece:</p>
<pre><code>sep = '...'
rest = text.split(sep, 1)[0]
</code></pre>
<p>You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.</p>
| 57 | 2009-05-24T22:01:34Z | [
"python",
"replace",
"python-2.6"
] |
How to remove all characters after a specific character in python? | 904,746 | <p>I have a string. How do I remove all text after a certain character? (<em>In this case <code>...</code></em>) <br/>
The text after will <strong><code>...</code></strong> change so I that's why I want to remove all characters after a certain one.</p>
| 33 | 2009-05-24T21:56:49Z | 904,758 | <p>Assuming your separator is '...', but it can be any string.</p>
<pre><code>text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
</code></pre>
<p>If the separator is not found, <code>head</code> will contain all of the original string.</p>
<p>The partition function was added in Python 2.5.</p>
<blockquote>
<p>partition(...)
S.partition(sep) -> (head, sep, tail)</p>
<pre><code>Searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it. If the separator is not
found, returns S and two empty strings.
</code></pre>
</blockquote>
| 35 | 2009-05-24T22:02:26Z | [
"python",
"replace",
"python-2.6"
] |
How to remove all characters after a specific character in python? | 904,746 | <p>I have a string. How do I remove all text after a certain character? (<em>In this case <code>...</code></em>) <br/>
The text after will <strong><code>...</code></strong> change so I that's why I want to remove all characters after a certain one.</p>
| 33 | 2009-05-24T21:56:49Z | 30,347,303 | <p>another easy way using re will be </p>
<p>import re, clr</p>
<p>text = 'some string... this part will be removed.'</p>
<p>text= re.search(r'(\A.*)....+',url,re.DOTALL|re.IGNORECASE).group(1)</p>
<p>// text = some string</p>
| 0 | 2015-05-20T10:42:08Z | [
"python",
"replace",
"python-2.6"
] |
How to remove all characters after a specific character in python? | 904,746 | <p>I have a string. How do I remove all text after a certain character? (<em>In this case <code>...</code></em>) <br/>
The text after will <strong><code>...</code></strong> change so I that's why I want to remove all characters after a certain one.</p>
| 33 | 2009-05-24T21:56:49Z | 32,574,818 | <p>If you want to remove everything after the last occurrence of character in a string I find this works well:</p>
<p><code>"<character_to_split>".join(string_to_split.split("<character_to_split>")[:-1])</code></p>
<p>For example, if <code>string_to_split</code> is a path like <code>root/location/child/too_far.exe</code> and you only want the folder path, you can split by by <code>"/".join(string_to_split.split("/")[:-1])</code> and you'll get
<code>root/location/child</code></p>
| 2 | 2015-09-14T22:18:10Z | [
"python",
"replace",
"python-2.6"
] |
Problem with datetime module-Python | 904,852 | <p>How come this works:</p>
<pre><code>import datetime
now = datetime.datetime.now()
month = '%d' % now.month
print month
</code></pre>
<p>But this doesn't?</p>
<pre><code>import datetime
now = datetime.datetime.now()
month = '%m' % now.month
print month
</code></pre>
<p>Thanks!</p>
| 0 | 2009-05-24T23:20:22Z | 904,856 | <p>%m is not a supported format character for the % operator. Here is the list of supported <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">formating characters</a> for this operator</p>
<p>%m is valid when your are using <a href="http://docs.python.org/library/time.html#time.strftime" rel="nofollow">strftime</a> function to build a date string</p>
| 3 | 2009-05-24T23:22:45Z | [
"python"
] |
Problem with datetime module-Python | 904,852 | <p>How come this works:</p>
<pre><code>import datetime
now = datetime.datetime.now()
month = '%d' % now.month
print month
</code></pre>
<p>But this doesn't?</p>
<pre><code>import datetime
now = datetime.datetime.now()
month = '%m' % now.month
print month
</code></pre>
<p>Thanks!</p>
| 0 | 2009-05-24T23:20:22Z | 904,861 | <p><code>'%d'</code> is a format character that insert a "signed integer decimal", <code>'%m'</code> has no such meaning. The possible format characters are listed <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">here</a>.</p>
| 1 | 2009-05-24T23:28:18Z | [
"python"
] |
How to do this with datetime & getpage in Python? | 904,894 | <p>Hey guys,
Currently having some problems-</p>
<pre><code>now = datetime.datetime.now()
month = now.strftime("%B")
site = wikipedia.getSite('en', 'wikiquote')
page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:abc")
</code></pre>
<p>I need to get abc to change into the name of the month before it then tries to get the page, yet everything I try it gives an error of some sort.</p>
<p>How could I do it?</p>
<p>Thanks!</p>
| 0 | 2009-05-24T23:50:55Z | 904,900 | <p>Would this work?</p>
<pre><code>page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:" + month)
</code></pre>
| 2 | 2009-05-24T23:57:32Z | [
"python"
] |
How to do this with datetime & getpage in Python? | 904,894 | <p>Hey guys,
Currently having some problems-</p>
<pre><code>now = datetime.datetime.now()
month = now.strftime("%B")
site = wikipedia.getSite('en', 'wikiquote')
page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:abc")
</code></pre>
<p>I need to get abc to change into the name of the month before it then tries to get the page, yet everything I try it gives an error of some sort.</p>
<p>How could I do it?</p>
<p>Thanks!</p>
| 0 | 2009-05-24T23:50:55Z | 904,901 | <p>Did you try this:</p>
<pre><code>page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:%s" % month )
</code></pre>
| 0 | 2009-05-24T23:58:29Z | [
"python"
] |
How to do this with datetime & getpage in Python? | 904,894 | <p>Hey guys,
Currently having some problems-</p>
<pre><code>now = datetime.datetime.now()
month = now.strftime("%B")
site = wikipedia.getSite('en', 'wikiquote')
page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:abc")
</code></pre>
<p>I need to get abc to change into the name of the month before it then tries to get the page, yet everything I try it gives an error of some sort.</p>
<p>How could I do it?</p>
<p>Thanks!</p>
| 0 | 2009-05-24T23:50:55Z | 904,903 | <p>The page URL format is actually <a href="http://en.wikiquote.org/wiki/Wikiquote:Quote%5Fof%5Fthe%5Fday/May" rel="nofollow"><code>Wikiquote:Quote_of_the_day/Month</code></a>. Try this:</p>
<pre><code>page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day/%s" % month)
</code></pre>
| 3 | 2009-05-24T23:59:31Z | [
"python"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 904,941 | <p>You can use <a href="http://docs.python.org/library/stdtypes.html#str.lstrip" rel="nofollow">left strip</a> to remove the leading zero's</p>
<pre><code>day = day.lstrip('0')
>>> day = '01'
>>> day.lstrip('0')
'1'
</code></pre>
| -11 | 2009-05-25T00:15:41Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 904,954 | <p>Some platforms may support width and precision specification between <code>%</code> and the letter (such as 'd' for day of month), according to <a href="http://docs.python.org/library/time.html">http://docs.python.org/library/time.html</a> -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the <code>strftime</code> to remedy that? e.g.:</p>
<pre><code>>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'
</code></pre>
| 30 | 2009-05-25T00:22:43Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 904,958 | <p>Because Python really just calls the C language <code>strftime(3)</code> function on your platform, it might be that there are format characters you could use to control the leading zero; try <code>man strftime</code> and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)</p>
<p>I would try using a new-style <code>datetime</code> object instead, which has attributes like <code>t.year</code> and <code>t.month</code> and <code>t.day</code>, and put those through the normal, high-powered formatting of the <code>%</code> operator, which does support control of leading zeros. See <a href="http://docs.python.org/library/datetime.html" rel="nofollow">http://docs.python.org/library/datetime.html</a> for details. Better yet, use the <code>"".format()</code> operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: <a href="http://docs.python.org/library/string.html#string-formatting" rel="nofollow">http://docs.python.org/library/string.html#string-formatting</a>.</p>
| 1 | 2009-05-25T00:23:21Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 907,607 | <p><a href="http://www.gnu.org/software/libc/manual/html%5Fnode/Formatting-Calendar-Time.html#index-strftime-2660">Here</a> is the documentation of the modifiers supported by <code>strftime()</code> in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:</p>
<ul>
<li><code>%e</code> instead of <code>%d</code> will replace leading zero in day of month with a space</li>
</ul>
<p>It works on my Python (on Linux). I don't know if it will work on yours.</p>
| 14 | 2009-05-25T18:13:36Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 1,428,227 | <p>I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don't mind importing the Django module, check it out.</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date</a></p>
<pre><code>from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')
</code></pre>
| 8 | 2009-09-15T16:31:23Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 2,073,189 | <p>Actually I had the same problem and I realized that, if you add a hyphen between the <code>%</code> and the letter, you can remove the leading zero.</p>
<p>For example <code>%Y/%-m/%-d</code>.</p>
<p>Only works on Unix (Linux, OS X). Doesn't work in Windows (including Cygwin).</p>
| 271 | 2010-01-15T16:38:41Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 3,285,938 | <p>For <code>%d</code> you can convert to integer using <code>int()</code> then it'll automatically remove leading 0 and becomes integer. You can then convert back to string using <code>str()</code>.</p>
| 0 | 2010-07-19T23:33:10Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 5,900,593 | <pre><code>>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'
</code></pre>
| 16 | 2011-05-05T15:46:24Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 7,698,783 | <p>Take a look at <code>-</code> bellow:</p>
<pre><code>>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)
</code></pre>
| 3 | 2011-10-08T18:15:59Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 16,097,385 | <p>We can do this sort of thing with the advent of the <a href="https://docs.python.org/2/library/functions.html#format" rel="nofollow"><code>format</code></a> method since python2.6:</p>
<pre><code>>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'
</code></pre>
<p>Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:</p>
<pre><code>>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'
</code></pre>
<p>And as of python3.6, this can be expressed as an <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow">inline formatted string</a>:</p>
<pre><code>Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'
</code></pre>
| 115 | 2013-04-19T04:48:02Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 26,979,224 | <p>Based on Alex's method, this will work for both the start-of-string and after-spaces cases:</p>
<pre><code>re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")
</code></pre>
<p>I like this better than .format or %-d because this is cross-platform and allows me to keep using strftime (to get things like "November" and "Monday").</p>
| 1 | 2014-11-17T18:19:31Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 27,125,022 | <p>quite late to the party but <code>%-d</code> works on my end.</p>
<p><code>datetime.now().strftime('%B %-d, %Y')</code> produces something like <strong>"November 5, 2014"</strong></p>
<p>cheers :)</p>
| 4 | 2014-11-25T11:08:03Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 31,748,295 | <p>On Windows, add a '#', as in '%#m/%#d/%Y %#I:%M:%S %p'</p>
<p>For reference: <a href="https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx">https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx</a></p>
| 7 | 2015-07-31T14:12:53Z | [
"python",
"padding",
"strftime"
] |
Python strftime - date without leading 0? | 904,928 | <p>When using Python <code>strftime</code>, is there a way to remove the first 0 of the date if it's before the 10th, ie. so <code>01</code> is <code>1</code>? Can't find a <code>%</code>thingy for that?</p>
<p>Thanks!</p>
| 125 | 2009-05-25T00:11:49Z | 38,662,476 | <p>Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it's not listed in the Python documentation I found</p>
| 0 | 2016-07-29T15:29:35Z | [
"python",
"padding",
"strftime"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,015 | <p>Wingware for example implements auto-completion, see <a href="http://wingware.com/doc/edit/auto-completion">http://wingware.com/doc/edit/auto-completion</a> .</p>
| 5 | 2009-05-25T01:07:20Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,022 | <p>ctags + vim works ok, too, although it is not as powerful as intellisense. Using this with ipython, you can get online help, automatic name completion, etc... But that's obviously command-line oriented.</p>
<p>Eclipse + pydev can do it as well, but I have no experience with it: <a href="http://pydev.sourceforge.net/" rel="nofollow">http://pydev.sourceforge.net/</a></p>
| 4 | 2009-05-25T01:13:06Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,036 | <p><a href="http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/">This</a> blog entry explains setting Vim up as a Python IDE, he covers Intellisense-like functionality:</p>
<p><img src="http://blog.dispatched.ch/wp-content/uploads/2009/05/omnicompletion.png" alt="Python Intellsense" /></p>
<p>This is standard in Vim 7. There are a number of other very useful plugins for python development in Vim, such as <a href="http://www.vim.org/scripts/script.php?script%5Fid=2441">Pyflakes</a> which checks code on the fly and <a href="http://www.vim.org/scripts/script.php?script%5Fid=30">Python_fn.vim</a> which provides functionality for manipulating python indentation & code blocks.</p>
| 30 | 2009-05-25T01:25:42Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,053 | <p>The <a href="http://pydev.sf.net/">PyDev</a> environment for Eclipse has intellisense-like functionality for Python. Keeping an interactive console open, along with the <code>help(item)</code> function is very helpful.</p>
| 19 | 2009-05-25T01:34:23Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,076 | <p>I strongly recommend <a href="http://pydev.sourceforge.net">PyDev</a>. In Pydev you can put the module you are using in the <a href="http://www.fabioz.com/pydev/manual%5F101%5Finterpreter.html"><strong>Forced Buildins</strong></a>, mostly the code-completion will work better than in other IDEs like KOMODO EDIT.</p>
<p>Also I think <a href="http://ipython.scipy.org/">IPython</a> is very helpful. Since it is 'run-time' in IPython, the code-completion in IPython won't miss anything.</p>
| 9 | 2009-05-25T01:54:20Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,129 | <p>I'd recommend <a href="http://www.activestate.com/komodo%5Fedit/">Komodo Edit</a>. However, I should point something out: you're not going to get anything quite as good as what you're used to with Visual Studio's C# intellisense. Python's dynamic nature can make it difficult to do these kinds of features.</p>
| 5 | 2009-05-25T02:33:11Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,167 | <p>The <a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29">IDLE editor</a> that comes with Python has an intellisense feature that auto-discovers imported modules, functions, classes and attributes.</p>
| 8 | 2009-05-25T02:55:47Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 905,206 | <p>The dynamic nature of the language tends to make autocomplete type analysis difficult, so the quality of the various completion facilities menitoned above varies wildly.</p>
<p>While it's not exactly what you asked for, the ipython shell is very good for exploratory work. When I'm working with a new module, I tend to pull it into ipython and poke at it. Having tried most of the solutions mentioned above (though it's been years since Wing), ipython's completion facilities are consistently more reliable. The two main tools for exploration are tab complete and appending a question mark to the module/function name to get the help text, e.g.:</p>
<pre><code>In [1]: import sqlalchemy
In [2]: sqlalchemy.s #tab completion
sqlalchemy.schema sqlalchemy.select sqlalchemy.sql sqlalchemy.subquery
In [2]: sqlalchemy.select? #Shows docstring
In [3]: sqlalchemy.select?? #Shows method source
In [4]: edit sqlalchemy.select #opens the source in an editor
</code></pre>
| 13 | 2009-05-25T03:22:07Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 910,623 | <p>Well, I think the most dynamic way to learn Python is to use <a href="http://ipython.scipy.org/moin/" rel="nofollow">iPython</a>.</p>
<p>You got autocompletion when using tab, dynamic behaviour because it's a shell and you can get the full documentation of any object / method typing :</p>
<pre><code>object.method ?
</code></pre>
<p>When developping, I agree that PyDev is cool. But it's heavy, so while learning, a text editor + iPython is really nice.</p>
| 3 | 2009-05-26T13:18:05Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 3,550,759 | <p><a href="http://code.google.com/p/pyscripter/" rel="nofollow">Pyscripter</a> has the best intellisense i have meet :)</p>
| 2 | 2010-08-23T18:54:19Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 6,963,061 | <p>Have a look at <a href="http://pytools.codeplex.com/">python tools for visual studio</a>, they provide code completion (a.k.a intellisense), debugging etc ...</p>
<p>Below is a screenshot of the interactive shell for python showing code completion.</p>
<p><img src="http://i.stack.imgur.com/UhMnP.png" alt="enter image description here"></p>
| 18 | 2011-08-05T22:00:12Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 14,027,081 | <p>IronPython is the way to go. Visual Studio has the best intellisense support and you can utilize that using IronPython</p>
| 0 | 2012-12-25T01:51:44Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 16,967,607 | <p><a href="http://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm</a> is the best Python IDE with IntelliSense support.</p>
| 4 | 2013-06-06T16:41:39Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 16,969,088 | <p>For emacs and VI there's also <a href="https://github.com/tkf/emacs-jedi" rel="nofollow">https://github.com/tkf/emacs-jedi</a>.</p>
| 2 | 2013-06-06T18:06:32Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 22,394,389 | <p>I would recommend <a href="https://github.com/davidhalter/jedi-vim" rel="nofollow">jedi-vim</a>, it's perfect to me, try it and you won't regret.</p>
| 2 | 2014-03-14T01:23:54Z | [
"python",
"ide",
"intellisense"
] |
Python and Intellisense | 905,005 | <p>Is there an equivalent to 'intellisense' for Python?</p>
<p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
| 56 | 2009-05-25T01:02:23Z | 40,068,447 | <p>Try visual Studio Code. It has very powerful Python and Django support and thousands of plugins for other languages used in a Python project such as CSS, HTML and Django templates. </p>
<p>Best of all, it is free:
<a href="https://code.visualstudio.com" rel="nofollow">https://code.visualstudio.com</a></p>
| 0 | 2016-10-16T08:36:46Z | [
"python",
"ide",
"intellisense"
] |
Resources concerning Python scripting in Vim | 905,020 | <p>I'm trying to learn a little about python scripting in GVim, but I'm having trouble with starting. Elementary things, really.</p>
<p>Are there any resources / tutorials concerting python scripting in Vim out there ? Simple examples which show the basic principles, would be welcomed also.</p>
| 34 | 2009-05-25T01:11:07Z | 905,026 | <p>Here is all I know of in terms of such docs:</p>
<ul>
<li><a href="http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html" rel="nofollow">A nice presentation by Sean Reifschneider</a></li>
<li><a href="http://vimdoc.sourceforge.net/htmldoc/if_pyth.html" rel="nofollow">The "official" VIM Python Interface reference</a></li>
<li><a href="http://zerokspot.com/weblog/2009/02/22/getting-to-know-vims-python-interface/" rel="nofollow">some shorter notes</a></li>
<li><a href="http://www.techrepublic.com/article/extending-vim-with-python/6310729" rel="nofollow">Extending Vim With Python</a></li>
</ul>
| 23 | 2009-05-25T01:16:08Z | [
"python",
"vim"
] |
Resources concerning Python scripting in Vim | 905,020 | <p>I'm trying to learn a little about python scripting in GVim, but I'm having trouble with starting. Elementary things, really.</p>
<p>Are there any resources / tutorials concerting python scripting in Vim out there ? Simple examples which show the basic principles, would be welcomed also.</p>
| 34 | 2009-05-25T01:11:07Z | 905,088 | <p>Refer to the <em>Scripting</em> chapter in <a href="http://www.swaroopch.com/notes/vim/" rel="nofollow">'A Byte of Vim'</a>.</p>
| 3 | 2009-05-25T02:01:24Z | [
"python",
"vim"
] |
Resources concerning Python scripting in Vim | 905,020 | <p>I'm trying to learn a little about python scripting in GVim, but I'm having trouble with starting. Elementary things, really.</p>
<p>Are there any resources / tutorials concerting python scripting in Vim out there ? Simple examples which show the basic principles, would be welcomed also.</p>
| 34 | 2009-05-25T01:11:07Z | 905,091 | <p>:help python-vim is a good start. The best vim resource is always at your fingertips and the sooner you get used to referring to it the better you will get at vim overall.</p>
<p>I got better at searching vim help with this..</p>
<p><a href="http://stackoverflow.com/questions/526858/how-do-i-make-vim-do-normal-bash-like-tab-completion-for-file-names/526940#526940">http://stackoverflow.com/questions/526858/how-do-i-make-vim-do-normal-bash-like-tab-completion-for-file-names/526940#526940</a></p>
<p>also :he vim-script-intro </p>
<p>I'd also recommend looking straight at the source of existing plugins that do something similar to what you want to do. That way you cut out the middle man and dont have to deal with blog ads and other distractions.</p>
| 4 | 2009-05-25T02:04:40Z | [
"python",
"vim"
] |
Resources concerning Python scripting in Vim | 905,020 | <p>I'm trying to learn a little about python scripting in GVim, but I'm having trouble with starting. Elementary things, really.</p>
<p>Are there any resources / tutorials concerting python scripting in Vim out there ? Simple examples which show the basic principles, would be welcomed also.</p>
| 34 | 2009-05-25T01:11:07Z | 9,173,894 | <h3>Vimscript The Hard Way</h3>
<p>Have you checked out <a href="http://www.vim.org/scripts/script.php?script_id=2914" rel="nofollow">Learn Vimscript The Hard Way</a>? It is an excellent read.</p>
<h3>Scripting Vim With Python</h3>
<p>vim 7.0 and above can be compiled with the <code>+python</code> flag, which gives vim Python support. This is a (albeit, somewhat extreme) path to getting the language support you want.</p>
<p><strong>Links</strong> </p>
<ul>
<li><a href="http://blog.raynes.me/blog/2012/02/01/i-code-with-things-and-stuff/" rel="nofollow">I Code With Things And Stuff</a> delves a into how to extend your editor with a scripting language like Python.</li>
<li><a href="http://www.techrepublic.com/article/extending-vim-with-python/6310729" rel="nofollow">Extending Vim With Python</a> seems like more of a reference for the topic.</li>
</ul>
| 3 | 2012-02-07T09:36:35Z | [
"python",
"vim"
] |
Why does sys.exit() not exit when called inside a thread in Python? | 905,189 | <p>This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.</p>
<pre><code>import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
</code></pre>
<p>The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit. </p>
<p>Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?</p>
| 43 | 2009-05-25T03:10:44Z | 905,224 | <p>sys.exit() raises the SystemExit exception, as does thread.exit(). So, when sys.exit() raises that exception inside that thread, it has the same effect as calling thread.exit(), which is why only the thread exits.</p>
| 35 | 2009-05-25T03:31:38Z | [
"python",
"python-2.6"
] |
Why does sys.exit() not exit when called inside a thread in Python? | 905,189 | <p>This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.</p>
<pre><code>import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
</code></pre>
<p>The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit. </p>
<p>Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?</p>
| 43 | 2009-05-25T03:10:44Z | 905,280 | <p>Is the fact that "pre main exit, post thread exit" is printed what's bothering you?</p>
<p>Unlike some other languages (like Java) where the analog to <code>sys.exit</code> (<code>System.exit</code>, in Java's case) causes the VM/process/interpreter to immediately stop, Python's <code>sys.exit</code> just throws an exception: a SystemExit exception in particular.</p>
<p>Here are the docs for <code>sys.exit</code> (just <code>print sys.exit.__doc__</code>):</p>
<blockquote>
<p>Exit the interpreter by raising SystemExit(status).<br>
If the status is omitted or None, it defaults to zero (i.e., success).<br>
If the status is numeric, it will be used as the system exit status.<br>
If it is another kind of object, it will be printed and the system<br>
exit status will be one (i.e., failure).<br></p>
</blockquote>
<p>This has a few consequences:</p>
<ul>
<li>in a thread it just kills the current thread, not the entire process (assuming it gets all the way to the top of the stack...) </li>
<li>object destructors (<code>__del__</code>) are potentially invoked as the stack frames that reference those objects are unwound</li>
<li>finally blocks are executed as the stack unwinds</li>
<li>you can catch a <code>SystemExit</code> exception</li>
</ul>
<p>The last is possibly the most surprising, and is yet another reason why you should almost never have an unqualified <code>except</code> statement in your Python code.</p>
| 6 | 2009-05-25T04:07:21Z | [
"python",
"python-2.6"
] |
Why does sys.exit() not exit when called inside a thread in Python? | 905,189 | <p>This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.</p>
<pre><code>import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
</code></pre>
<p>The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit. </p>
<p>Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?</p>
| 43 | 2009-05-25T03:10:44Z | 906,401 | <blockquote>
<p>What if I did want to exit the program
from the thread (not that I actually
want to, but just so I understand)?</p>
</blockquote>
<p>My preferred method is Erlang-ish message passing. Slightly simlified, I do it like this:</p>
<pre><code>import sys, time
import threading
import Queue # thread-safe
class CleanExit:
pass
ipq = Queue.Queue()
def testexit(ipq):
time.sleep(5)
ipq.put(CleanExit)
return
threading.Thread(target=testexit, args=(ipq,)).start()
while True:
print "Working..."
time.sleep(1)
try:
if ipq.get_nowait() == CleanExit:
sys.exit()
except Queue.Empty:
pass
</code></pre>
| 12 | 2009-05-25T11:32:18Z | [
"python",
"python-2.6"
] |
Why does sys.exit() not exit when called inside a thread in Python? | 905,189 | <p>This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.</p>
<pre><code>import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
</code></pre>
<p>The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit. </p>
<p>Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?</p>
| 43 | 2009-05-25T03:10:44Z | 5,120,178 | <blockquote>
<p>What if I did want to exit the program
from the thread?</p>
</blockquote>
<p>Apart from the method Deestan described you can call <code>os._exit</code> (notice the underscore). Before using it make sure that you understand that it does <em>no</em> cleanups (like calling <code>__del__</code> or similar).</p>
| 7 | 2011-02-25T16:58:10Z | [
"python",
"python-2.6"
] |
Why does sys.exit() not exit when called inside a thread in Python? | 905,189 | <p>This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.</p>
<pre><code>import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
</code></pre>
<p>The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit. </p>
<p>Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?</p>
| 43 | 2009-05-25T03:10:44Z | 7,099,229 | <blockquote>
<p>What if I did want to exit the program from the thread (not that I
actually want to, but just so I understand)?</p>
</blockquote>
<p>At least on Linux you could do something like:</p>
<pre><code>os.kill(os.getpid(), signal.SIGINT)
</code></pre>
<p>This send a SIGINT to the main thread where it can be handled as a KeyboardInterrupt.</p>
<p>BTW: On Windows you can only send a SIGTERM signal, which cannot be caught from Python. (there I would prefer calling os._exit as suggested by Helmut)</p>
| 3 | 2011-08-17T20:43:41Z | [
"python",
"python-2.6"
] |
os.system() execute command under which linux shell? | 905,221 | <p>I am using /bin/tcsh as my default shell. </p>
<p>However, the tcsh style command os.system('setenv VAR val') doesn't work for me. But os.system('export VAR=val') works.</p>
<p>So my question is how can I know the os.system() run command under which shell?</p>
| 8 | 2009-05-25T03:30:14Z | 905,258 | <p>These days you should be using the <a href="http://docs.python.org/library/subprocess.html">Subprocess</a> module instead of <code>os.system()</code>. According to the documentation there, the default shell is <code>/bin/sh</code>. I believe that <code>os.system()</code> works the same way.</p>
<p>Edit: I should also mention that the subprocess module allows you to set the environment available to the executing process through the <code>env</code> parameter.</p>
| 9 | 2009-05-25T03:51:58Z | [
"python",
"linux",
"shell"
] |
os.system() execute command under which linux shell? | 905,221 | <p>I am using /bin/tcsh as my default shell. </p>
<p>However, the tcsh style command os.system('setenv VAR val') doesn't work for me. But os.system('export VAR=val') works.</p>
<p>So my question is how can I know the os.system() run command under which shell?</p>
| 8 | 2009-05-25T03:30:14Z | 905,294 | <p><code>os.system()</code> just calls the <code>system()</code> system call ("<code>man 3 system</code>"). On most *nixes this means you get <code>/bin/sh</code>.</p>
<p>Note that <code>export VAR=val</code> is technically not standard syntax (though <code>bash</code> understands it, and I think <code>ksh</code> does too). It will not work on systems where <code>/bin/sh</code> is actually the Bourne shell. On those systems you need to export and set as separate commands. (This will work with <code>bash</code> too.)</p>
| 4 | 2009-05-25T04:17:18Z | [
"python",
"linux",
"shell"
] |
os.system() execute command under which linux shell? | 905,221 | <p>I am using /bin/tcsh as my default shell. </p>
<p>However, the tcsh style command os.system('setenv VAR val') doesn't work for me. But os.system('export VAR=val') works.</p>
<p>So my question is how can I know the os.system() run command under which shell?</p>
| 8 | 2009-05-25T03:30:14Z | 906,286 | <p>If your command is a shell file, and the file is executable, and the file begins with "#!", you can pick your shell.</p>
<pre><code>#!/bin/zsh
Do Some Stuff
</code></pre>
<p>You can write this file and then execute it with <code>subprocess.Popen(filename,shell=True)</code> and you'll be able to use any shell you want.</p>
<p>Also, be sure to read <a href="http://docs.python.org/library/subprocess.html#replacing-os-system" rel="nofollow">this</a> about <code>os.system</code> and <code>subprocess.Popen</code>.</p>
| 2 | 2009-05-25T11:00:53Z | [
"python",
"linux",
"shell"
] |
os.system() execute command under which linux shell? | 905,221 | <p>I am using /bin/tcsh as my default shell. </p>
<p>However, the tcsh style command os.system('setenv VAR val') doesn't work for me. But os.system('export VAR=val') works.</p>
<p>So my question is how can I know the os.system() run command under which shell?</p>
| 8 | 2009-05-25T03:30:14Z | 14,665,851 | <p>Was just reading <a href="http://www.rubyops.net/executing-bash-from-python">Executing BASH from Python</a>, then <a href="http://docs.python.org/2/library/subprocess.html#popen-constructor">17.1. subprocess â Subprocess management â Python v2.7.3 documentation</a>, and I saw the <code>executable</code> argument; and it seems to work:</p>
<pre><code>$ python
Python 2.7.1+ (r271:86832, Sep 27 2012, 21:16:52)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print os.popen("echo $0").read()
sh
>>> import subprocess
>>> print subprocess.call("echo $0", shell=True).read()
/bin/sh
>>> print subprocess.Popen("echo $0", stdout=subprocess.PIPE, shell=True).stdout.read()
/bin/sh
>>> print subprocess.Popen("echo $0", stdout=subprocess.PIPE, shell=True, executable="/bin/bash").stdout.read()
/bin/bash
>>> print subprocess.Popen("cat <(echo TEST)", stdout=subprocess.PIPE, shell=True).stdout.read()
/bin/sh: Syntax error: "(" unexpected
>>> print subprocess.Popen("cat <(echo TEST)", stdout=subprocess.PIPE, shell=True, executable="/bin/bash").stdout.read()
TEST
</code></pre>
<p>Hope this helps someone,<br>
Cheers!</p>
| 8 | 2013-02-02T19:54:43Z | [
"python",
"linux",
"shell"
] |
Python - how to implement Bridge (or Adapter) design pattern? | 905,289 | <p>I'm struggling with implementing the Bridge design pattern (or an alternative such as Adapter) in Python</p>
<p>I want to be able to write code like this to dump database schemas based on a supplied URL:</p>
<pre><code>urls = ['sqlite://c:\\temp\\test.db', 'oracle://user:password@tns_name'];
for url in urls:
db = Database(url);
schema = db.schema()
</code></pre>
<p>I've got classes defined as</p>
<pre><code>class Database():
def __init__(self, url):
self.db_type = string.split(self.url, "://")[0]
class Oracle():
def schema(self):
# Code to return Oracle schema
class SQLite():
def schema(self):
# Code to return SQLite schema
</code></pre>
<p>How can I "glue" these 3 classes together so I can get the first code block to execute correctly? I've Googled around, but must be having a thick day as it's just not coming together in my mind...</p>
<p>Thanks in advance</p>
| 7 | 2009-05-25T04:12:43Z | 905,292 | <p>Use a Factory pattern instead:</p>
<pre><code>class Oracle(object):
...
class SQLite(object):
...
dbkind = dict(sqlite=SQLite, oracle=Oracle)
def Database(url):
db_type, rest = string.split(self.url, "://", 1)
return dbkind[db_type](rest)
</code></pre>
| 21 | 2009-05-25T04:16:29Z | [
"python",
"design-patterns"
] |
Is there any library to find out urls of embedded flvs in a webpage? | 905,403 | <p>I'm trying to write a script which can automatically download gameplay videos. The webpages look like dota.sgamer.com/Video/Detail/402 and www.wfbrood.com/movie/spl2009/movie_38214.html, they have flv player embedded in the flash plugin.
Is there any library to help me find out the exact flv urls? or any other ideas to get it?</p>
<p>Many thanks for your replies</p>
| 1 | 2009-05-25T05:07:31Z | 905,451 | <p>if the embed player makes use of some variable where the flv path is set then you can download it, if not.. I doubt you find something to do it "automaticly" since every site make it's own player and identify the file by id not by path, which makes hard to know where the flv file is.</p>
| 0 | 2009-05-25T05:34:41Z | [
"python",
"download",
"flv"
] |
Is there any library to find out urls of embedded flvs in a webpage? | 905,403 | <p>I'm trying to write a script which can automatically download gameplay videos. The webpages look like dota.sgamer.com/Video/Detail/402 and www.wfbrood.com/movie/spl2009/movie_38214.html, they have flv player embedded in the flash plugin.
Is there any library to help me find out the exact flv urls? or any other ideas to get it?</p>
<p>Many thanks for your replies</p>
| 1 | 2009-05-25T05:07:31Z | 905,552 | <p>It looks like <a href="http://undefined.org/python/#flashticle" rel="nofollow">Flashticle</a> (4th result on searching the cheese shop for "flash"), might be able to get the information you want, if it is there.</p>
<p>As to getting the file, you want to look at a html parser. I've heard good things about <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>. Between that and urllib2 (part of the standard library), you should be able to download the swf file to work on.</p>
<p>Please note that I have never tried this, and am not familiar with flash at all (other than as an end-user, of course).</p>
| 1 | 2009-05-25T06:15:54Z | [
"python",
"download",
"flv"
] |
HttpResponseRedirect django + facebook | 905,803 | <p>I have a form with 2 buttons. depending on the button click user is
taken to different url.
view function is : </p>
<pre><code>friend_id = request.POST.get('selected_friend_id_list')
history = request.POST.get('statushistory')
if history:
print "dfgdfgdf"
return HttpResponseRedirect('../status/')
else:
return direct_to_template(request, 'friends_list.fbml',
extra_context={'fbuser': user,
'user_lastname':user_lastname,
'activemaintab':activemaintab,
'friends':friends,
'friend_list':friend_list})
</code></pre>
<p>for template : </p>
<pre><code><input type="submit" value="Calendar View" name="calendarview"/>
<input type="submit" value="Status History" name="statushistory"/>
</form
</code></pre>
<p>so my problem is page is not redirecting to the url .
If I make HttpResponseRedirect('../') it gives me the correct page
but url is not changing.</p>
<p>current page = "friendlist/ status/
so after submitting form my url should be frinedlist/list/
so this should work HttpResponseRedirect('../list/') but url is not getting changed.
Any idea?
How can I fix this
Thanks </p>
| 0 | 2009-05-25T07:53:37Z | 905,930 | <p>Why do you need to use relative urls? Can you not use absolute urls?</p>
| 0 | 2009-05-25T08:50:25Z | [
"python",
"django",
"facebook"
] |
HttpResponseRedirect django + facebook | 905,803 | <p>I have a form with 2 buttons. depending on the button click user is
taken to different url.
view function is : </p>
<pre><code>friend_id = request.POST.get('selected_friend_id_list')
history = request.POST.get('statushistory')
if history:
print "dfgdfgdf"
return HttpResponseRedirect('../status/')
else:
return direct_to_template(request, 'friends_list.fbml',
extra_context={'fbuser': user,
'user_lastname':user_lastname,
'activemaintab':activemaintab,
'friends':friends,
'friend_list':friend_list})
</code></pre>
<p>for template : </p>
<pre><code><input type="submit" value="Calendar View" name="calendarview"/>
<input type="submit" value="Status History" name="statushistory"/>
</form
</code></pre>
<p>so my problem is page is not redirecting to the url .
If I make HttpResponseRedirect('../') it gives me the correct page
but url is not changing.</p>
<p>current page = "friendlist/ status/
so after submitting form my url should be frinedlist/list/
so this should work HttpResponseRedirect('../list/') but url is not getting changed.
Any idea?
How can I fix this
Thanks </p>
| 0 | 2009-05-25T07:53:37Z | 906,265 | <p>"so my problem is page is not redirecting to the url . If I make HttpResponseRedirect('../') it gives me the correct page but url is not changing."</p>
<p>By "URL" I'm guessing you mean "The URL shown in the browser". It helps if your question is very precise.</p>
<p>First, you must provide an absolute URL. <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect</a></p>
<p>It's quite clear from the standards (RFC 2616, section 14.30) that an absolute URL is required. Some browsers may tolerate a relative URL. Some don't.</p>
<p>Second, you should never use relative URL's anywhere in your programs.</p>
<p>You should be using <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse" rel="nofollow">reverse</a>.</p>
<pre><code>from django.core.urlresolvers import reverse
def myview(request):
theURL= reverse('path.to.viewFunction')
return HttpResponseRedirect(theURL)
</code></pre>
| 2 | 2009-05-25T10:56:03Z | [
"python",
"django",
"facebook"
] |
Why such import is not allowed? | 905,848 | <p>FILE: b.py</p>
<pre><code>class B:
def __init__(self):
print "B"
import a
a = A()
</code></pre>
<p>FILE: a.py</p>
<pre><code>class A(B): ###=> B is not defined
def __init__(self):
print "A"
</code></pre>
<p>When I try to execute <code>b.py</code>, it's said that B is not defined. Am I misunderstanding "import"?</p>
<p>Thanks a lot if you can pointer out the problem. </p>
| 3 | 2009-05-25T08:22:29Z | 905,887 | <p>Because python initializes class A in its own file. It is not like a C or PHP include where every imported module is essentially pasted into the original file.</p>
<p>You should put class B in the same file as class A to fix this problem. Or you can put class B in c.py and import it with "from c import B".</p>
| 5 | 2009-05-25T08:36:18Z | [
"python"
] |
Why such import is not allowed? | 905,848 | <p>FILE: b.py</p>
<pre><code>class B:
def __init__(self):
print "B"
import a
a = A()
</code></pre>
<p>FILE: a.py</p>
<pre><code>class A(B): ###=> B is not defined
def __init__(self):
print "A"
</code></pre>
<p>When I try to execute <code>b.py</code>, it's said that B is not defined. Am I misunderstanding "import"?</p>
<p>Thanks a lot if you can pointer out the problem. </p>
| 3 | 2009-05-25T08:22:29Z | 906,141 | <p>The closest working thing to your code would be:</p>
<pre><code>==== FILE: b.py ====
class B:
def __init__(self):
print "B"
import a
if __name__ == "__main__":
a = a.A()
==== FILE: a.py ====
import b
class A(b.B): ###=> B is not defined
def __init__(self):
print "A"
</code></pre>
<p>Notice the differences:</p>
<ul>
<li><p>Files (modules) are namespaces, if you import "a" you refer to its class A as "a.A".</p></li>
<li><p>You need to import b in a.py if you want to use it.</p></li>
</ul>
<p>You want to avoid having two modules that need to include each other, by either putting everything in the same module, or splitting things up in more modules. Also, it's better to have all your imports at the head of the file, which makes this kind of monkeying impossible.</p>
| 5 | 2009-05-25T10:08:29Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.