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
sequence |
---|---|---|---|---|---|---|---|---|---|
In Python, how do I find the date of the first Monday of a given week? | 396,913 | <p>If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?</p>
<p>Many thanks</p>
| 26 | 2008-12-29T00:42:56Z | 3,314,360 | <pre><code>from datetime import date, timedelta
def first_monday(year, week):
d = date(year, 1, 4) # The Jan 4th must be in week 1 according to ISO
return d + timedelta(weeks=(week-1), days=-d.weekday())
</code></pre>
| 12 | 2010-07-22T23:36:23Z | [
"python",
"datetime"
] |
commands to send messages in Python via the Poplib module? | 396,991 | <p>I've found a number of tutorials online involving downloading messages via Poplib, but haven't been able to find anything explaining how to create new messages. Does this exist?</p>
| 1 | 2008-12-29T02:14:17Z | 396,994 | <p>Send yourself an email to create a message.</p>
<p>SMTP is the protocol the email uses to send. In Python, you'd find this in <a href="http://docs.python.org/library/smtplib.html" rel="nofollow">smtplib</a>.</p>
<p>There are numerous email RFC's. Here are a few.</p>
<p>SMTP - <a href="http://www.faqs.org/rfcs/rfc821.html" rel="nofollow">RFC 821</a> </p>
<p>POP - <a href="http://www.faqs.org/rfcs/rfc1939.html" rel="nofollow">RFC 1939</a></p>
<p>IMAP - <a href="http://www.faqs.org/rfcs/rfc1730.html" rel="nofollow">RFC 1730</a></p>
| 2 | 2008-12-29T02:17:35Z | [
"python",
"email",
"poplib"
] |
commands to send messages in Python via the Poplib module? | 396,991 | <p>I've found a number of tutorials online involving downloading messages via Poplib, but haven't been able to find anything explaining how to create new messages. Does this exist?</p>
| 1 | 2008-12-29T02:14:17Z | 397,003 | <p>As S.Lott rightly says, you will want some smtp, but to create the actual email, use the <a href="http://docs.python.org/library/email" rel="nofollow">email</a> package from the standard library, then use an message's as_string method to send it.</p>
<p><a href="http://code.activestate.com/recipes/52243/" rel="nofollow">An example with multipart MIME (how cool is that!)</a></p>
| 3 | 2008-12-29T02:24:51Z | [
"python",
"email",
"poplib"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,047 | <p>EDIT: As mentioned above, this isn't the Ellipsis object, but the result of a looped list. I jumped the gun here. Knowing about the Ellipsis object is a good bit of back shelf knowledge should you find an Ellipsis in some actual code, rather than the output.</p>
<p><hr /></p>
<p>The Ellipsis object in Python is used for extended slice notation. It's not used in current Python core libraries, but is available for developers to define in their own libraries. For example, NumPy (or SciPy) use this as part of their array object. You'll need to look at the documentation for tree() to know exactly how Ellipsis behaves in this object.</p>
<p>From <a href="http://www.python.org/doc/2.5.2/lib/bltin-ellipsis-object.html" rel="nofollow">Python documentation</a>:</p>
<blockquote>
<p>3.11.8 The Ellipsis Object</p>
<p>This object is used by extended slice
notation (see the Python Reference
Manual). It supports no special
operations. There is exactly one
ellipsis object, named Ellipsis (a
built-in name).</p>
<p>It is written as Ellipsis.</p>
</blockquote>
| 2 | 2008-12-29T02:56:36Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,054 | <p>It can also appear if you have a circular structure with a list pointing to itself. Like this:</p>
<pre><code>>>> a = [1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>>
</code></pre>
<p>Since python can't print out the structure (it would be an infinite loop) it uses the ellipsis to show that there is recursion in the structure.</p>
<p><hr /></p>
<p>I'm not quite sure if the question was what what going on or how to fix it, but I'll try to correct the functions above.</p>
<p>In both of them, you first make two recursive calls, which add data to the list <code>y</code>, and then AGAIN append the returned data to <code>y</code>. This means the same data will be present several times in the result.</p>
<p>Either just collect all the data without adding to any <code>y</code>, with something like</p>
<pre><code>return [x[2]]+keys(x[0])+keys(x[1])
</code></pre>
<p>or just do the appending in the calls, with something like</p>
<pre><code>y += [x[2]]
keys(x[0], y) #Add left children to y...
keys(x[1], y) #Add right children to y...
return y
</code></pre>
<p>(Of course, both these snippets need handling for empty lists etc)</p>
<p>@Abgan also noted that you really don't want <code>y=[]</code> in the initializer.</p>
| 23 | 2008-12-29T03:02:35Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,057 | <p>I don't understand your code above, but the [...] I think is the Python interpreter skipping infinite data structures. For example:</p>
<pre><code>>>> a = [0, 1]
>>> a[0] = a
>>> a
[[...], 1]
</code></pre>
<p>It looks like your tree structure is becoming looped.</p>
<p>The answers about slice objects are beside the point.</p>
| 5 | 2008-12-29T03:03:22Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,062 | <p>I believe, that your 'tree' contains itself, therefore it contains cycles.</p>
<p>Try this code:</p>
<pre>
a = [1,2,3,4]
print a
a.append(a)
print a
</pre>
<p>The first print outputs:</p>
<pre>
[1,2,3,4]
</pre>
<p>while the second:
<pre>
[1,2,3,4, [...]]
</pre></p>
<p>The reason is using
<pre>
def Keys(x,y=[]):
</pre>
This is wrong and evil. List is a mutable object, and when used as a default parameter, it is preserved between function calls.
So each y += "anything" operation adds to the same list (in all function calls, and since the function is recursive...)</p>
<p><hr /></p>
<p>See the <a href="http://effbot.org/zone/default-values.htm" rel="nofollow">Effbot</a> or <a href="http://www.devshed.com/c/a/Python/Python-Parameters-Functions-and-Arguments/" rel="nofollow">Devshed</a> for more details on mutable objects passed as default values for functions.</p>
| 6 | 2008-12-29T03:08:33Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,070 | <blockquote>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however </p>
</blockquote>
<p>Look at the following code:</p>
<pre><code>>>> a = [0]
>>> a.append(a)
>>> print a
[0, [...]]
</code></pre>
<p>How is Python supposed to print a? It is a list that contains a zero and a reference to itself. Hence it is a list that contains a zero and a reference to a list</p>
<pre><code>[0, [...]]
</code></pre>
<p>which in turn contains a zero and a reference to a list</p>
<pre><code>[0, [0, [...]]]
</code></pre>
<p>which in turn contains a zero and a reference to a list,
and so on, recursively:</p>
<pre><code>[0, [0, [0, [...]]]]
[0, [0, [0, [0, [...]]]]]
[0, [0, [0, [0, [0, [...]]]]]]
...
</code></pre>
<p>There is nothing wrong with the recursive data structure itself. The only problem is that it cannot be <em>displayed</em>, for this would imply an infinite recursion. Hence Python stops at the first recursion step and deals with the infinity issue printing only the ellipsis, as was pointed out in previous answers.</p>
| 4 | 2008-12-29T03:15:38Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,091 | <p>Ok, so in points:</p>
<ol>
<li><p>You're creating infinite data
structure: <pre>def Keys(x,y=[])</pre> will use the same 'y' in
each call. This just isn't correct.</p></li>
<li><p>The <code>print</code> statement, however, is clever enough not to print an infinite data, but to mark self-reference with a [...] (known as <em>Ellipsis</em>)</p></li>
<li>The Python will allow you to address such structure correctly, so you can write <pre>a.keys()[1][1][1]</pre> and so on. Why shouldn't you?</li>
<li>The <code>y = y[:]</code> statement simply copies the list y. Can be done more soundly with <code>y = list(y)</code></li>
</ol>
<p>Try using the following code:</p>
<pre>
def Keys(x,y=None):
if y is None:
y = []
if len(x):
y += [x[2], Keys(x[0],y), Keys(x[1],y)]
return y
</pre>
<p>But still I guess that it can bite you. You're still using the same variable y (I mean the same object) in three places in one expression:</p>
<pre> y += [x[2], Keys(x[0], y), Keys(x[1], y)] </pre>
Is that what you really want to achieve?
Or maybe you should try:
<pre>
def mKeys(x,y=None):
if y is None:
y = []
if len(x):
z = [x[2], mKeys(x[0], y), mKeys(x[1],y)]
return z
return []
</pre>
| 1 | 2008-12-29T03:46:18Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 397,223 | <p>For the difference between the two versions of the function Keys, note the following difference:</p>
<pre><code>y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)
</code></pre>
<p>The right side value in this statement is a list which contains x[2], plus the ELEMENTS OF Keys(x[0],y) and the ELEMENTS OF Keys(x[1],y)</p>
<pre><code>y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
</code></pre>
<p>The right side value in this statement is a list which contains x[2], plus the LIST Keys(x[2],y) and the LIST Keys(x[1],y).</p>
<p>So the version using [a,b] will causing y contains itself as its elements.</p>
<p>Some other notes:</p>
<ol>
<li><p>Since in python, the default value object is created once when the function is defined, the first version will not work like the example shows. It will contain multiple copy of some keys. It's hard to explain in short, but you can get some idea by printing the values of x, y on each call of Keys. </p>
<p>This is confirmed by running the function on my machine with python 2.5.2.</p></li>
<li><p>Also because the default value is defined only once at function definition time, even the function works correct for the first time, it will not work when calling with a different a, since the keys in the first binary tree will remain in y.</p>
<p>You can see this by calling Keys(a) twice, or calling it on two different lists.</p></li>
<li><p>The second parameter is not required for this problem. The function can be like this:</p>
<p>def Keys(a):
if a = []:
return []
else:
return [a[2]]+Keys(a[0])+Keys(a[1])</p>
<p>Defining a recursive function basically contains two part, solve subproblems and combined the results. In your code, the combining results part is repeated twice: one by accumulating them in y, one by adding the list together.</p></li>
</ol>
| 1 | 2008-12-29T06:20:54Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 15,325,426 | <p>If you would have used a PrettyPrinter, the output would had been self explanatory</p>
<pre><code>>>> l = [1,2,3,4]
>>> l[0]=l
>>> l
[[...], 2, 3, 4]
>>> pp = pprint.PrettyPrinter(indent = 4)
>>> pp.pprint(l)
[<Recursion on list with id=70327632>, 2, 3, 4]
>>> id(l)
70327632
</code></pre>
<p>In other words its something like</p>
<p><img src="http://i.stack.imgur.com/v2TY7.png" alt="enter image description here"></p>
| 2 | 2013-03-10T17:47:02Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Confusing [...] List in Python: What is it? | 397,034 | <p>So I was writing up a simple binary tree in Python and came across [...]</p>
<p>I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
<code></p>
<pre><code>>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
</code></pre>
<p></code></p>
<p>Version using a+b</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
</code></pre>
<p>version using [a,b]</p>
<pre><code>def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
</code></pre>
<p>So what exactly is [...]?</p>
| 16 | 2008-12-29T02:46:31Z | 38,544,046 | <p>The issue is because one of the list element is referencing the list itself. So if an attempt to print all the elements is made then it would never end.</p>
<p><strong>Illustration:</strong></p>
<pre><code>x = range(3)
x.append(x)
x[3][3][3][3][3][0] = 5
print x
</code></pre>
<p>Output:</p>
<pre><code>[5, 1, 2, [...]]
</code></pre>
<p><code>x[3]</code> is a referring to <code>x</code> itself. Same goes for <code>x[3][3]</code>.</p>
<p>This can be visualised better
[here](<a href="http://pythontutor.com/visualize.html#code=x+%3D+range(3%29%0Ax.append(x%29%0Ax%5B3%5D%5B3%5D%5B3%5D%5B3%5D%5B3%5D%5B0%5D+%3D+5%0Aprint+x&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=4" rel="nofollow">http://pythontutor.com/visualize.html#code=x+%3D+range(3%29%0Ax.append(x%29%0Ax%5B3%5D%5B3%5D%5B3%5D%5B3%5D%5B3%5D%5B0%5D+%3D+5%0Aprint+x&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=4</a> )</p>
| 0 | 2016-07-23T16:35:28Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] |
Reading the target of a .lnk file in Python? | 397,125 | <p>I'm trying to read the target file/directory of a shortcut (<code>.lnk</code>) file from Python. Is there a headache-free way to do it? The <a href="http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf">.lnk spec [PDF]</a> is way over my head.
I don't mind using Windows-only APIs.</p>
<p>My ultimate goal is to find the <code>"(My) Videos"</code> folder on Windows XP and Vista. On XP, by default, it's at <code>%HOMEPATH%\My Documents\My Videos</code>, and on Vista it's <code>%HOMEPATH%\Videos</code>. However, the user can relocate this folder. In the case, the <code>%HOMEPATH%\Videos</code> folder ceases to exists and is replaced by <code>%HOMEPATH%\Videos.lnk</code> which points to the new <code>"My Videos"</code> folder. And I want its absolute location.</p>
| 16 | 2008-12-29T04:31:27Z | 397,137 | <p>Basically call the Windows API directly. Here is a good example found after Googling:</p>
<pre><code>import os, sys
import pythoncom
from win32com.shell import shell, shellcon
shortcut = pythoncom.CoCreateInstance (
shell.CLSID_ShellLink,
None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IShellLink
)
desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
shortcut_path = os.path.join (desktop_path, "python.lnk")
persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
persist_file.Load (shortcut_path)
shortcut.SetDescription ("Updated Python %s" % sys.version)
mydocs_path = shell.SHGetFolderPath (0, shellcon.CSIDL_PERSONAL, 0, 0)
shortcut.SetWorkingDirectory (mydocs_path)
persist_file.Save (shortcut_path, 0)
</code></pre>
<p>This is from <a href="http://timgolden.me.uk/python/win32_how_do_i/create-a-shortcut.html">http://timgolden.me.uk/python/win32_how_do_i/create-a-shortcut.html</a>.</p>
<p>You can search for "python ishelllink" for other examples.</p>
<p>Also, the API reference helps too: <a href="http://msdn.microsoft.com/en-us/library/bb774950(VS.85).aspx">http://msdn.microsoft.com/en-us/library/bb774950(VS.85).aspx</a></p>
| 6 | 2008-12-29T04:44:23Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] |
Reading the target of a .lnk file in Python? | 397,125 | <p>I'm trying to read the target file/directory of a shortcut (<code>.lnk</code>) file from Python. Is there a headache-free way to do it? The <a href="http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf">.lnk spec [PDF]</a> is way over my head.
I don't mind using Windows-only APIs.</p>
<p>My ultimate goal is to find the <code>"(My) Videos"</code> folder on Windows XP and Vista. On XP, by default, it's at <code>%HOMEPATH%\My Documents\My Videos</code>, and on Vista it's <code>%HOMEPATH%\Videos</code>. However, the user can relocate this folder. In the case, the <code>%HOMEPATH%\Videos</code> folder ceases to exists and is replaced by <code>%HOMEPATH%\Videos.lnk</code> which points to the new <code>"My Videos"</code> folder. And I want its absolute location.</p>
| 16 | 2008-12-29T04:31:27Z | 397,147 | <p>Alternatively, you could try using <a href="http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx" rel="nofollow">SHGetFolderPath()</a>. The following code might work, but I'm not on a Windows machine right now so I can't test it.</p>
<pre><code>import ctypes
shell32 = ctypes.windll.shell32
# allocate MAX_PATH bytes in buffer
video_folder_path = ctypes.create_string_buffer(260)
# 0xE is CSIDL_MYVIDEO
# 0 is SHGFP_TYPE_CURRENT
# If you want a Unicode path, use SHGetFolderPathW instead
if shell32.SHGetFolderPathA(None, 0xE, None, 0, video_folder_path) >= 0:
# success, video_folder_path now contains the correct path
else:
# error
</code></pre>
| 7 | 2008-12-29T04:53:05Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] |
Reading the target of a .lnk file in Python? | 397,125 | <p>I'm trying to read the target file/directory of a shortcut (<code>.lnk</code>) file from Python. Is there a headache-free way to do it? The <a href="http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf">.lnk spec [PDF]</a> is way over my head.
I don't mind using Windows-only APIs.</p>
<p>My ultimate goal is to find the <code>"(My) Videos"</code> folder on Windows XP and Vista. On XP, by default, it's at <code>%HOMEPATH%\My Documents\My Videos</code>, and on Vista it's <code>%HOMEPATH%\Videos</code>. However, the user can relocate this folder. In the case, the <code>%HOMEPATH%\Videos</code> folder ceases to exists and is replaced by <code>%HOMEPATH%\Videos.lnk</code> which points to the new <code>"My Videos"</code> folder. And I want its absolute location.</p>
| 16 | 2008-12-29T04:31:27Z | 571,573 | <p><strong>Create a shortcut using Python (via WSH)</strong></p>
<pre><code>import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()
</code></pre>
<p><br></p>
<p><strong>Read the Target of a Shortcut using Python (via WSH)</strong></p>
<pre><code>import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)
</code></pre>
| 23 | 2009-02-20T22:59:37Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] |
Reading the target of a .lnk file in Python? | 397,125 | <p>I'm trying to read the target file/directory of a shortcut (<code>.lnk</code>) file from Python. Is there a headache-free way to do it? The <a href="http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf">.lnk spec [PDF]</a> is way over my head.
I don't mind using Windows-only APIs.</p>
<p>My ultimate goal is to find the <code>"(My) Videos"</code> folder on Windows XP and Vista. On XP, by default, it's at <code>%HOMEPATH%\My Documents\My Videos</code>, and on Vista it's <code>%HOMEPATH%\Videos</code>. However, the user can relocate this folder. In the case, the <code>%HOMEPATH%\Videos</code> folder ceases to exists and is replaced by <code>%HOMEPATH%\Videos.lnk</code> which points to the new <code>"My Videos"</code> folder. And I want its absolute location.</p>
| 16 | 2008-12-29T04:31:27Z | 28,952,464 | <p>I know this is an older thread but I feel that there isn't much information on the method that uses the link specification as noted in the original question. </p>
<p>My shortcut target implementation could not use the win32com module and after a lot of searching, decided to come up with my own. Nothing else seemed to accomplish what I needed under my restrictions. Hopefully this will help other folks in this same situation.</p>
<p>It uses the binary structure Microsoft has provided for <a href="http://msdn.microsoft.com/en-us/library/dd871305.aspx" rel="nofollow">MS-SHLLINK</a>. </p>
<pre><code>import struct
target = ''
try:
with open(path, 'rb') as stream:
content = stream.read()
# skip first 20 bytes (HeaderSize and LinkCLSID)
# read the LinkFlags structure (4 bytes)
lflags = struct.unpack('I', content[0x14:0x18])[0]
position = 0x18
# if the HasLinkTargetIDList bit is set then skip the stored IDList
# structure and header
if (lflags & 0x01) == 1:
position = struct.unpack('H', content[0x4C:0x4E])[0] + 0x4E
last_pos = position
position += 0x04
# get how long the file information is (LinkInfoSize)
length = struct.unpack('I', content[last_pos:position])[0]
# skip 12 bytes (LinkInfoHeaderSize, LinkInfoFlags, and VolumeIDOffset)
position += 0x0C
# go to the LocalBasePath position
lbpos = struct.unpack('I', content[position:position+0x04])[0]
position = last_pos + lbpos
# read the string at the given position of the determined length
size= (length + last_pos) - position - 0x02
temp = struct.unpack('c' * size, content[position:position+size])
target = ''.join([chr(ord(a)) for a in temp])
except:
# could not read the file
pass
return target
</code></pre>
| 2 | 2015-03-09T21:55:13Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] |
Reading the target of a .lnk file in Python? | 397,125 | <p>I'm trying to read the target file/directory of a shortcut (<code>.lnk</code>) file from Python. Is there a headache-free way to do it? The <a href="http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf">.lnk spec [PDF]</a> is way over my head.
I don't mind using Windows-only APIs.</p>
<p>My ultimate goal is to find the <code>"(My) Videos"</code> folder on Windows XP and Vista. On XP, by default, it's at <code>%HOMEPATH%\My Documents\My Videos</code>, and on Vista it's <code>%HOMEPATH%\Videos</code>. However, the user can relocate this folder. In the case, the <code>%HOMEPATH%\Videos</code> folder ceases to exists and is replaced by <code>%HOMEPATH%\Videos.lnk</code> which points to the new <code>"My Videos"</code> folder. And I want its absolute location.</p>
| 16 | 2008-12-29T04:31:27Z | 36,706,549 | <p>I also realize this question is old, but I found the answers to be most relevant to my situation. </p>
<p>Like Jared's answer, I also could not use the win32com module. So Jared's use of the binary structure from <a href="https://msdn.microsoft.com/en-us/library/dd871305.aspx" rel="nofollow">MS-SHLLINK</a> got me part of the way there. I needed read shortcuts on both Windows and Linux, where the shortcuts are created on a samba share by Windows. Jared's implementation didn't quite work for me, I think only because I encountered some different variations on the shortcut format. But, it gave me the start I needed (thanks Jared).</p>
<p>So, here is a class named MSShortcut which expands on Jared's approach. However, the implementation is only Python3.4 and above, due to using some pathlib features added in Python3.4</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3
# Link Format from MS: https://msdn.microsoft.com/en-us/library/dd871305.aspx
# Need to be able to read shortcut target from .lnk file on linux or windows.
# Original inspiration from: http://stackoverflow.com/questions/397125/reading-the-target-of-a-lnk-file-in-python
from pathlib import Path, PureWindowsPath
import struct, sys, warnings
if sys.hexversion < 0x03040000:
warnings.warn("'{}' module requires python3.4 version or above".format(__file__), ImportWarning)
# doc says class id =
# 00021401-0000-0000-C000-000000000046
# requiredCLSID = b'\x00\x02\x14\x01\x00\x00\x00\x00\xC0\x00\x00\x00\x00\x00\x00\x46'
# Actually Getting:
requiredCLSID = b'\x01\x14\x02\x00\x00\x00\x00\x00\xC0\x00\x00\x00\x00\x00\x00\x46' # puzzling
class ShortCutError(RuntimeError):
pass
class MSShortcut():
"""
interface to Microsoft Shortcut Objects. Purpose:
- I need to be able to get the target from a samba shared on a linux machine
- Also need to get access from a Windows machine.
- Need to support several forms of the shortcut, as they seem be created differently depending on the
creating machine.
- Included some 'flag' types in external interface to help test differences in shortcut types
Args:
scPath (str): path to shortcut
Limitations:
- There are some omitted object properties in the implementation.
Only implemented / tested enough to recover the shortcut target information. Recognized omissions:
- LinkTargetIDList
- VolumeId structure (if captured later, should be a separate class object to hold info)
- Only captured environment block from extra data
- I don't know how or when some of the shortcut information is used, only captured what I recognized,
so there may be bugs related to use of the information
- NO shortcut update support (though might be nice)
- Implementation requires python 3.4 or greater
- Tested only with Unicode data on a 64bit little endian machine, did not consider potential endian issues
Not Debugged:
- localBasePath - didn't check if parsed correctly or not.
- commonPathSuffix
- commonNetworkRelativeLink
"""
def __init__(self, scPath):
"""
Parse and keep shortcut properties on creation
"""
self.scPath = Path(scPath)
self._clsid = None
self._lnkFlags = None
self._lnkInfoFlags = None
self._localBasePath = None
self._commonPathSuffix = None
self._commonNetworkRelativeLink = None
self._name = None
self._relativePath = None
self._workingDir = None
self._commandLineArgs = None
self._iconLocation = None
self._envTarget = None
self._ParseLnkFile(self.scPath)
@property
def clsid(self):
return self._clsid
@property
def lnkFlags(self):
return self._lnkFlags
@property
def lnkInfoFlags(self):
return self._lnkInfoFlags
@property
def localBasePath(self):
return self._localBasePath
@property
def commonPathSuffix(self):
return self._commonPathSuffix
@property
def commonNetworkRelativeLink(self):
return self._commonNetworkRelativeLink
@property
def name(self):
return self._name
@property
def relativePath(self):
return self._relativePath
@property
def workingDir(self):
return self._workingDir
@property
def commandLineArgs(self):
return self._commandLineArgs
@property
def iconLocation(self):
return self._iconLocation
@property
def envTarget(self):
return self._envTarget
@property
def targetPath(self):
"""
Args:
woAnchor (bool): remove the anchor (\\server\path or drive:) from returned path.
Returns:
a libpath PureWindowsPath object for combined workingDir/relative path
or the envTarget
Raises:
ShortCutError when no target path found in Shortcut
"""
target = None
if self.workingDir:
target = PureWindowsPath(self.workingDir)
if self.relativePath:
target = target / PureWindowsPath(self.relativePath)
else: target = None
if not target and self.envTarget:
target = PureWindowsPath(self.envTarget)
if not target:
raise ShortCutError("Unable to retrieve target path from MS Shortcut: shortcut = {}"
.format(str(self.scPath)))
return target
@property
def targetPathWOAnchor(self):
tp = self.targetPath
return tp.relative_to(tp.anchor)
def _ParseLnkFile(self, lnkPath):
with lnkPath.open('rb') as f:
content = f.read()
# verify size (4 bytes)
hdrSize = struct.unpack('I', content[0x00:0x04])[0]
if hdrSize != 0x4C:
raise ShortCutError("MS Shortcut HeaderSize = {}, but required to be = {}: shortcut = {}"
.format(hdrSize, 0x4C, str(lnkPath)))
# verify LinkCLSID id (16 bytes)
self._clsid = bytes(struct.unpack('B'*16, content[0x04:0x14]))
if self._clsid != requiredCLSID:
raise ShortCutError("MS Shortcut ClassID = {}, but required to be = {}: shortcut = {}"
.format(self._clsid, requiredCLSID, str(lnkPath)))
# read the LinkFlags structure (4 bytes)
self._lnkFlags = struct.unpack('I', content[0x14:0x18])[0]
#logger.debug("lnkFlags=0x%0.8x" % self._lnkFlags)
position = 0x4C
# if HasLinkTargetIDList bit, then position to skip the stored IDList structure and header
if (self._lnkFlags & 0x01):
idListSize = struct.unpack('H', content[position:position+0x02])[0]
position += idListSize + 2
# if HasLinkInfo, then process the linkinfo structure
if (self._lnkFlags & 0x02):
(linkInfoSize, linkInfoHdrSize, self._linkInfoFlags,
volIdOffset, localBasePathOffset,
cmnNetRelativeLinkOffset, cmnPathSuffixOffset) = struct.unpack('IIIIIII', content[position:position+28])
# check for optional offsets
localBasePathOffsetUnicode = None
cmnPathSuffixOffsetUnicode = None
if linkInfoHdrSize >= 0x24:
(localBasePathOffsetUnicode, cmnPathSuffixOffsetUnicode) = struct.unpack('II', content[position+28:position+36])
#logger.debug("0x%0.8X" % linkInfoSize)
#logger.debug("0x%0.8X" % linkInfoHdrSize)
#logger.debug("0x%0.8X" % self._linkInfoFlags)
#logger.debug("0x%0.8X" % volIdOffset)
#logger.debug("0x%0.8X" % localBasePathOffset)
#logger.debug("0x%0.8X" % cmnNetRelativeLinkOffset)
#logger.debug("0x%0.8X" % cmnPathSuffixOffset)
#logger.debug("0x%0.8X" % localBasePathOffsetUnicode)
#logger.debug("0x%0.8X" % cmnPathSuffixOffsetUnicode)
# if info has a localBasePath
if (self._linkInfoFlags & 0x01):
bpPosition = position + localBasePathOffset
# not debugged - don't know if this works or not
self._localBasePath = UnpackZ('z', content[bpPosition:])[0].decode('ascii')
#logger.debug("localBasePath: {}".format(self._localBasePath))
if localBasePathOffsetUnicode:
bpPosition = position + localBasePathOffsetUnicode
self._localBasePath = UnpackUnicodeZ('z', content[bpPosition:])[0]
self._localBasePath = self._localBasePath.decode('utf-16')
#logger.debug("localBasePathUnicode: {}".format(self._localBasePath))
# get common Path Suffix
cmnSuffixPosition = position + cmnPathSuffixOffset
self._commonPathSuffix = UnpackZ('z', content[cmnSuffixPosition:])[0].decode('ascii')
#logger.debug("commonPathSuffix: {}".format(self._commonPathSuffix))
if cmnPathSuffixOffsetUnicode:
cmnSuffixPosition = position + cmnPathSuffixOffsetUnicode
self._commonPathSuffix = UnpackUnicodeZ('z', content[cmnSuffixPosition:])[0]
self._commonPathSuffix = self._commonPathSuffix.decode('utf-16')
#logger.debug("commonPathSuffix: {}".format(self._commonPathSuffix))
# check for CommonNetworkRelativeLink
if (self._linkInfoFlags & 0x02):
relPosition = position + cmnNetRelativeLinkOffset
self._commonNetworkRelativeLink = CommonNetworkRelativeLink(content, relPosition)
position += linkInfoSize
# If HasName
if (self._lnkFlags & 0x04):
(position, self._name) = self.readStringObj(content, position)
#logger.debug("name: {}".format(self._name))
# get relative path string
if (self._lnkFlags & 0x08):
(position, self._relativePath) = self.readStringObj(content, position)
#logger.debug("relPath='{}'".format(self._relativePath))
# get working dir string
if (self._lnkFlags & 0x10):
(position, self._workingDir) = self.readStringObj(content, position)
#logger.debug("workingDir='{}'".format(self._workingDir))
# get command line arguments
if (self._lnkFlags & 0x20):
(position, self._commandLineArgs) = self.readStringObj(content, position)
#logger.debug("commandLineArgs='{}'".format(self._commandLineArgs))
# get icon location
if (self._lnkFlags & 0x40):
(position, self._iconLocation) = self.readStringObj(content, position)
#logger.debug("iconLocation='{}'".format(self._iconLocation))
# look for environment properties
if (self._lnkFlags & 0x200):
while True:
size = struct.unpack('I', content[position:position+4])[0]
#logger.debug("blksize=%d" % size)
if size==0: break
signature = struct.unpack('I', content[position+4:position+8])[0]
#logger.debug("signature=0x%0.8x" % signature)
# EnvironmentVariableDataBlock
if signature == 0xA0000001:
if (self._lnkFlags & 0x80): # unicode
self._envTarget = UnpackUnicodeZ('z', content[position+268:])[0]
self._envTarget = self._envTarget.decode('utf-16')
else:
self._envTarget = UnpackZ('z', content[position+8:])[0].decode('ascii')
#logger.debug("envTarget='{}'".format(self._envTarget))
position += size
def readStringObj(self, scContent, position):
"""
returns:
tuple: (newPosition, string)
"""
strg = ''
size = struct.unpack('H', scContent[position:position+2])[0]
#logger.debug("workingDirSize={}".format(size))
if (self._lnkFlags & 0x80): # unicode
size *= 2
strg = struct.unpack(str(size)+'s', scContent[position+2:position+2+size])[0]
strg = strg.decode('utf-16')
else:
strg = struct.unpack(str(size)+'s', scContent[position+2:position+2+size])[0].decode('ascii')
#logger.debug("strg='{}'".format(strg))
position += size + 2 # 2 bytes to account for CountCharacters field
return (position, strg)
class CommonNetworkRelativeLink():
def __init__(self, scContent, linkContentPos):
self._networkProviderType = None
self._deviceName = None
self._netName = None
(linkSize, flags, netNameOffset,
devNameOffset, self._networkProviderType) = struct.unpack('IIIII', scContent[linkContentPos:linkContentPos+20])
#logger.debug("netnameOffset = {}".format(netNameOffset))
if netNameOffset > 0x014:
(netNameOffsetUnicode, devNameOffsetUnicode) = struct.unpack('II', scContent[linkContentPos+20:linkContentPos+28])
#logger.debug("netnameOffsetUnicode = {}".format(netNameOffsetUnicode))
self._netName = UnpackUnicodeZ('z', scContent[linkContentPos+netNameOffsetUnicode:])[0]
self._netName = self._netName.decode('utf-16')
self._deviceName = UnpackUnicodeZ('z', scContent[linkContentPos+devNameOffsetUnicode:])[0]
self._deviceName = self._deviceName.decode('utf-16')
else:
self._netName = UnpackZ('z', scContent[linkContentPos+netNameOffset:])[0].decode('ascii')
self._deviceName = UnpackZ('z', scContent[linkContentPos+devNameOffset:])[0].decode('ascii')
@property
def deviceName(self):
return self._deviceName
@property
def netName(self):
return self._netName
@property
def networkProviderType(self):
return self._networkProviderType
def UnpackZ (fmt, buf) :
"""
Unpack Null Terminated String
"""
#logger.debug(bytes(buf))
while True :
pos = fmt.find ('z')
if pos < 0 :
break
z_start = struct.calcsize (fmt[:pos])
z_len = buf[z_start:].find(b'\0')
#logger.debug(z_len)
fmt = '%s%dsx%s' % (fmt[:pos], z_len, fmt[pos+1:])
#logger.debug("fmt='{}', len={}".format(fmt, z_len))
fmtlen = struct.calcsize(fmt)
return struct.unpack (fmt, buf[0:fmtlen])
def UnpackUnicodeZ (fmt, buf) :
"""
Unpack Null Terminated String
"""
#logger.debug(bytes(buf))
while True :
pos = fmt.find ('z')
if pos < 0 :
break
z_start = struct.calcsize (fmt[:pos])
# look for null bytes by pairs
z_len = 0
for i in range(z_start,len(buf),2):
if buf[i:i+2] == b'\0\0':
z_len = i-z_start
break
fmt = '%s%dsxx%s' % (fmt[:pos], z_len, fmt[pos+1:])
# logger.debug("fmt='{}', len={}".format(fmt, z_len))
fmtlen = struct.calcsize(fmt)
return struct.unpack (fmt, buf[0:fmtlen])
</code></pre>
<p>I hope this helps others as well.
Thanks</p>
| 0 | 2016-04-19T00:37:09Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,159 | <p>This likely goes back to the core concept that there should be one obvious way to do a task. Additional comment styles add unnecessary complications and could decrease readability.</p>
| 27 | 2008-12-29T05:04:11Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,160 | <p>Well, the triple-quotes are used as multiline comments in docstrings. And # comments are used as inline comments and people get use to it.</p>
<p>Most of script languages don't have multiline comments either. Maybe that's the cause?</p>
<p>See <a href="http://www.python.org/dev/peps/pep-0008/">PEP 0008</a>, section <em>Comments</em></p>
<p>And see if your Python editor offers some keyboard shortcut for block commenting. Emacs supports it, as well as Eclipse, presumably most of decent IDEs does.</p>
| 11 | 2008-12-29T05:05:00Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,161 | <p>I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments". </p>
<p>Guido has <a href="https://twitter.com/gvanrossum/status/112670605505077248">tweeted</a> about this,</p>
<blockquote>
<p>Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)</p>
</blockquote>
| 223 | 2008-12-29T05:06:00Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,192 | <p>Assume that they were just considered unnecessary. Since it's so easy to just type <code>#a comment</code>, multiline comments can just consist of many single line comments.</p>
<p>For <a href="http://en.wikipedia.org/wiki/HTML" rel="nofollow">HTML</a>, on the other hand, there's more of a need for multiliners. It's harder to keep typing <code><!--comments like this--></code>.</p>
| 0 | 2008-12-29T05:35:39Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,194 | <p>This is just a guess .. but</p>
<p>Because they are strings, they have some semantic value (the compiler doesn't get rid of them), therefore it makes sense for them to be used as docstrings. They actually become part of the <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">AST</a>, so extracting documentation becomes easier.</p>
| 0 | 2008-12-29T05:38:01Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,216 | <p>Because the # convention is a common one, and there really isn't anything you can do with a multiline comment that you can't with a #-sign comment. It's a historical accident, like the ancestry of <code>/* ... */</code> comments going back to PL/I,</p>
| 0 | 2008-12-29T06:01:33Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,786 | <p>Triple-quoted text should NOT be considered multi-line comments; by convention, they are <a href="http://www.python.org/dev/peps/pep-0257/#rationale">docstrings</a>. They should describe what your code does and how to use it, but not for things like commenting out blocks of code. </p>
<p>According to Guido, <a href="http://www.python.org/dev/peps/pep-0008/">multiline comments in Python are just contiguous single-line comments</a> (search for "block comments").</p>
<p>To comment blocks of code, I sometimes use the following pattern:</p>
<pre><code>if False:
# A bunch of code
</code></pre>
| 31 | 2008-12-29T14:16:05Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,889 | <pre><code># This
# is
# a
# multi-line
# comment
</code></pre>
<p>Use comment block or search and replace (s/^/#/g) in your editor to achieve this.</p>
| 3 | 2008-12-29T15:17:54Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 397,950 | <p>Multi-line comments are easily breakable. What if you have the following in a simple calculator program?</p>
<pre><code>operation = ''
print("Pick an operation: +-*/")
# Get user input here
</code></pre>
<p>Try to comment that with a multi-line comment:</p>
<pre><code>/*
operation = ''
print("Pick an operation: +-*/")
# Get user input here
*/
</code></pre>
<p>Oops, your string contains the end comment delimiter.</p>
| 59 | 2008-12-29T15:44:08Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 398,025 | <p>From <a href="http://www.python.org/dev/peps/pep-0020/">The Zen of Python</a>:</p>
<p>There should be one-- and preferably only one --obvious way to do it.</p>
| 8 | 2008-12-29T16:18:23Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 398,042 | <p>Personally my comment style in say Java is like</p>
<pre><code>/*
* My multi-line comment in Java
*/
</code></pre>
<p>So having single-line only comments isn't such a bad thing if your style is typical to the preceding example because in comparison you'd have</p>
<pre><code>#
# My multi-line comment in Python
#
</code></pre>
<p>VB.NET is also a language with single-line only commenting, and personally I find it annoying as comments end up looking less likes comments and more like some kind of quote</p>
<pre><code>'
' This is a VB.NET example
'
</code></pre>
<p>Single-line-only comments end up having less character-usage than multi-line comments, and are less likely to be escaped by some dodgy characters in a regex statement perhaps? I'd tend to agree with Ned though.</p>
| 4 | 2008-12-29T16:27:01Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 398,045 | <p>Besides, <a href="http://en.wikipedia.org/wiki/Amores_perros" rel="nofollow">multiline comments are a bitch</a>. Sorry to say, but regardless of the language, I don't use them for anything else than debugging purposes. Say you have code like this:</p>
<pre><code>void someFunction()
{
Something
/*Some comments*/
Something else
}
</code></pre>
<p>Then you find out that there is something in your code you can't fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:</p>
<pre><code>void someFunction()
{ /*
Something
/* Comments */
Something more*/
}
</code></pre>
<p>This is really irritating.</p>
| 0 | 2008-12-29T16:28:12Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 6,402,964 | <p>I remember reading about one guy who would put his multi-line comments into a triple-quoted variable:</p>
<pre><code>x = '''
This is my
super-long mega-comment.
Wow there are a lot of lines
going on here!
'''
</code></pre>
<p>This does take up a bit of memory, but it gives you multi-line comment functionality, and plus most editors will highlight the syntax for you :)</p>
<p>It's also easy to comment out code by simply wrapping it with </p>
<pre><code>x = '''
</code></pre>
<p>and</p>
<pre><code>'''
</code></pre>
| -1 | 2011-06-19T14:27:14Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 13,395,008 | <p>I solved this by downloading a macro for my text editor (TextPad) that lets me highlight lines and it then inserts # at the first of each line. A similar macro removes the #'s. Some may ask why multiline is necessary but it comes in handy when you're trying to "turn off" a block of code for debugging purposes.</p>
| 2 | 2012-11-15T09:54:37Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 19,171,859 | <p>Multiline comments using <strong><a href="http://en.wikipedia.org/wiki/IDLE_%28Python%29" rel="nofollow">IDLE</a></strong> on:</p>
<ul>
<li><p><strong>Mac OS X</strong>, after code selection, comment a block of code with <kbd>Ctrl</kbd>+<kbd>3</kbd> and uncomment using <kbd>Ctrl</kbd>+<kbd>4</kbd>.</p></li>
<li><p><strong>Windows</strong>, after code selection,
comment a block of code with <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>3</kbd> and uncomment using <kbd>Ctrl</kbd>+<kbd>At</kbd>+<kbd>4</kbd>.</p></li>
</ul>
| 0 | 2013-10-04T01:45:06Z | [
"python",
"comments",
"multiline"
] |
Why doesn't Python have multiline comments? | 397,148 | <p>OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,</p>
<pre><code>"""Hello, I am a
multiline comment"""
</code></pre>
<p>and </p>
<pre><code>'''Hello, I am a
multiline comment'''
</code></pre>
<p>But technically speaking these are strings, correct?</p>
<p>I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.</p>
| 194 | 2008-12-29T04:53:17Z | 29,478,739 | <p>To comment out a block of code in the <a href="https://www.jetbrains.com/pycharm/help/commenting-and-uncommenting-blocks-of-code.html" rel="nofollow">Pycharm</a> IDE:</p>
<ul>
<li>Code | Comment with Line Comment</li>
<li>Windows or Linux: <kbd>Ctrl</kbd> + <kbd>/</kbd></li>
<li>Mac OS: <kbd>Command</kbd> + <kbd>/</kbd></li>
</ul>
| 2 | 2015-04-06T20:02:59Z | [
"python",
"comments",
"multiline"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 397,305 | <p>The os.path module has a directory tree walking function as well. I've never run any sort of benchmarks on it, but you could give it a try. I'm not sure there's a faster way than os.walk/os.path.walk in Python, however.</p>
| 0 | 2008-12-29T08:01:08Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 397,539 | <p>Well, I would expect this to be heavily I/O bound task.
As such, optimizations on python side would be quite ineffective; the only optimization I could think of is some different way of accessing/listing files, in order to reduce the actual read from the file system.
This of course requires a deep knowledge of the file system, that I do not have, and I do not expect python's developer to have while implementing <code>os.walk</code>.</p>
<p>What about spawning a command prompt, and then issue 'dir' and parse the results?
It could be a bit an overkill, but with any luck, 'dir' is making some effort for such optimizations.</p>
| 3 | 2008-12-29T11:21:56Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 397,561 | <p>It seems as if os.walk has been <a href="http://mail.python.org/pipermail/python-list/2006-October/408667.html" rel="nofollow">considerably improved</a> in python 2.5, so you might check if you're running that version. </p>
<p>Other than that, <a href="http://randomfoo.net/blog/id/4214" rel="nofollow">someone has already compared the speed of os.walk to ls</a> and noticed a clear advance of the latter, but not in a range that would actually justify using it.</p>
| 3 | 2008-12-29T11:36:25Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 397,647 | <p>When you look at the code for <code>os.walk</code>, you'll see that there's not much fat to be trimmed.</p>
<p>For example, the following is only a hair faster than os.walk.</p>
<pre><code>import os
import stat
listdir= os.listdir
pathjoin= os.path.join
fstat= os.stat
is_dir= stat.S_ISDIR
is_reg= stat.S_ISREG
def yieldFiles( path ):
for f in listdir(path):
nm= pathjoin( path, f )
s= fstat( nm ).st_mode
if is_dir( s ):
for sub in yieldFiles( nm ):
yield sub
elif is_reg( s ):
yield f
else:
pass # ignore these
</code></pre>
<p>Consequently, the overheads must he in the <code>os</code> module itself. You'll have to resort to making direct Windows API calls.</p>
<p>Look at the <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">Python for Windows Extensions</a>.</p>
| 1 | 2008-12-29T12:38:38Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 398,092 | <p>You might want to look at the code for some Python version control systems like Mercurial or Bazaar. They have devoted a lot of time to coming up with ways to quickly traverse a directory tree and detect changes (or "finding basic stats about the files").</p>
| 2 | 2008-12-29T16:48:42Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 398,436 | <p>I'm wondering if you might want to group your I/O operations. </p>
<p>For instance, if you're walking a dense directory tree with thousands of files, you might try experimenting with walking the entire tree and storing all the file locations, and then looping through the (in-memory) locations and getting file statistics. </p>
<p>If your OS stores these two data in different locations (directory structure in one place, file stats in another), then this might be a significant optimization. </p>
<p>Anyway, that's something I'd try before digging further.</p>
| 1 | 2008-12-29T19:33:44Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 401,894 | <p>This is only partial help, more like pointers; however:</p>
<p>I believe you need to do the following:</p>
<pre><code>fp = open("C:/$MFT", "rb")
</code></pre>
<p>using an account that includes SYSTEM permissions, because even as an admin, you can't open the "Master File Table" (kind of an inode table) of an NTFS filesystem. After you succeed in that, then you'll just have to locate information on the web that explains the structure of each file record (I believe it's commonly 1024 bytes per on-disk file, which includes the file's primary pathname) and off you go for super-high speeds of disk structure reading.</p>
| 0 | 2008-12-31T00:00:04Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 19,715,067 | <p>Use scandir python module (formerly betterwalk) on github by Ben Hoyt.</p>
<p><a href="http://github.com/benhoyt/scandir" rel="nofollow">http://github.com/benhoyt/scandir</a></p>
<p>It is much faster than python walk, but uses the same syntax. Just import scandir and change os.walk() to scandir.walk(). That's it. It is the fastest way to traverse directories and files in python. </p>
| 2 | 2013-10-31T19:29:49Z | [
"python",
"windows"
] |
Fast file/directory scan method for windows? | 397,293 | <p>I'm looking for a high performance method or library for scanning all files on disk or in a given directory and grabbing their basic stats - filename, size, and modification date. </p>
<p>I've written a python program that uses <code>os.walk</code> along with <code>os.path.getsize</code> to get the file list, and it works fine, but is not particularly fast. I noticed one of the freeware programs I had downloaded accomplished the same scan much faster than my program. </p>
<p>Any ideas for speeding up the file scan? Here's my python code, but keep in mind that I'm not at all married to os.walk and perfectly willing to use others APIs (including windows native APIs) if there are better alternatives.</p>
<pre><code>for root, dirs, files in os.walk(top, topdown=False):
for name in files:
...
</code></pre>
<p>I should also note I realize the python code probably can't be sped up that much; I'm particularly interested in any native APIs that provide better speed.</p>
| 3 | 2008-12-29T07:47:11Z | 32,559,545 | <p>Python 3.5 just introduced <a href="https://docs.python.org/dev/library/os.html#os.scandir" rel="nofollow"><code>os.scandir</code></a> (see <a href="https://www.python.org/dev/peps/pep-0471/#abstract" rel="nofollow">PEP-0471</a>) which avoids a number of non-required system calls such as <code>stat()</code> and <code>GetFileAttributes()</code> to provide a significantly quicker file-system iterator.</p>
<p><code>os.walk()</code> will now be implemented using <code>os.scandir()</code> as its iterator, and so you should see potentially large performance improvements whilst continuing to use <code>os.walk()</code>.</p>
<hr>
<p>Example usage:</p>
<pre><code>for entry in os.scandir(path):
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
</code></pre>
| 1 | 2015-09-14T07:42:06Z | [
"python",
"windows"
] |
Using external GUI libraries to make user interfaces in Autodesk Maya | 397,337 | <p>I develop tools in Autodesk Maya. Many of the tools I build have simple windowed GUIs for the animators and modellers to use. These GUIs often contain what you'd normally expect to see in any basic window; labels, lists, menus, buttons, textfields, etc. However, there are limitations to the complexity of the UIs you can build with the available tools, specifically in the types of available widgets.</p>
<p>I'm interested in using some of the more advanced wxPython widgets such as the ListView (grid), Tree, etc. This would involve using a complete wxFrame (window) to display the whole UI, which would essentially mean that window would no longer be tied to Maya. Not a deal breaker, but it means when Maya is minimized, the window won't follow suit.</p>
<p>I've tried something like this before with tkinter as a test, but found that it needed a MainLoop to run in its own thread. This is logical, but in my case, it conflicts with Maya's own thread, essentially making Maya hang until the window is closed. This is due to the fact that Maya runs all scripts, be they MEL or Python, in a single thread that the main Maya GUI shares. This is to prevent one script from, say, deleting an object while another script is trying to do work on the same object.</p>
<p>wxPython has this same "mainloop" methodolgy. I'm wondering if there's any way around it so that it can work within Maya?</p>
| 7 | 2008-12-29T08:41:12Z | 398,469 | <p>I don't know if there is a way around a mainloop for the gui, since it is needed to handle all event chains and redraw queues. </p>
<p>But there are several means of inter-process communication, like pipes or semaphores. Maybe it is an option to split your Maya extension into the actual plugin, being tight into maya, and a separate application for the gui. These two could use such means to communicate and exchange model information between plugin and gui.
I'm not sure, however, if I can really recommend this approach because it very much complicates the application.</p>
<p>You could have a look at IPython, an interactive Python shell, whose dev team has put some effort into integrating it with wxPython. They have some way of interrupting the event loop and hooking into it to do their own stuff.</p>
| 0 | 2008-12-29T19:41:38Z | [
"python",
"scripting",
"wxpython",
"wxwidgets",
"maya"
] |
Using external GUI libraries to make user interfaces in Autodesk Maya | 397,337 | <p>I develop tools in Autodesk Maya. Many of the tools I build have simple windowed GUIs for the animators and modellers to use. These GUIs often contain what you'd normally expect to see in any basic window; labels, lists, menus, buttons, textfields, etc. However, there are limitations to the complexity of the UIs you can build with the available tools, specifically in the types of available widgets.</p>
<p>I'm interested in using some of the more advanced wxPython widgets such as the ListView (grid), Tree, etc. This would involve using a complete wxFrame (window) to display the whole UI, which would essentially mean that window would no longer be tied to Maya. Not a deal breaker, but it means when Maya is minimized, the window won't follow suit.</p>
<p>I've tried something like this before with tkinter as a test, but found that it needed a MainLoop to run in its own thread. This is logical, but in my case, it conflicts with Maya's own thread, essentially making Maya hang until the window is closed. This is due to the fact that Maya runs all scripts, be they MEL or Python, in a single thread that the main Maya GUI shares. This is to prevent one script from, say, deleting an object while another script is trying to do work on the same object.</p>
<p>wxPython has this same "mainloop" methodolgy. I'm wondering if there's any way around it so that it can work within Maya?</p>
| 7 | 2008-12-29T08:41:12Z | 399,413 | <p>I'm not sure if this is germane, but some googling turns up that PyQt is pretty popular inside of Maya. You could try the technique <a href="http://www.highend3d.com/boards/lofiversion/index.php/t236041.html" rel="nofollow">here</a> or <a href="http://www.highend3d.com/boards/index.php?showtopic=242116" rel="nofollow">here</a> (explained <a href="http://groups.google.com/group/xsi_list/msg/dd500eb2420f3417?" rel="nofollow">here</a> with source code) of creating a new threadloop via Maya and executing inside of that. It seems Maya has a module included that sets up a new thread object, with a QApplication inside it:</p>
<pre><code>def initializePumpThread():
global pumpedThread
global app
if pumpedThread == None:
app = QtGui.QApplication(sys.argv)
pumpedThread = threading.Thread(target = pumpQt, args = ())
pumpedThread.start()
</code></pre>
<p>and then sets up a function to process the Qt events:</p>
<pre><code>def pumpQt():
global app
def processor():
app.processEvents()
while 1:
time.sleep(0.01)
utils.executeDeferred( processor )
</code></pre>
<p>You can probably do something similar with wxPython as well. (utils.executeDeferred is a Maya function.) Be sure to check out how to create a <a href="http://wiki.wxpython.org/Non-Blocking%20Gui" rel="nofollow">non-blocking GUI</a> on the wxPython wiki. Instead of processEvents(), you'll want to set up an event loop and check for "Pending" events inside the (hopefully renamed?) pumpQt function above. (The wxPython source has a <a href="http://cvs.wxwidgets.org/viewcvs.cgi/wxWidgets/wxPython/samples/mainloop/mainloop.py" rel="nofollow">Python implementation</a> of MainLoop.) Likely this should be done through the app.Yield() function, but I'm not sure.</p>
<pre><code>def pumpWx():
global app
def processor():
app.Yield(True)
while 1:
time.sleep(0.01)
utils.executeDeferred( processor )
def initializePumpThread():
global pumpedThread
global app
if pumpedThread == None:
app = wx.App(False)
pumpedThread = threading.Thread(target = pumpWx, args = ())
pumpedThread.start()
</code></pre>
<p>The wxPython docs <a href="http://www.wxpython.org/docs/api/wx-module.html#SafeYield" rel="nofollow">indicate SafeYield()</a> is preferred. Again, this seems like it could be a first step, but I'm not sure it will work and not just crash horribly. (There's some discussion about what you want to do on the <a href="http://www.nabble.com/app.MainLoop-vs.-Pending-Dispatch-td17921845.html" rel="nofollow">wxPython mailing list</a> but it's from a few minor versions of wx ago.) There is also some indication in various forums that this technique causes problems with keyboard input. You might also try doing:</p>
<pre><code>def processor():
while app.Pending(): app.Dispatch()
</code></pre>
<p>to deal with the current list of events.</p>
<p>Good luck!</p>
| 2 | 2008-12-30T02:48:01Z | [
"python",
"scripting",
"wxpython",
"wxwidgets",
"maya"
] |
Using external GUI libraries to make user interfaces in Autodesk Maya | 397,337 | <p>I develop tools in Autodesk Maya. Many of the tools I build have simple windowed GUIs for the animators and modellers to use. These GUIs often contain what you'd normally expect to see in any basic window; labels, lists, menus, buttons, textfields, etc. However, there are limitations to the complexity of the UIs you can build with the available tools, specifically in the types of available widgets.</p>
<p>I'm interested in using some of the more advanced wxPython widgets such as the ListView (grid), Tree, etc. This would involve using a complete wxFrame (window) to display the whole UI, which would essentially mean that window would no longer be tied to Maya. Not a deal breaker, but it means when Maya is minimized, the window won't follow suit.</p>
<p>I've tried something like this before with tkinter as a test, but found that it needed a MainLoop to run in its own thread. This is logical, but in my case, it conflicts with Maya's own thread, essentially making Maya hang until the window is closed. This is due to the fact that Maya runs all scripts, be they MEL or Python, in a single thread that the main Maya GUI shares. This is to prevent one script from, say, deleting an object while another script is trying to do work on the same object.</p>
<p>wxPython has this same "mainloop" methodolgy. I'm wondering if there's any way around it so that it can work within Maya?</p>
| 7 | 2008-12-29T08:41:12Z | 30,247,511 | <p>The best way to go is creating a QWidget with what you need, and using it from within a MPxCommand thru the C++ API. That way you also have the chance to inject complete custom editors into Maya via scriptedPanels.</p>
<p>But if you're bound to Python, pyQt is the way to go.</p>
| 0 | 2015-05-14T21:18:00Z | [
"python",
"scripting",
"wxpython",
"wxwidgets",
"maya"
] |
Python Proxy Script | 398,385 | <p>I'm writing a simple python script so I can test my websites from a different ip address.</p>
<p>The url of a page is given in the querystring, the script fetches the page and displays it to the user. The code below is used to rewrite the tags that contain urls but I don't think it's complete/totally correct.</p>
<pre><code>def rel2abs(rel_url, base=loc):
return urlparse.urljoin(base, rel_url)
def is_proxy_else_abs(tag, attr):
if tag in ('a',):
return True
if tag in ('form', 'img', 'link') and attr in ('href', 'src', 'action', 'background'):
return False
def repl(matchobj):
if is_proxy_else_abs(matchobj.group(1).lower(), matchobj.group(3).lower()):
return r'<%s %s %s="http://%s?%s" ' %(proxy_script_url, matchobj.group(1), matchobj.group(2), matchobj.group(3), urllib.urlencode({'loc':rel2abs(matchobj.group(5))}))
else:
return r'<%s %s %s="%s" ' %(matchobj.group(1), matchobj.group(2), matchobj.group(3), rel2abs(matchobj.group(5)))
def fix_urls(page):
get_link_re = re.compile(r"""<(a|form|img|link) ([^>]*?)(href|src|action|background)\s*=\s*("|'?)([^>]*?)\4""", re.I|re.DOTALL)
page = get_link_re.sub(repl, page)
return page
</code></pre>
<p>The idea is that 'a' tag's href attributes should be routed through the proxy script, but css, javascript, images, forms etc should not be, so these have to be made absolute if they are relative in the original page.</p>
<p>The problem is the code doesn't always work, css can be written in a number of ways etc. Is there a more comprehensive regex I can use?</p>
| 0 | 2008-12-29T19:19:08Z | 398,536 | <p>Please read other postings here about parsing HTML. For example <a href="http://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup">http://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup</a> and <a href="http://stackoverflow.com/questions/71151/html-parser-in-python">http://stackoverflow.com/questions/71151/html-parser-in-python</a>.</p>
<p>Use Beautiful Soup, not regular expressions.</p>
| 3 | 2008-12-29T20:09:34Z | [
"python",
"proxy"
] |
Split by \b when your regex engine doesn't support it | 398,560 | <p>How can I split by word boundary in a regex engine that doesn't support it?</p>
<p>python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.</p>
<p>example input:</p>
<pre><code>"hello, foo"
</code></pre>
<p>expected output:</p>
<pre><code>['hello', ', ', 'foo']
</code></pre>
<p>actual python output:</p>
<pre><code>>>> re.compile(r'\b').split('hello, foo')
['hello, foo']
</code></pre>
| 4 | 2008-12-29T20:22:14Z | 398,570 | <p>Try </p>
<pre><code>>>> re.compile(r'\W\b').split('hello, foo')
['hello,', 'foo']
</code></pre>
<p>This splits at the non-word characted before a boundry.
Your example has nothing to split on.</p>
| 0 | 2008-12-29T20:31:15Z | [
"python",
"regex"
] |
Split by \b when your regex engine doesn't support it | 398,560 | <p>How can I split by word boundary in a regex engine that doesn't support it?</p>
<p>python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.</p>
<p>example input:</p>
<pre><code>"hello, foo"
</code></pre>
<p>expected output:</p>
<pre><code>['hello', ', ', 'foo']
</code></pre>
<p>actual python output:</p>
<pre><code>>>> re.compile(r'\b').split('hello, foo')
['hello, foo']
</code></pre>
| 4 | 2008-12-29T20:22:14Z | 398,584 | <p>(\W+) can give you the expected output:</p>
<pre><code>>>> re.compile(r'(\W+)').split('hello, foo')
['hello', ', ', 'foo']
</code></pre>
| 9 | 2008-12-29T20:38:26Z | [
"python",
"regex"
] |
Split by \b when your regex engine doesn't support it | 398,560 | <p>How can I split by word boundary in a regex engine that doesn't support it?</p>
<p>python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.</p>
<p>example input:</p>
<pre><code>"hello, foo"
</code></pre>
<p>expected output:</p>
<pre><code>['hello', ', ', 'foo']
</code></pre>
<p>actual python output:</p>
<pre><code>>>> re.compile(r'\b').split('hello, foo')
['hello, foo']
</code></pre>
| 4 | 2008-12-29T20:22:14Z | 398,589 | <p>Ok I figured it out:</p>
<p>Put the split pattern in capturing parens and will be included in the output. You can use either \w+ or \W+:</p>
<pre><code>>>> re.compile(r'(\w+)').split('hello, foo')
['', 'hello', ', ', 'foo', '']
</code></pre>
<p>To get rid of the empty results, pass it through filter() with None as the filter function, which will filter anything that doesn't evaluate to true:</p>
<pre><code>>>> filter(None, re.compile(r'(\w+)').split('hello, foo'))
['hello', ', ', 'foo']
</code></pre>
<p>Edit: CMS points out that if you use \W+ you don't need to use filter()</p>
| 1 | 2008-12-29T20:39:05Z | [
"python",
"regex"
] |
Split by \b when your regex engine doesn't support it | 398,560 | <p>How can I split by word boundary in a regex engine that doesn't support it?</p>
<p>python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.</p>
<p>example input:</p>
<pre><code>"hello, foo"
</code></pre>
<p>expected output:</p>
<pre><code>['hello', ', ', 'foo']
</code></pre>
<p>actual python output:</p>
<pre><code>>>> re.compile(r'\b').split('hello, foo')
['hello, foo']
</code></pre>
| 4 | 2008-12-29T20:22:14Z | 398,590 | <p>Interesting. So far most RE engines I tried do this split.</p>
<p>I played a bit and found that <code>re.compile(r'(\W+)').split('hello, foo')</code> is giving the output you expected... Not sure if that's reliable, though.</p>
| 0 | 2008-12-29T20:39:57Z | [
"python",
"regex"
] |
Split by \b when your regex engine doesn't support it | 398,560 | <p>How can I split by word boundary in a regex engine that doesn't support it?</p>
<p>python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.</p>
<p>example input:</p>
<pre><code>"hello, foo"
</code></pre>
<p>expected output:</p>
<pre><code>['hello', ', ', 'foo']
</code></pre>
<p>actual python output:</p>
<pre><code>>>> re.compile(r'\b').split('hello, foo')
['hello, foo']
</code></pre>
| 4 | 2008-12-29T20:22:14Z | 398,768 | <p>One can also use re.findall() for this:</p>
<pre><code>>>> re.findall(r'.+?\b', 'hello, foo')
['hello', ', ', 'foo']
</code></pre>
| 2 | 2008-12-29T21:41:31Z | [
"python",
"regex"
] |
Why can't I subclass datetime.date? | 399,022 | <p>Why doesn't the following work (Python 2.5.2)?</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
</code></pre>
<p>I wanted to create a class that was just like <code>datetime.date</code>, but with a different <code>__init__</code> function. Apparently my function never gets called. Instead the original <code>datetime.date.__init__</code> is called and fails because that expects 3 arguments and I am passing in one.</p>
<p>What's going on here? And is this a clue?</p>
<pre><code>>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
</code></pre>
<p>Thanks!</p>
| 15 | 2008-12-29T23:08:18Z | 399,033 | <p>Here's the answer, and a possible solution (use a function or strptime instead of subclassing)</p>
<p><a href="http://www.mail-archive.com/[email protected]/msg192783.html" rel="nofollow">http://www.mail-archive.com/[email protected]/msg192783.html</a></p>
| 3 | 2008-12-29T23:12:44Z | [
"python",
"oop",
"datetime",
"subclass"
] |
Why can't I subclass datetime.date? | 399,022 | <p>Why doesn't the following work (Python 2.5.2)?</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
</code></pre>
<p>I wanted to create a class that was just like <code>datetime.date</code>, but with a different <code>__init__</code> function. Apparently my function never gets called. Instead the original <code>datetime.date.__init__</code> is called and fails because that expects 3 arguments and I am passing in one.</p>
<p>What's going on here? And is this a clue?</p>
<pre><code>>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
</code></pre>
<p>Thanks!</p>
| 15 | 2008-12-29T23:08:18Z | 399,061 | <p>You should probably use a factory function instead of creating a subclass:</p>
<pre><code>def first_day_of_the_year(year):
return datetime.date(year, 1, 1)
</code></pre>
| 0 | 2008-12-29T23:22:00Z | [
"python",
"oop",
"datetime",
"subclass"
] |
Why can't I subclass datetime.date? | 399,022 | <p>Why doesn't the following work (Python 2.5.2)?</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
</code></pre>
<p>I wanted to create a class that was just like <code>datetime.date</code>, but with a different <code>__init__</code> function. Apparently my function never gets called. Instead the original <code>datetime.date.__init__</code> is called and fails because that expects 3 arguments and I am passing in one.</p>
<p>What's going on here? And is this a clue?</p>
<pre><code>>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
</code></pre>
<p>Thanks!</p>
| 15 | 2008-12-29T23:08:18Z | 399,418 | <p>You're function isn't being bypassed; Python just never gets to the point where it would call it. Since datetime is implemented in C, it does its initialization in <code>datetime.__new__</code> not <code>datetime.__init__</code>. This is because datetime is immutable. You could presumably get around this by overriding <code>__new__</code> instead of <code>__init__</code>. But as other people have suggested, the best way is probably not subclassing datetime at all.</p>
| 1 | 2008-12-30T02:50:29Z | [
"python",
"oop",
"datetime",
"subclass"
] |
Why can't I subclass datetime.date? | 399,022 | <p>Why doesn't the following work (Python 2.5.2)?</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
</code></pre>
<p>I wanted to create a class that was just like <code>datetime.date</code>, but with a different <code>__init__</code> function. Apparently my function never gets called. Instead the original <code>datetime.date.__init__</code> is called and fails because that expects 3 arguments and I am passing in one.</p>
<p>What's going on here? And is this a clue?</p>
<pre><code>>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
</code></pre>
<p>Thanks!</p>
| 15 | 2008-12-29T23:08:18Z | 399,712 | <p>You can <strong>wrap</strong> it and add extended functionality to your wrapper.</p>
<p>Here is an example:</p>
<pre><code>class D2(object):
def __init__(self, *args, **kwargs):
self.date_object = datetime.date(*args, **kwargs)
def __getattr__(self, name):
return getattr(self.date_object, name)
</code></pre>
<p>And here is how it works:</p>
<pre><code>>>> d = D2(2005, 10, 20)
>>> d.weekday()
3
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
'__weakref__', 'date_object']
>>> d.strftime('%d.%m.%Y')
'20.10.2005'
>>>
</code></pre>
<p>Note that <code>dir()</code> doesn't list <code>datetime.date</code>s attributes.</p>
| 0 | 2008-12-30T07:21:29Z | [
"python",
"oop",
"datetime",
"subclass"
] |
Why can't I subclass datetime.date? | 399,022 | <p>Why doesn't the following work (Python 2.5.2)?</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
</code></pre>
<p>I wanted to create a class that was just like <code>datetime.date</code>, but with a different <code>__init__</code> function. Apparently my function never gets called. Instead the original <code>datetime.date.__init__</code> is called and fails because that expects 3 arguments and I am passing in one.</p>
<p>What's going on here? And is this a clue?</p>
<pre><code>>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
</code></pre>
<p>Thanks!</p>
| 15 | 2008-12-29T23:08:18Z | 400,583 | <p>Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The <code>__init__</code> method does nothing because they are <em>immutable</em> objects, therefore the constructor (<code>__new__</code>) should do all the work. You would see the same behavior subclassing int, str, etc.</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __new__(cls, year):
return datetime.date.__new__(cls, year, 1, 1)
>>> D(2008)
D(2008, 1, 1)
</code></pre>
| 31 | 2008-12-30T15:36:32Z | [
"python",
"oop",
"datetime",
"subclass"
] |
Why can't I subclass datetime.date? | 399,022 | <p>Why doesn't the following work (Python 2.5.2)?</p>
<pre><code>>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
</code></pre>
<p>I wanted to create a class that was just like <code>datetime.date</code>, but with a different <code>__init__</code> function. Apparently my function never gets called. Instead the original <code>datetime.date.__init__</code> is called and fails because that expects 3 arguments and I am passing in one.</p>
<p>What's going on here? And is this a clue?</p>
<pre><code>>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
</code></pre>
<p>Thanks!</p>
| 15 | 2008-12-29T23:08:18Z | 402,024 | <p>Please read the Python reference on <a href="http://www.python.org/doc/current/reference/datamodel.html"><em>Data model</em></a>, especially about the <code>__new__</code> <a href="http://www.python.org/doc/current/reference/datamodel.html#object.__new__">special method</a>.</p>
<p>Excerpt from that page (my italics):</p>
<blockquote>
<p><code>__new__()</code> is intended mainly to allow subclasses of <em>immutable</em> types (like int, str, or tuple) to <em>customize instance creation</em>. It is also commonly overridden in custom metaclasses in order to customize class creation.</p>
</blockquote>
<p><code>datetime.datetime</code> is also an immutable type.</p>
<p>PS If you think that:</p>
<ul>
<li>an object implemented in C cannot be subclassed, or</li>
<li><code>__init__</code> doesn't get called for C implemented objects, only <code>__new__</code></li>
</ul>
<p>then please try it:</p>
<pre><code>>>> import array
>>> array
<module 'array' (built-in)>
>>> class A(array.array):
def __init__(self, *args):
super(array.array, self).__init__(*args)
print "init is fine for objects implemented in C"
>>> a=A('c')
init is fine for objects implemented in C
>>>
</code></pre>
| 8 | 2008-12-31T01:19:50Z | [
"python",
"oop",
"datetime",
"subclass"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 399,082 | <pre><code>a[4::-1]
</code></pre>
<p>Example:</p>
<pre><code>Python 2.6 (r26:66714, Dec 4 2008, 11:34:15)
[GCC 4.0.1 (Apple Inc. build 5488)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[4:0:-1]
[4, 3, 2, 1]
>>> a[4::-1]
[4, 3, 2, 1, 0]
>>>
</code></pre>
<p>The reason is that the second term is interpreted as "while not index ==". Leaving it out is "while index in range".</p>
| 0 | 2008-12-29T23:33:18Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 399,089 | <p>I believe that the following doesn't satisfy you:</p>
<pre><code>def getReversedList(aList, end, start, step):
if step < 0 and start == 0:
return aList[end::step]
return aList[end:start:step]
</code></pre>
<p>or does it? :-)</p>
| 1 | 2008-12-29T23:38:30Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 399,107 | <p>Ok, I think this is probably as good as I will get it. Thanks to Abgan for sparking the idea. This relies on the fact that None in a slice is treated as if it were a missing parameter. Anyone got anything better?</p>
<pre><code>def getReversedList(aList, end, start, step):
return aList[end:start if start!=-1 else None:step]
</code></pre>
<p><em>edit: check for <code>start==-1</code>, not <code>0</code></em></p>
<p>This is still not ideal, because you're clobbering the usual behavior of -1. It seems the problem here is two overlapping definitions of what's supposed to happen. Whoever wins takes away otherwise valid invocations looking for the other intention.</p>
| 2 | 2008-12-29T23:44:35Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 399,176 | <pre><code>[ A[b] for b in range(end,start,stride) ]
</code></pre>
<p>Slower, however you can use negative indices, so this should work:</p>
<pre><code>[ A[b] for b in range(9, -1, -1) ]
</code></pre>
<p>I realize this isn't using slices, but thought I'd offer the solution anyway if using slices specifically for getting the result isn't a priority.</p>
| 2 | 2008-12-30T00:10:05Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 400,080 | <blockquote>
<p><a href="http://stackoverflow.com/questions/399067/extended-slice-that-goes-to-beginning-of-sequence-with-negative-stride#399082">But</a> you can't use that if you are
storing your indices in variables for
example.</p>
</blockquote>
<p>Is this satisfactory?</p>
<pre><code>>>> a = range(10)
>>> start = 0
>>> end = 4
>>> a[4:start-1 if start > 0 else None:-1]
[4, 3, 2, 1, 0]
</code></pre>
| 1 | 2008-12-30T11:41:43Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 400,118 | <p>It is error-prone to change the semantics of <code>start</code> and <code>stop</code>. Use <code>None</code> or <code>-(len(a) + 1)</code> instead of <code>0</code> or <code>-1</code>. The semantics is not arbitrary. See Edsger W. Dijkstra's article <a href="http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html" rel="nofollow">"Why numbering should start at zero"</a>.</p>
<pre><code>>>> a = range(10)
>>> start, stop, step = 4, None, -1
</code></pre>
<p>Or </p>
<pre><code>>>> start, stop, step = 4, -(len(a) + 1), -1
>>> a[start:stop:step]
[4, 3, 2, 1, 0]
</code></pre>
<p>Or</p>
<pre><code>>>> s = slice(start, stop, step)
>>> a[s]
[4, 3, 2, 1, 0]
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#common-sequence-operations" rel="nofollow">When <code>s</code> is a sequence the negative indexes in <code>s[i:j:k]</code> are treated specially</a>:</p>
<blockquote>
<p>If <code>i</code> or <code>j</code> is negative, the index is relative to the end of the string:
<code>len(s) + i</code> or <code>len(s) + j</code> is substituted. But note that <code>-0</code> is still <code>0</code>.</p>
</blockquote>
<p>that is why <code>len(range(10)[4:-1:-1]) == 0</code> because it is equivalent to <code>range(10)[4:9:-1]</code>.</p>
| 5 | 2008-12-30T12:06:23Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 400,473 | <p>As you say very few people fully understand everything that you can do with extended slicing, so unless you really need the extra performance I'd do it the "obvious" way:</p>
<p><code>
rev_subset = reversed(data[start:stop])
</code></p>
| 1 | 2008-12-30T15:01:08Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 4,599,442 | <p>I know this is an old question, but in case someone like me is looking for answers:</p>
<pre><code>>>> A[5-1::-1]
[4, 3, 2, 1, 0]
>>> A[4:1:-1]
[4, 3, 2]
</code></pre>
| 0 | 2011-01-04T23:17:45Z | [
"python",
"list",
"slice"
] |
Extended slice that goes to beginning of sequence with negative stride | 399,067 | <p>Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.</p>
<p>In python, you can index lists using slice notation. Here's an example:</p>
<pre><code>>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
</code></pre>
<p>You can also include a stride, which acts like a "step":</p>
<pre><code>>>> A[0:5:2]
[0, 2, 4]
</code></pre>
<p>The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:</p>
<pre><code>>>> A[5:0:-1]
[5, 4, 3, 2, 1]
</code></pre>
<p>But wait! I wanted to see <code>[4, 3, 2, 1, 0]</code>. Oh, I see, I need to decrement the start and end indices:</p>
<pre><code>>>> A[4:-1:-1]
[]
</code></pre>
<p>What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:</p>
<pre><code>>>> A[4::-1]
[4, 3, 2, 1, 0]
</code></pre>
<p>But you can't use this in all cases. For example, in a method that's been passed indices. </p>
<h2>My question is:</h2>
<p>Is there any good pythonic way of using extended slices with negative strides <em>and explicit start and end indices</em> that include the first element of a sequence?</p>
<p>This is what I've come up with so far, but it seems unsatisfying.</p>
<pre><code>>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
</code></pre>
| 11 | 2008-12-29T23:26:41Z | 4,599,638 | <p>You can use a <code>slice(start, stop, step)</code> object, which is such that</p>
<pre><code>s=slice(start, stop, step)
print a[s]
</code></pre>
<p>is the same as</p>
<pre><code>print a[start : stop : step]
</code></pre>
<p>and, moreover, you can set any of the arguments to <code>None</code> to indicate nothing in between the colons. So in the case you give, you can use <code>slice(4, None, -1)</code>.</p>
| 0 | 2011-01-04T23:52:24Z | [
"python",
"list",
"slice"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 399,140 | <p>Incorrect port maybe? I'm using <strong>587</strong> for <strong>smtp.gmail.com</strong> and it works.</p>
| 1 | 2008-12-29T23:59:19Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 399,142 | <p>You should check your port, I'm not sure that google's SMTP port is 65, that would explain the timeout. </p>
<p>Modify your sources as such:</p>
<p>smtplib.SMTP_SSL('smtp.google.com', 465)</p>
<p>If, however, you are certain that it ought to work and it doesn't, it appears that there are some problems with smtplib.SMTP_SSL, and there's an available patch for it <a href="http://bugs.python.org/issue4470" rel="nofollow" title="Issue 4470">here</a>. </p>
| 0 | 2008-12-29T23:59:31Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 399,240 | <p>The following code works for me:</p>
<pre><code>import smtplib
FROMADDR = "[email protected]"
LOGIN = FROMADDR
PASSWORD = "my.real.password"
TOADDRS = ["[email protected]"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
</code></pre>
<p>I'm using Python 2.5.2.</p>
<p><strong>Edit</strong>: changed port from 25 to 587 as suggested by ΤÎΩΤÎÎÎÎ¥, and dropped the second ehlo(). Now I would love to know why port 25 works <em>perfectly</em> from my machine (and port 465 does <em>not</em>).</p>
| 25 | 2008-12-30T00:48:19Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 399,587 | <p>Here's a simple throw away solution. Meant to paste this earlier, but fell asleep at my chair.</p>
<pre><code>
import smtplib
import email
import os
username = "[email protected]"
passwd = "password"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
server = smtplib.SMTP("smtp.gmail.com", 495)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, passwd)
server.sendmail(username, to, msg.as_string())
server.close()
mail("you", "hi", "hi", "webcam.jpg")
</code></pre>
<p>It's my assumption that most people on this thread that have had successful attempts with their code aren't on win32. ;)</p>
<p>*edit: See <a href="http://docs.python.org/library/email-examples.html" rel="nofollow">http://docs.python.org/library/email-examples.html</a> for some good "official" examples. </p>
| 6 | 2008-12-30T05:35:03Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 400,930 | <p>Okay, found out that this line of code does the trick!</p>
<p>server = smtplib.SMTP('smtp.gmail.com', 587 )</p>
<p>Turned out to be GMAIL didn't support SSL on port 25 (and port 465 caused a hang for some reason).</p>
<p>Thanks guys!</p>
| 2 | 2008-12-30T17:30:53Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 402,054 | <p>The correct way to connect to GMail using SSL is:</p>
<pre><code>server = smtplib.SMTP('smtp.gmail.com', 587)
</code></pre>
<p>Port 465 seems to cause delays. Both ports are specified in a <a href="http://mail.google.com/support/bin/answer.py?hl=en&answer=78799">GMail FAQ</a>.</p>
<p>Note that use of port 587 is more common for SMTP over SSL, although this is just trivial information, it has no other practical use.</p>
<p><em>This answer is provided as community wiki in order to be chosen as "the" answer. Please improve as needed.</em></p>
| 6 | 2008-12-31T01:41:13Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 955,323 | <p>The problem is due to <a href="http://bugs.python.org/issue4066">a bug in Python</a>. Trying to create a connection with SMTP_SSL will fail with "SMTPServerDisconnected: please run connect() first."</p>
<p>A fix has been committed, so you can patch your local copy. See the attachment named "smtplib_72551.diff".</p>
<p>(Note: SMTP_SSL is a new class added to Python 2.6/3.0 and later.)</p>
| 6 | 2009-06-05T11:01:06Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 21,589,598 | <pre><code>import smtplib
content = 'example email stuff here'
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('[email protected]','password')
mail.sendmail('[email protected]', '[email protected]', content)
mail.close()
</code></pre>
| 0 | 2014-02-05T22:08:59Z | [
"python",
"email",
"smtplib"
] |
Failing to send email with the Python example | 399,129 | <p>I've been trying (and failing) to figure out how to send email via Python.</p>
<p>Trying the example from here:
<a href="http://docs.python.org/library/smtplib.html#smtplib.SMTP">http://docs.python.org/library/smtplib.html#smtplib.SMTP</a></p>
<p>but added the line <code>server = smtplib.SMTP_SSL('smtp.gmail.com', 465)</code> after I got a bounceback about not having an SSL connection. </p>
<p>Now I'm getting this:</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
</code></pre>
<p>Thoughts?</p>
<hr>
<p>server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).</p>
<p>I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.</p>
<p>"</p>
<pre><code>import smtplib
mailuser = '[email protected]'
mailpasswd = 'MYPASSWORD'
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</code></pre>
<p>"</p>
<p>and then I get this error message: "</p>
<pre><code>Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code></pre>
<p>"</p>
<p>note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP <em>underscore</em> SSL <em>underscore</em> PORT=587", there's some sort of formatting thing going on here.</p>
| 18 | 2008-12-29T23:51:33Z | 30,595,598 | <pre><code>from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText
HOST = 'smtp.gmail.com'
PORT = 465
USERNAME = '[email protected]'
PASSWORD = ''
SENDER = '[email protected]'
RECIPIENT = '[email protected]'
text_subtype = 'plain'
with open('textfile', 'rb') as f:
msg = MIMEText(f.read(), text_subtype)
msg['Subject'] = 'Python Script'
msg['From'] = SENDER
msg['To'] = RECIPIENT
try:
connection = SMTP(HOST, PORT)
connection.login(USERNAME, PASSWORD)
connection.sendmail(SENDER, RECIPIENT, msg.as_string())
except Exception, e:
print(e)
</code></pre>
<p>The above code works fine for me. As you can see the <code>PORT = 465</code> is being used in this example since I am using <code>SSL</code>. If you plan to use the port <code>587</code> then <code>TLS</code> is required.</p>
| 1 | 2015-06-02T12:04:50Z | [
"python",
"email",
"smtplib"
] |
Tix and Python 3.0 | 399,326 | <p>Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable.</p>
<p>I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1.</p>
<p>Why doesn't Python either dump Tix or support it? Its got a lot of good stuff to make easy programs.</p>
| 0 | 2008-12-30T01:57:34Z | 399,400 | <p>Likely what happened is that no one noticed the bug. (It's very hard to automatically test GUI libraries like Tix and Tkinter.) You should report bugs as you find them to <a href="http://bugs.python.org" rel="nofollow">http://bugs.python.org</a>.</p>
| 1 | 2008-12-30T02:41:54Z | [
"python",
"python-3.x",
"tix"
] |
Tix and Python 3.0 | 399,326 | <p>Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable.</p>
<p>I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1.</p>
<p>Why doesn't Python either dump Tix or support it? Its got a lot of good stuff to make easy programs.</p>
| 0 | 2008-12-30T01:57:34Z | 400,066 | <p>Generally speaking, if you're using third-party modules, you're better off avoiding Python 3.0 for now. If you're working on a third-party module yourself, porting forward to Python 3.0 is a good idea, but for the time being general development in it is just going to be a recipe for pain.</p>
| 0 | 2008-12-30T11:31:40Z | [
"python",
"python-3.x",
"tix"
] |
Tix and Python 3.0 | 399,326 | <p>Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable.</p>
<p>I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1.</p>
<p>Why doesn't Python either dump Tix or support it? Its got a lot of good stuff to make easy programs.</p>
| 0 | 2008-12-30T01:57:34Z | 1,333,329 | <p>See this: <a href="http://docs.python.org/3.1/library/tkinter.tix.html?highlight=tix#module-tkinter.tix" rel="nofollow">http://docs.python.org/3.1/library/tkinter.tix.html?highlight=tix#module-tkinter.tix</a></p>
| 0 | 2009-08-26T09:02:40Z | [
"python",
"python-3.x",
"tix"
] |
Programming a Logitech G15 using python | 399,624 | <p>I'd like to be able to write apps for my G15 keyboard using python. There seems to be a few people out there who have done it in the past, but I'm not sure what packages I need to install or where I should start. Does anyone have any experience with this?</p>
| 1 | 2008-12-30T06:14:00Z | 399,904 | <p>There's actually a couple of ways. You can use <a href="http://www.g15tools.com/" rel="nofollow">G15Tools</a>, of course. But the best solution would be <a href="https://launchpad.net/pyg15/" rel="nofollow">PyG15</a>.</p>
| 2 | 2008-12-30T10:00:43Z | [
"python",
"logitech",
"g15"
] |
How to integrate pep8.py in Eclipse? | 399,956 | <p>A little background:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> is the <em>Style Guide for Python Code</em>. It contains the conventions all python programmers should follow.</li>
<li><a href="http://pypi.python.org/pypi/pep8">pep8.py</a> is a (very useful) script that checks the code formating of a given python script, according to PEP 8.</li>
<li><a href="http://www.eclipse.org/">Eclipse</a> is a great IDE. With the <a href="http://pydev.sourceforge.net/">Pydev</a> extension, it that can be used to develop Python</li>
</ul>
<p>I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.</p>
<p>Question is: <strong>How to integrate pep8.py in Eclipse?</strong></p>
| 82 | 2008-12-30T10:39:53Z | 403,262 | <p>That does not yet appear to be fully integrated into Pydev.</p>
<p>As suggested in <a href="http://osdir.com/ml/ide.eclipse.plugins.pydev.user/2007-01/msg00011.html" rel="nofollow">this post</a>, </p>
<blockquote>
<p>[it] would require changing the code within pydev -- a flexible option would be adding preferences to let the user choose to which patterns he wants to match for creating hyperlinks (and saying which group in the match is the line and which one is the file)...</p>
<p>Or, you can try it hard-coded playing with: <a href="https://garage.maemo.org/pipermail/pluthon-commits/2007-October/000256.html" rel="nofollow">org.python.pydev.debug.ui.PythonConsoleLineTracker</a> (should be pretty easy to grasp).</p>
</blockquote>
<p>A <a href="https://garage.maemo.org/tracker/index.php?func=detail&aid=935&group_id=247&atid=989" rel="nofollow">request does exist</a> for just that, but it seems to be still open 1 year after its creation...</p>
| 5 | 2008-12-31T15:47:42Z | [
"python",
"eclipse",
"pydev",
"pep8"
] |
How to integrate pep8.py in Eclipse? | 399,956 | <p>A little background:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> is the <em>Style Guide for Python Code</em>. It contains the conventions all python programmers should follow.</li>
<li><a href="http://pypi.python.org/pypi/pep8">pep8.py</a> is a (very useful) script that checks the code formating of a given python script, according to PEP 8.</li>
<li><a href="http://www.eclipse.org/">Eclipse</a> is a great IDE. With the <a href="http://pydev.sourceforge.net/">Pydev</a> extension, it that can be used to develop Python</li>
</ul>
<p>I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.</p>
<p>Question is: <strong>How to integrate pep8.py in Eclipse?</strong></p>
| 82 | 2008-12-30T10:39:53Z | 2,296,249 | <p>I don't know how to integrate it for whole project, but I have used it as an external tool to analyze an individual file.</p>
<p>Note that the <a href="https://pypi.python.org/pypi/pycodestyle/" rel="nofollow"><code>pycodestyle</code></a> package is the official replacement for and is the newer version of the <a href="https://pypi.python.org/pypi/pep8/" rel="nofollow"><code>pep8</code></a> package. To install it, run:</p>
<pre><code>$ sudo pip install --upgrade pycodestyle
</code></pre>
<p>Next, in Eclipse:</p>
<ol>
<li>Select <strong>Run-External Tools-External Tools Configurations...</strong></li>
<li>Select <strong>Program</strong> root node.</li>
<li>Press <strong>New launch configuration</strong> button.</li>
<li>Enter <strong>Name</strong> for your launch configuration. I use <code>pycodestyle</code>.</li>
<li><p>Fill following fields:</p>
<p><strong>Location</strong> -- <code>${system_path:pycodestyle}</code></p>
<p><strong>Working directory</strong> -- <code>${container_loc}</code></p>
<p><strong>Arguments</strong> -- <code>"${resource_name}"</code> (This uses the currently active file.)</p></li>
</ol>
<p>Go to <strong>Common</strong> tab and confirm that the <strong>Allocate Console</strong> checkbox is checked.</p>
<p>A benefit of this approach is that you can use a very up-to-date version of the package, and are not limited to the old version included with PyDev. And if you are curious about setting up <code>pylint</code> in a similar manner, see <a href="https://stackoverflow.com/a/39863131/832230">this answer</a>.</p>
| 23 | 2010-02-19T12:36:16Z | [
"python",
"eclipse",
"pydev",
"pep8"
] |
How to integrate pep8.py in Eclipse? | 399,956 | <p>A little background:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> is the <em>Style Guide for Python Code</em>. It contains the conventions all python programmers should follow.</li>
<li><a href="http://pypi.python.org/pypi/pep8">pep8.py</a> is a (very useful) script that checks the code formating of a given python script, according to PEP 8.</li>
<li><a href="http://www.eclipse.org/">Eclipse</a> is a great IDE. With the <a href="http://pydev.sourceforge.net/">Pydev</a> extension, it that can be used to develop Python</li>
</ul>
<p>I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.</p>
<p>Question is: <strong>How to integrate pep8.py in Eclipse?</strong></p>
| 82 | 2008-12-30T10:39:53Z | 7,947,400 | <p>You don't :) Instead you take advantage of very good integration with PyLint and configure PyLint to check all things PEP8 checks. See <a href="http://stackoverflow.com/questions/6879640/">How to configure PyLint to check all things PEP8 checks?</a></p>
| -1 | 2011-10-30T19:53:36Z | [
"python",
"eclipse",
"pydev",
"pep8"
] |
How to integrate pep8.py in Eclipse? | 399,956 | <p>A little background:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> is the <em>Style Guide for Python Code</em>. It contains the conventions all python programmers should follow.</li>
<li><a href="http://pypi.python.org/pypi/pep8">pep8.py</a> is a (very useful) script that checks the code formating of a given python script, according to PEP 8.</li>
<li><a href="http://www.eclipse.org/">Eclipse</a> is a great IDE. With the <a href="http://pydev.sourceforge.net/">Pydev</a> extension, it that can be used to develop Python</li>
</ul>
<p>I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.</p>
<p>Question is: <strong>How to integrate pep8.py in Eclipse?</strong></p>
| 82 | 2008-12-30T10:39:53Z | 8,532,188 | <p>As of PyDev 2.3.0, <code>pep8</code> is integrated in PyDev by default, even shipping with a default version of it.</p>
<p>Open Window > Preferences</p>
<p>It must be enabled in PyDev > Editor > Code Analysis > pep8.py</p>
<p>Errors/Warnings should be shown as markers (as other things in the regular code analysis).</p>
<p>In the event a file is not analyzed, see <a href="https://stackoverflow.com/a/31001619/832230">https://stackoverflow.com/a/31001619/832230</a>.</p>
| 75 | 2011-12-16T09:32:19Z | [
"python",
"eclipse",
"pydev",
"pep8"
] |
How to integrate pep8.py in Eclipse? | 399,956 | <p>A little background:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> is the <em>Style Guide for Python Code</em>. It contains the conventions all python programmers should follow.</li>
<li><a href="http://pypi.python.org/pypi/pep8">pep8.py</a> is a (very useful) script that checks the code formating of a given python script, according to PEP 8.</li>
<li><a href="http://www.eclipse.org/">Eclipse</a> is a great IDE. With the <a href="http://pydev.sourceforge.net/">Pydev</a> extension, it that can be used to develop Python</li>
</ul>
<p>I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.</p>
<p>Question is: <strong>How to integrate pep8.py in Eclipse?</strong></p>
| 82 | 2008-12-30T10:39:53Z | 8,830,316 | <ol>
<li>Open your Eclipse</li>
<li>Go to Help and select Install New Software</li>
<li>Click the Add button and a "Add Repository" Dialog box will appear</li>
<li>You can use any name you like for it. (I used PyDev)</li>
<li>For the location, enter "http://pydev.org/updates"</li>
<li>Click Ok.</li>
<li>You are now in the process of installation. Just wait for it to finish.</li>
<li>After the installation, close Eclipse and Open it again.</li>
<li>Now that PyDev is installed in your Eclipse, go to Window->Preferences</li>
<li>Choose PyDev->Editor->Code Analysis</li>
<li>Go to pep8.py tab</li>
<li>Choose the radio button for warning and click Ok.</li>
</ol>
<p>That's it. Your Eclipse IDE is now integrated with PEP8.
To run pep8.py automatically, right click on your project editor. Choose PyDev and click "code analysis". In your problems tab in your workspace, you will see warnings that points to the line that you have made a violation in the PEP8 (if you have violated).</p>
| 10 | 2012-01-12T04:55:42Z | [
"python",
"eclipse",
"pydev",
"pep8"
] |
How to integrate pep8.py in Eclipse? | 399,956 | <p>A little background:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> is the <em>Style Guide for Python Code</em>. It contains the conventions all python programmers should follow.</li>
<li><a href="http://pypi.python.org/pypi/pep8">pep8.py</a> is a (very useful) script that checks the code formating of a given python script, according to PEP 8.</li>
<li><a href="http://www.eclipse.org/">Eclipse</a> is a great IDE. With the <a href="http://pydev.sourceforge.net/">Pydev</a> extension, it that can be used to develop Python</li>
</ul>
<p>I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.</p>
<p>Question is: <strong>How to integrate pep8.py in Eclipse?</strong></p>
| 82 | 2008-12-30T10:39:53Z | 33,952,133 | <p><strong>CODE ANALYSIS :</strong></p>
<p>In Eclipse (<strong>PyDev</strong>), if you want to <strong>code analysis</strong> using pep8 style then</p>
<p>Go to:Windows -> Preferences -> PyDev -> Editor -> Code Analysis -> <strong>pep8.py</strong> tab and select <strong>Warning</strong> click Apply and OK button.</p>
<p>In your python code if you validate pep8 coding style it will give you warning</p>
<p><strong>AUTO CODE FORMATTING :</strong></p>
<p>In Eclipse (<strong>PyDev</strong>), if you want to <strong>Auto Format</strong> python code using pep8 style then</p>
<p>Go to:Windows -> Preferences -> PyDev -> Editor -> Code Style -> Code Formatter -> click on check-box (<strong>Use autopep8.py for console formatting?</strong>) click Apply and OK button.</p>
<p>If you want to increase length of line(pep8 default is 79) below Use autopep8.py you can set parameter type <strong><code>--max-line-length=150</code></strong> if you set max length to 150</p>
<p>If press auto-format shortcut ( <strong>Ctrl + Shift + f</strong> ) it will automatically format your python code like pep8 style </p>
| 3 | 2015-11-27T07:19:03Z | [
"python",
"eclipse",
"pydev",
"pep8"
] |
Need help on selecting items in simple database in python | 399,957 | <p>I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, all resistors with value>100ohms or footprint='0402' </p>
<p>So far, I can select things using some primitive predicate search and then union and intersection for more complex things. </p>
<p>However, I'm having trouble defining what the semantics ought to be for a purely negative search. For instance, something like </p>
<p>footprint != '0402' </p>
<p>should select all items with footprint not equal to 0402. But doing this with only intersection gives me a blank result. For this to work I need to select <em>all</em> components, then intersect with "not 0402" to remove the ones I don't want.</p>
<p>But this seems kind of brute force and seems like a fishy solution. I'm not interested in using a "real" database and query language, so please don't suggest that. I'm looking for the proper engineering rationale here, not necessarily a workaround to the problem.</p>
<p>This problem was covered to some degree in SICP book, but I got very confused, since I think they were also using continuations and stuff, which I don't get yet.</p>
<p>Can someone please explain what the 'proper' usage ought to be for negatively selecting stuff. I tried this in a commercial cad tool and it worked as expected, but then I've seen some SQL query examples (I think), which selected things <em>first</em>, then removed the unwanted ones.</p>
<p>thanks<br />
michael</p>
| 2 | 2008-12-30T10:40:07Z | 399,997 | <p>It really depends on how you've implemented this "simple database based on dictionaries" as to why straight negation isn't working - you'll have to give us some more clues.</p>
<p>There's no reason why a straightforward negation match <em>shouldn't</em> work in Python, e.g.:</p>
<pre><code>components = [
{ 'name': 'resistor', 'footprint': '0402', },
{ 'name': 'LED', 'footprint': '0100', },
{ 'name': 'speaker', 'footprint': '2000', },
]
[comp for comp in components if comp['footprint'] != '0402']
# [{'footprint': '0100', 'name': 'LED'}, {'footprint': '2000', 'name': 'speaker'}]
</code></pre>
<p>At a stretch, this is a simple database based on dictionaries - the specific capabilities are really going to depend on your actual implementation.</p>
<p>I'm resisting the temptation to suggest use of a real database and query language as I assume this is a learning exercise. It is a learning exercise, right? :)</p>
| 3 | 2008-12-30T10:58:05Z | [
"python",
"sql",
"circuit",
"eda"
] |
Need help on selecting items in simple database in python | 399,957 | <p>I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, all resistors with value>100ohms or footprint='0402' </p>
<p>So far, I can select things using some primitive predicate search and then union and intersection for more complex things. </p>
<p>However, I'm having trouble defining what the semantics ought to be for a purely negative search. For instance, something like </p>
<p>footprint != '0402' </p>
<p>should select all items with footprint not equal to 0402. But doing this with only intersection gives me a blank result. For this to work I need to select <em>all</em> components, then intersect with "not 0402" to remove the ones I don't want.</p>
<p>But this seems kind of brute force and seems like a fishy solution. I'm not interested in using a "real" database and query language, so please don't suggest that. I'm looking for the proper engineering rationale here, not necessarily a workaround to the problem.</p>
<p>This problem was covered to some degree in SICP book, but I got very confused, since I think they were also using continuations and stuff, which I don't get yet.</p>
<p>Can someone please explain what the 'proper' usage ought to be for negatively selecting stuff. I tried this in a commercial cad tool and it worked as expected, but then I've seen some SQL query examples (I think), which selected things <em>first</em>, then removed the unwanted ones.</p>
<p>thanks<br />
michael</p>
| 2 | 2008-12-30T10:40:07Z | 400,058 | <p>You'll be a lot happier with a proper database.</p>
<p>You have SQLite with your Python distribution. Simply define tables instead of dictionaries and use SQL. </p>
<p>If you need more power and sophistication, you can add <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> (or <a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a>) and you won't struggle with these problems.</p>
| 5 | 2008-12-30T11:26:39Z | [
"python",
"sql",
"circuit",
"eda"
] |
Need help on selecting items in simple database in python | 399,957 | <p>I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, all resistors with value>100ohms or footprint='0402' </p>
<p>So far, I can select things using some primitive predicate search and then union and intersection for more complex things. </p>
<p>However, I'm having trouble defining what the semantics ought to be for a purely negative search. For instance, something like </p>
<p>footprint != '0402' </p>
<p>should select all items with footprint not equal to 0402. But doing this with only intersection gives me a blank result. For this to work I need to select <em>all</em> components, then intersect with "not 0402" to remove the ones I don't want.</p>
<p>But this seems kind of brute force and seems like a fishy solution. I'm not interested in using a "real" database and query language, so please don't suggest that. I'm looking for the proper engineering rationale here, not necessarily a workaround to the problem.</p>
<p>This problem was covered to some degree in SICP book, but I got very confused, since I think they were also using continuations and stuff, which I don't get yet.</p>
<p>Can someone please explain what the 'proper' usage ought to be for negatively selecting stuff. I tried this in a commercial cad tool and it worked as expected, but then I've seen some SQL query examples (I think), which selected things <em>first</em>, then removed the unwanted ones.</p>
<p>thanks<br />
michael</p>
| 2 | 2008-12-30T10:40:07Z | 400,137 | <p>I agree with S.Lott that you would be happier with a real DB. SQLite is really light and fast, almost no drawbacks on using it.</p>
<p>if you really need to expose a simpler, yet complete, query language to the user, check <a href="http://goessner.net/articles/JsonPath/" rel="nofollow">JSONPath</a> or <a href="http://www.sitepen.com/blog/2008/07/16/jsonquery-data-querying-beyond-jsonpath/" rel="nofollow">JSONQuery</a> (the second is a superset of the first). The exact syntax is (obviously) thought for JavaScript; but it should give you some ideas.</p>
<p>also, try to check similarities and differences with XPath and XQuery. it helps to see what is useful and what's culture-specific.</p>
| 1 | 2008-12-30T12:18:40Z | [
"python",
"sql",
"circuit",
"eda"
] |
Ignoring XML errors in Python | 399,980 | <p>I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser.
Is it possible to ignore them, like a browser for example?
I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.</p>
| 5 | 2008-12-30T10:48:33Z | 399,996 | <p>There is a library called <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a>, I think it's what you're looking for.
As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML.</p>
<blockquote>
<p>Beautiful Soup is a Python HTML/XML
parser designed for quick turnaround
projects like screen-scraping. Three
features make it powerful:</p>
<ol>
<li>Beautiful Soup won't choke if you give it bad markup. It yields a
parse tree that makes approximately as
much sense as your original document.
This is usually good enough to collect
the data you need and run away.</li>
<li>Beautiful Soup provides a few simple methods and Pythonic idioms for
navigating, searching, and modifying a
parse tree: a toolkit for dissecting a
document and extracting what you need.
You don't have to create a custom
parser for each application.</li>
<li>Beautiful Soup automatically converts incoming documents to Unicode
and outgoing documents to UTF-8. You
don't have to think about encodings,
unless the document doesn't specify an
encoding and Beautiful Soup can't
autodetect one. Then you just have to
specify the original encoding. </li>
</ol>
<p>Beautiful Soup parses anything you
give it, and does the tree traversal
stuff for you. You can tell it "Find
all the links", or "Find all the links
of class externalLink", or "Find all
the links whose urls match "foo.com",
or "Find the table heading that's got
bold text, then give me that text."</p>
</blockquote>
| 10 | 2008-12-30T10:57:54Z | [
"python",
"xml",
"minidom"
] |
Ignoring XML errors in Python | 399,980 | <p>I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser.
Is it possible to ignore them, like a browser for example?
I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.</p>
| 5 | 2008-12-30T10:48:33Z | 400,001 | <p>See, for example, <a href="http://stackoverflow.com/questions/328356/extracting-text-from-html-file-using-python">extracting-text-from-html-file-using-python</a> for suggestions regarding ways for parsing HTML in Python.</p>
| 0 | 2008-12-30T10:58:44Z | [
"python",
"xml",
"minidom"
] |
Ignoring XML errors in Python | 399,980 | <p>I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser.
Is it possible to ignore them, like a browser for example?
I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.</p>
| 5 | 2008-12-30T10:48:33Z | 400,669 | <p>It should be noted that while HTML looks like XML it is not XML. XHTML is an XML form of HTML.</p>
| 3 | 2008-12-30T16:05:16Z | [
"python",
"xml",
"minidom"
] |
How do you get Python to write down the code of a function it has in memory? | 399,991 | <p>When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.<br>
So I have this .py file that reads like:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
</code></pre>
<p>Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.<br>
I can also write a similar file very easily:</p>
<pre><code>def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
</code></pre>
<p>I want to pass a function as one of the parameters:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
</code></pre>
<p>And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.</p>
<p>But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.</p>
<p>How do you get python to write down the code of a function, as it writes down the value of a variable?</p>
| 4 | 2008-12-30T10:55:43Z | 400,040 | <pre>
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
</pre>
| 12 | 2008-12-30T11:18:39Z | [
"python",
"artificial-intelligence"
] |
How do you get Python to write down the code of a function it has in memory? | 399,991 | <p>When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.<br>
So I have this .py file that reads like:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
</code></pre>
<p>Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.<br>
I can also write a similar file very easily:</p>
<pre><code>def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
</code></pre>
<p>I want to pass a function as one of the parameters:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
</code></pre>
<p>And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.</p>
<p>But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.</p>
<p>How do you get python to write down the code of a function, as it writes down the value of a variable?</p>
| 4 | 2008-12-30T10:55:43Z | 400,046 | <p>Are you asking about this?</p>
<pre><code>def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
options+="def pippo(a,b):%s" % ( os.linesep, )
options+=" '''Some version of pippo'''%s" % ( os.linesep, )
options+=" return 2*a+b%s" % ( os.linesep, )
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
</code></pre>
<p>Or something else?</p>
| 0 | 2008-12-30T11:21:05Z | [
"python",
"artificial-intelligence"
] |
How do you get Python to write down the code of a function it has in memory? | 399,991 | <p>When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.<br>
So I have this .py file that reads like:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
</code></pre>
<p>Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.<br>
I can also write a similar file very easily:</p>
<pre><code>def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
</code></pre>
<p>I want to pass a function as one of the parameters:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
</code></pre>
<p>And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.</p>
<p>But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.</p>
<p>How do you get python to write down the code of a function, as it writes down the value of a variable?</p>
| 4 | 2008-12-30T10:55:43Z | 400,052 | <p>While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to <em>share code</em>. Put <code>pippo</code> and his buddies in a submodule that both programs can access.</p>
| 0 | 2008-12-30T11:24:44Z | [
"python",
"artificial-intelligence"
] |
How do you get Python to write down the code of a function it has in memory? | 399,991 | <p>When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.<br>
So I have this .py file that reads like:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
</code></pre>
<p>Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.<br>
I can also write a similar file very easily:</p>
<pre><code>def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
</code></pre>
<p>I want to pass a function as one of the parameters:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
</code></pre>
<p>And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.</p>
<p>But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.</p>
<p>How do you get python to write down the code of a function, as it writes down the value of a variable?</p>
| 4 | 2008-12-30T10:55:43Z | 400,054 | <p>Instead of diving into the subject of <a href="http://docs.python.org/library/dis.html" rel="nofollow">disassemblers</a> and bytecodes (e.g <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a>), why don't you just save the generated Python source in a module (<em>file.py</em>), and later, import it?</p>
<p>I would suggest looking into a more standard way of handling what you call <em>options</em>. For example, you can use the <a href="http://docs.python.org/library/json.html" rel="nofollow">JSON</a> module and save or restore your data. Or look into the <a href="http://docs.python.org/library/marshal.html#module-marshal" rel="nofollow">marshal</a> and <a href="http://docs.python.org/library/pickle.html#module-pickle" rel="nofollow">pickle</a> modules.</p>
| 0 | 2008-12-30T11:25:27Z | [
"python",
"artificial-intelligence"
] |
How do you get Python to write down the code of a function it has in memory? | 399,991 | <p>When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.<br>
So I have this .py file that reads like:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
</code></pre>
<p>Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.<br>
I can also write a similar file very easily:</p>
<pre><code>def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
</code></pre>
<p>I want to pass a function as one of the parameters:</p>
<pre><code>starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
</code></pre>
<p>And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.</p>
<p>But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.</p>
<p>How do you get python to write down the code of a function, as it writes down the value of a variable?</p>
| 4 | 2008-12-30T10:55:43Z | 400,349 | <p>You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash:</p>
<pre><code>alias run_py='svn ci -m "Commit before running"; python2.5 $*'
</code></pre>
<p>and inside the script, have the output prefixed by the <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html" rel="nofollow">current subversion revision number</a> for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be.</p>
<p>Another, substantially less full-featured, means of tracking the input to a function could be via something like <a href="http://paste.pocoo.org/" rel="nofollow">LodgeIt</a>, a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.)</p>
<p>But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman <a href="http://www.doughellmann.com/PyMOTW/inspect/index.html" rel="nofollow">covered the <code>inspect</code> module</a> in his <a href="http://www.doughellmann.com/PyMOTW/" rel="nofollow">Python Module of the Week</a> series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use <code>inspect.getargspec</code> to get the names of the arguments.)</p>
<pre><code>import inspect
from functools import wraps
def option_printer(func):
@wraps(func)
def run_func(*args, **kwargs):
for name, arg in zip(inspect.getargspec(func)[0], args) \
+ sorted(kwargs.items()):
if isinstance(arg, types.FunctionType):
print "Function argument '%s' named '%s':\n" % (name, func.func_name)
print inspect.getsource(func)
else:
print "%s: %s" % (name, arg)
return func(*args, **kwargs)
return run_func
</code></pre>
<p>This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.</p>
| 1 | 2008-12-30T14:12:54Z | [
"python",
"artificial-intelligence"
] |
Reading and running a mathematical expression in Python | 400,050 | <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p>
<p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
| 5 | 2008-12-30T11:22:43Z | 400,060 | <p>If you are receiving an expression as a string you'll need to parse it into its operators and operands and then process the resulting tree. This isn't a python problem per se. but a general issue of how to deal with mathematical expressions delivered as strings.</p>
<p>A quick google reveals a bunch of lexical parsers for python. </p>
| 2 | 2008-12-30T11:28:02Z | [
"python"
] |
Reading and running a mathematical expression in Python | 400,050 | <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p>
<p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
| 5 | 2008-12-30T11:22:43Z | 400,062 | <p>Perhaps <code>eval</code> is what you're after?</p>
<pre><code>>>> eval('1+1')
2
</code></pre>
| 1 | 2008-12-30T11:28:51Z | [
"python"
] |
Reading and running a mathematical expression in Python | 400,050 | <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p>
<p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
| 5 | 2008-12-30T11:22:43Z | 400,070 | <p>Read about the <a href="http://docs.python.org/library/functions.html#input" rel="nofollow">input</a> function.</p>
| 1 | 2008-12-30T11:32:25Z | [
"python"
] |
Reading and running a mathematical expression in Python | 400,050 | <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p>
<p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
| 5 | 2008-12-30T11:22:43Z | 400,081 | <p>Because python supports some algebraic forms, you could do:</p>
<pre><code>eval("1 + 1")
</code></pre>
<p>But this allows the input to execute about anything defined in your env:</p>
<pre><code>eval("__import__('sys').exit(1)")
</code></pre>
<p>Also, if you want to support something python doesn't support, the approach fails:</p>
<pre><code>x³ + y² + c
----------- = 0
z
</code></pre>
<p>Instead of doing this, you can implement a tokenizer and a parser with <a href="http://www.dabeaz.com/ply/">ply</a>. Evaluating a thing like '1 + 1' ought not take more than ten lines or so.</p>
<p>You could also implement the tokenizer and the parser by hand. Read about LL and LR parsers. Before attempting this it's also better to learn using parser generators first.</p>
| 7 | 2008-12-30T11:43:43Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.