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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am ... | 25 | 2009-06-12T00:45:51Z | 984,808 | <p>If it was me I would probably do something like the following:</p>
<pre><code>try:
server = smtplib.SMTP(host)
try:
server.login(username, password)
server.sendmail(addr, [to], str(msg))
finally:
server.quit()
except:
debug("sendmail", traceback.format_exc().splitlines()[-1])... | 3 | 2009-06-12T03:09:51Z | [
"python",
"exception"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am ... | 25 | 2009-06-12T00:45:51Z | 985,886 | <p>I would try something like this:</p>
<pre><code>class Mailer():
def send_message(self):
exception = None
for method in [self.connect,
self.authenticate,
self.send,
self.quit]:
try:
if not method(... | 1 | 2009-06-12T09:46:10Z | [
"python",
"exception"
] |
How to use standard toolbar icons with WxPython? | 984,816 | <p>I'm designing a simple text editor using WxPython, and I want to put the platform's native icons in the toolbar. It seems that the only way to make toolbars is with custom images, which are not good for portability. Is there some kind of (e.g.) GetSaveIcon()?</p>
| 2 | 2009-06-12T03:16:20Z | 984,833 | <p>I don't think wxPython provides native images on each platform
but just for consistency sake you can use wx.ArtProvider
e.g.
wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN)</p>
| 4 | 2009-06-12T03:25:11Z | [
"python",
"wxpython",
"icons"
] |
Convert a value into row, column and char | 984,888 | <p>My data structure is initialized as follows:</p>
<pre><code>[[0,0,0,0,0,0,0,0] for x in range(8)]
</code></pre>
<p>8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.</p>
<p>I have to convert the number 177 (can be between 0 and 319) into char, ro... | 1 | 2009-06-12T03:56:42Z | 984,954 | <p>Are you looking for divmod function?</p>
<p>[Edit: using python operators instead of pseudo language.]</p>
<pre><code>char is between 0 and 319
character = (char % 40)
column = (char / 40) % 5
row = (char / 40) / 5
</code></pre>
| 1 | 2009-06-12T04:15:11Z | [
"python",
"math"
] |
Convert a value into row, column and char | 984,888 | <p>My data structure is initialized as follows:</p>
<pre><code>[[0,0,0,0,0,0,0,0] for x in range(8)]
</code></pre>
<p>8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.</p>
<p>I have to convert the number 177 (can be between 0 and 319) into char, ro... | 1 | 2009-06-12T03:56:42Z | 985,510 | <p>Okay, this looks as if you're working with a 1x8 LCD display, where each character is 8 rows of 5 pixels.</p>
<p>So, you have a total of 8 * (8 * 5) = 320 pixels, and you want to map the index of a pixel to a position in the "framebuffer" decribing the display's contents.</p>
<p>I assume pixels are distributed lik... | 2 | 2009-06-12T07:50:34Z | [
"python",
"math"
] |
Python Subprocess.Popen from a thread | 984,941 | <p>I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Ano... | 18 | 2009-06-12T04:13:25Z | 985,028 | <p>You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe:</p>
<pre><code>import threading
import subprocess
class MyClass(threading.Thread):
def __init__(self):
self.stdout = None
self.stderr = None
threading.Thread.__init__(self... | 27 | 2009-06-12T04:39:35Z | [
"python",
"multithreading",
"subprocess",
"rsync"
] |
Python Subprocess.Popen from a thread | 984,941 | <p>I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Ano... | 18 | 2009-06-12T04:13:25Z | 4,872,639 | <p>Here's a great implementation not using threads:
<a href="http://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running">constantly-print-subprocess-output-while-process-is-running</a></p>
<pre><code>import subprocess
def execute(command):
process = subprocess.Popen(com... | 5 | 2011-02-02T09:25:26Z | [
"python",
"multithreading",
"subprocess",
"rsync"
] |
Page isn't always rendered | 985,017 | <p>In Google App Engine, I have the following code which shows a simple HTML page.</p>
<pre><code>import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
class IndexHandler(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.d... | 1 | 2009-06-12T04:35:23Z | 985,165 | <p>Can't reproduce -- with directory changed to <code>./templates</code> (don't have a <code>../templates</code> in my setup), and the usual <code>main</code> function added, and this script assigned in <code>app.yaml</code> to some arbitrary URL, it serves successfully "Hello World" every time. Guess we need more info... | 0 | 2009-06-12T05:34:28Z | [
"python",
"google-app-engine"
] |
Page isn't always rendered | 985,017 | <p>In Google App Engine, I have the following code which shows a simple HTML page.</p>
<pre><code>import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
class IndexHandler(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.d... | 1 | 2009-06-12T04:35:23Z | 986,395 | <p>Your handler script (the one referenced by app.yaml) has a main() function, but needs this stanza at the end:</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
<p>What's happening is that the first time your script is run in a given interpreter, it interprets your main script, which does nothing (th... | 3 | 2009-06-12T12:33:49Z | [
"python",
"google-app-engine"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
... | 1 | 2009-06-12T04:39:21Z | 985,045 | <pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>is dreck -- use</p>
<pre><code>self.data = map(list, data)
</code></pre>
<p>if you're a <code>map</code> fanatic (list comprehensions are generally preferred these days). More generally, <code>lambda x: somecallable(x)</code> can <strong>always</st... | 11 | 2009-06-12T04:45:29Z | [
"python",
"shortcut",
"refactoring"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
... | 1 | 2009-06-12T04:39:21Z | 985,141 | <p>Alex Martelli provided an even shorter version of your first example. I shall provide a (slightly) shorter version of your second:</p>
<pre><code>tuple(t[0] for t in self.result if t[0] not in ('mysql', 'information_schema'))
</code></pre>
<p>Obviously the in operator becomes more advantageous the more values you... | 3 | 2009-06-12T05:24:11Z | [
"python",
"shortcut",
"refactoring"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
... | 1 | 2009-06-12T04:39:21Z | 985,952 | <p>I'm not sure if this is a shortcut, but I love it:</p>
<pre><code>>>> class Enum(object):
def __init__(self, *keys):
self.keys = keys
self.__dict__.update(zip(keys, range(len(keys))))
def value(self, key):
return self.keys.index(key)
>>&g... | 3 | 2009-06-12T10:01:58Z | [
"python",
"shortcut",
"refactoring"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
... | 1 | 2009-06-12T04:39:21Z | 986,633 | <p>I always liked the "unzip" idiom:</p>
<pre><code>>>> zipped = [('a', 1), ('b', 2), ('c', 3)]
>>> zip(*zipped)
[('a', 'b', 'c'), (1, 2, 3)]
>>>
>>> l,n = zip(*zipped)
>>> l
('a', 'b', 'c')
>>> n
(1, 2, 3)
</code></pre>
| 1 | 2009-06-12T13:26:38Z | [
"python",
"shortcut",
"refactoring"
] |
How to specify native library search path for python | 985,155 | <p>I have installed lxml which was built using a standalone version of libxml2. Reason for this was that the lxml needed a later version of libxml2 than what was currently installed.</p>
<p>When I use the lxml module how do I tell it (python) where to find the correct version of the libxml2 shared library?</p>
| 4 | 2009-06-12T05:28:54Z | 985,176 | <p>Assuming you're talking about a <code>.so</code> file, it's not up to Python to find it -- it's up to the operating system's dynamic library loaded. For Linux, for example, <code>LD_LIBRARY_PATH</code> is the environment variable you need to set.</p>
| 5 | 2009-06-12T05:38:53Z | [
"python"
] |
disable a block in django | 985,224 | <p>I want to disable a block in development and use it in deployment in google apps in python development. What changes do i need to make in template or main script?</p>
| 0 | 2009-06-12T06:10:29Z | 985,268 | <p>If you've got the middleware <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug" rel="nofollow">django.core.content_processors.debug</a> then you can just do this in your template:</p>
<pre><code>{% block mydebugonly %}
{% if debug %}
<p>Something tha... | 3 | 2009-06-12T06:33:01Z | [
"python",
"django",
"google-app-engine"
] |
Is the pickling process deterministic? | 985,294 | <p>Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.</p>
| 6 | 2009-06-12T06:41:15Z | 985,362 | <p>What do you mean by same output ? You should normally always get the same output for a roundtrip (pickling -> unpickling), but I don't think the serialized format itself is guaranteed to be the same in every condition. Certainly, it may change between platforms and all that.</p>
<p>Within one run of your program, u... | 0 | 2009-06-12T07:04:14Z | [
"python",
"pickle",
"memoization"
] |
Is the pickling process deterministic? | 985,294 | <p>Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.</p>
| 6 | 2009-06-12T06:41:15Z | 985,369 | <blockquote>
<p>I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories.</p>
</blockquote>
<p>Right:</p>
<pre><code>>>> pickle.dumps({1: 0, 9: 0}) == pickle.dumps({9: 0, 1: 0})
False
</code></pre>
<p>See also: <a href="http://www.aminu... | 7 | 2009-06-12T07:06:00Z | [
"python",
"pickle",
"memoization"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 985,331 | <p>Now I am thinking of something such as:</p>
<pre><code>def comparator(lop, rop):
def comp(i, j, k):
if j <= k:
return lop(j, i) and rop(i,k)
return lop(j, i) or rop(i,k)
return comp
from operator import le, lt
inRange = comparator(le, lt)
inStrictRange = comparator(lt, lt)
... | 2 | 2009-06-12T06:55:07Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 985,340 | <p>The Pythonic way to do it is to choose readability, and therefor keep the 3 methods as they were at the beginning.</p>
<p>It's not like they are HUGE methods, or there are thousand of them, or you would have to dynamically generate them.</p>
| 5 | 2009-06-12T06:58:04Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 985,388 | <p>No higher-order functions, but it's less code, even with the extraneous <code>else</code>.</p>
<pre><code>def exclusive(i, j, k):
if j <= k:
return j < i < k
else:
return j < i or i < k
def inclusive_left(i, j, k):
return i==j or exclusive(i, j, k)
def inclusive_right(i,... | 4 | 2009-06-12T07:12:45Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 985,630 | <p>Two <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow" title="PEP 20: The Zen of Python">Zen of Python</a> principles leap to mind:</p>
<ul>
<li>Simple is better than complex.</li>
<li>There should be oneâand preferably only oneâobvious way to do it.</li>
</ul>
<h1><code>range</code></h1>
<p>Th... | 7 | 2009-06-12T08:39:00Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 989,391 | <p>To make it more familiar to your users, I would have one main in_range function with the same bounds as range(). This makes it much easier to remember, and has other nice properties as Wesley mentioned.</p>
<pre><code>def in_range(i, j, k):
return (j <= i < k) if j <= k else (j <= i or i < k)
</c... | 1 | 2009-06-12T22:42:50Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 989,437 | <p>I'd go one step further than Wesley in aping the normal python 'in range' idiom; i'd write a cyclic_range class:</p>
<pre><code>import itertools
MAX = 10 # or whatever
class cyclic_range(object):
def __init__(self, start, stop):
# mod so you can be a bit sloppy with indices, plus -1 means the last element, as ... | 1 | 2009-06-12T22:58:17Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)... | 2 | 2009-06-12T06:48:02Z | 989,623 | <p>I certainly agree that you need only one function, and that the function should use a (Pythonic) half-open range.</p>
<p>Two suggestions:</p>
<ol>
<li><p>Use meaningful names for the args:
in_range(x, lo, hi) is a big
improvement relative to the
2-keystroke cost.</p></li>
<li><p>Document the fact that the
constrai... | 2 | 2009-06-13T00:39:29Z | [
"python",
"operators"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.tx... | 8 | 2009-06-12T07:39:00Z | 985,494 | <p>Check this out:</p>
<pre><code># -*- coding: utf-8 -*-
import pprint
f = open('unicode.txt','r')
for line in f:
print line
pprint.pprint(line)
for i in line:
print i,
f.close()
</code></pre>
<p>It returns this:</p>
<p>Stäckövérfløw<br />
'St\xc3\xa4ck\xc3\xb6v\xc3\xa9rfl\xc3\xb8w'<br />
S ... | 1 | 2009-06-12T07:42:17Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.tx... | 8 | 2009-06-12T07:39:00Z | 985,501 | <p>Use codecs.open instead, it works for me.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = codecs.open('in','r','utf8')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
| 2 | 2009-06-12T07:45:50Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.tx... | 8 | 2009-06-12T07:39:00Z | 985,508 | <pre><code>for i in line:
print i,
</code></pre>
<p>When you read the file, the string you read in is a string of bytes. The for loop iterates over a single byte at a time. This causes problems with a UTF-8 encoded string, where non-ASCII characters are represented by multiple bytes. If you want to work with Un... | 14 | 2009-06-12T07:50:00Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.tx... | 8 | 2009-06-12T07:39:00Z | 985,523 | <pre><code>print c,
</code></pre>
<p>Adds a "blank charrecter" and breaks correct utf-8 sequences into incorrect one. So this would not work unless you write a signle byte to output</p>
<pre><code>sys.stdout.write(i)
</code></pre>
| 1 | 2009-06-12T07:56:28Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.tx... | 8 | 2009-06-12T07:39:00Z | 20,399,153 | <p>One may want to just use </p>
<pre><code>f = open('in.txt','r')
for line in f:
print line
for i in line.decode('utf-8'):
print i,
f.close()
</code></pre>
| 0 | 2013-12-05T11:45:02Z | [
"python",
"utf-8"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 985,517 | <p>You can just set the locale like in this example:</p>
<pre><code>>>> import time
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
Sun, 23 Oct 2005 20:38:56
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
'sv_SE'
>>> print time.strftime("%a, %d %... | 33 | 2009-06-12T07:53:14Z | [
"python",
"date",
"locale"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 10,290,840 | <p>Another option is:</p>
<pre><code>>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_TIME,'')
'es_CR.UTF-8'
>>> date_format = locale.nl_langinfo(locale.D_FMT)
>>> date_format
'%d/%m/%Y'
>>> today = datetime.date.today()
>>> today
datet... | 9 | 2012-04-24T02:03:23Z | [
"python",
"date",
"locale"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 26,927,760 | <p>You should use <code>%x</code> and <code>%X</code> to format the date string in the correct locale. E.g. in Swedish a date is represented as <code>2014-11-14</code> instead of <code>11/14/2014</code>.</p>
<p>The correct way to get the result as Unicode is:</p>
<pre><code>locale.setlocale(locale.LC_ALL, lang)
forma... | 11 | 2014-11-14T10:22:52Z | [
"python",
"date",
"locale"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 32,785,195 | <p>If your application is supposed to support more than one locale then getting localized format of date/time by changing locale (by means of <code>locale.setlocale()</code>) is discouraged. For explanation why it's a bad idea see Alex Martelli's <a href="http://stackoverflow.com/a/1551834/95735">answer</a> to the the ... | 8 | 2015-09-25T15:04:19Z | [
"python",
"date",
"locale"
] |
Django: How can I change a ModelForm's Many2ManyField (select tag) choices verbose values? | 985,543 | <p>For example:</p>
<p>I have the follow model</p>
<pre><code>class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,related_name="child_cat")
description = models.TextFi... | 1 | 2009-06-12T08:05:10Z | 985,555 | <p>I'm not sure if this is the best way, but you could edit the Categories model so it looks like this:</p>
<pre><code>class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,r... | 0 | 2009-06-12T08:10:13Z | [
"python",
"django"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 986,044 | <p>In this case the variable titled <code>var</code> in the method <code>Change</code> is assigned a reference to <code>self.variable</code>, and you immediately assign a string to <code>var</code>. It's no longer pointing to <code>self.variable</code>. The following code snippet shows what would happen if you modify t... | 11 | 2009-06-12T10:39:59Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 986,145 | <p>Arguments are <a href="http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference">passed by assignment</a>. The rationale behind this is twofold:</p>
<ol>
<li>the parameter passed in is actually a <em>reference</em> to an object (but the reference is passed by ... | 1,619 | 2009-06-12T11:18:27Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 986,335 | <p>You got some really good answers here.</p>
<pre><code>x = [ 2, 4, 4, 5, 5 ]
print x # 2, 4, 4, 5, 5
def go( li ) :
li = [ 5, 6, 7, 8 ] # re-assigning what li POINTS TO, does not
# change the value of the ORIGINAL variable x
go( x )
print x # 2, 4, 4, 5, 5 [ STILL! ]
raw_input( 'press any key to continu... | 16 | 2009-06-12T12:16:45Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 986,339 | <p>Think of stuff being passed <strong>by assignment</strong> instead of by reference/by value. That way, it is allways clear, what is happening as long as you understand what happens during normal assignment.</p>
<p>So, when passing a list to a function/method, the list is assigned to the parameter name. Appending to... | 110 | 2009-06-12T12:17:48Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 986,495 | <p>It is neither pass-by-value or pass-by-reference - it is call-by-object. See this, by Fredrik Lundh: </p>
<p><a href="http://effbot.org/zone/call-by-object.htm">http://effbot.org/zone/call-by-object.htm</a></p>
<p>Here is a significant quote:</p>
<blockquote>
<p>"...variables [names] are <em>not</em> objects; t... | 190 | 2009-06-12T12:55:41Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 3,127,336 | <p>(edit - Blair has updated his enormously popular answer so that it is now accurate)</p>
<p>I think it is important to note that the current post with the most votes (by Blair Conrad), while being correct with respect to its result, is misleading and is borderline incorrect based on its definitions. While there are... | 29 | 2010-06-27T12:33:45Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 6,963,425 | <p>A simple trick I normally use is to just wrap it in a list:</p>
<pre><code>def Change(self, var):
var[0] = 'Changed'
variable = ['Original']
self.Change(variable)
print variable[0]
</code></pre>
<p>(Yeah I know this can be inconvenient, but sometimes it is simple enough to do this.)</p>
| 23 | 2011-08-05T22:52:00Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 8,140,747 | <p>The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence:</p>
<pre><code>a = 1
a = 2
</code></pre>
<p>You believe that <code>a</code> is a memory location that stores the value <code>1<... | 345 | 2011-11-15T17:45:28Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 12,440,140 | <p>Technically, <strong>Python always uses pass by reference values</strong>. I am going to repeat <a href="http://stackoverflow.com/a/12438316/1346705">my other answer</a> to support my statement.</p>
<p>Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the ... | 43 | 2012-09-15T18:53:57Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 12,686,527 | <p>Here is the simple (I hope) explanation of the concept <code>pass by object</code> used in Python.<br>
Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when ... | 4 | 2012-10-02T08:03:08Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 15,697,476 | <p>Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: <a href="http://effbot.org/zone/call-by-object.htm">http://effbot.org/zone/call-by-object.htm</a></p>
<p>Objects are allocated on the heap and pointers to them can be passed around anywhere. </p>
<ul>
<li><p>When you make... | 35 | 2013-03-29T04:41:44Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 21,684,541 | <p>As you can state you need to have a mutable object, but let me suggest you to check over the global variables as they can help you or even solve this kind of issue!</p>
<p><a href="http://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python" rel="nofollow">http://docs.p... | 10 | 2014-02-10T17:57:39Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 21,700,609 | <p>The key to understanding parameter passing is to stop thinking about "variables". <strong>There are no variables in Python.</strong></p>
<ol>
<li>Python has names and objects.</li>
<li>Assignment binds a name to an object.</li>
<li>Passing an argument into a function also binds a name (the parameter name of the fun... | 15 | 2014-02-11T11:29:07Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 25,670,170 | <p>I found the other answers rather long and complicated, so I created this simple diagram to explain the way Python treats variables and parameters.
<a href="http://i.stack.imgur.com/FdaCu.png"><img src="http://i.stack.imgur.com/FdaCu.png" alt="enter image description here"></a></p>
| 170 | 2014-09-04T16:05:35Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 25,810,863 | <p>A lot of insights in answers here, but i think an additional point is not clearly mentioned here explicitly. Quoting from python documentation <a href="https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python">https://docs.python.org/2/faq/programming.html#what-are... | 9 | 2014-09-12T14:40:18Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 29,293,411 | <p>Pythonâs pass-by-assignment scheme isnât quite the same as C++âs reference parameters option, but it turns out to be very similar to the argument-passing model of the C language (and others) in practice:</p>
<ul>
<li>Immutable arguments are effectively passed â<strong>by value</strong>.â Objects such as i... | 10 | 2015-03-27T04:38:18Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 35,260,424 | <p>Aside from all the great explanations on how this stuff works in Python, I don't see a simple suggestion for the problem. As you seem to do create objects and instances, the pythonic way of handling instance variables and changing them is the following:</p>
<pre><code>class PassByReference:
def __init__(self):
... | 3 | 2016-02-07T23:18:36Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 36,775,894 | <p>There is a little trick to pass an object by reference, even though the language doesn't make it possible. It works in Java too, it's the list with one item. ;-)</p>
<pre><code>class PassByReference:
def __init__(self, name):
self.name = name
def changeRef(ref):
ref[0] = PassByReference('Michael')
... | 2 | 2016-04-21T16:47:42Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 38,834,546 | <p>I used the following method to quickly convert a couple of Fortran codes to Python. True, it's not pass by reference as the original question was posed, but is a simple work around in some cases.</p>
<pre><code>a=0
b=0
c=0
def myfunc(a,b,c):
a=1
b=2
c=3
return a,b,c
a,b,c = myfunc(a,b,c)
print a,b... | 0 | 2016-08-08T16:46:05Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.vari... | 1,460 | 2009-06-12T10:23:51Z | 39,054,982 | <p>While pass by reference is nothing that fits well into python and should be rarely used there are some workarounds that actually can work to get the object currently assigned to a local variable or even reassign a local variable from inside of a called function.</p>
<p>The basic idea is to have a function that can ... | 1 | 2016-08-20T14:02:37Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
What does this line mean in Python? | 986,087 | <p>Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#.</p>
<pre><code>from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof
CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3")
cpu... | 9 | 2009-06-12T10:57:21Z | 986,128 | <p>It executes the following machine code:</p>
<pre><code>push bx
xor ax, ax
inc ax
cpuid
pop bx
retn
</code></pre>
<p>Basically it calls <a href="http://en.wikipedia.org/wiki/CPUID" rel="nofollow">CPUID</a> instruction of the CPU in order to get information about the CPU. Since EAX=1 it gets the processor info and f... | 24 | 2009-06-12T11:12:23Z | [
"c#",
"python",
"windows",
"cpu",
"cpuid"
] |
What does this line mean in Python? | 986,087 | <p>Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#.</p>
<pre><code>from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof
CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3")
cpu... | 9 | 2009-06-12T10:57:21Z | 986,190 | <p>In addition to <a href="http://stackoverflow.com/questions/986087/what-does-this-line-means-in-python/986128#986128">DrJokepu</a>'s answer. The python code is using the <code>ctypes</code> modules do implement the following C code(/hack):</p>
<pre><code>char *CPUID = "\x53\x31\xc0\x40\x0f\xa2\x5b\xc3"; // x86 code
... | 6 | 2009-06-12T11:33:40Z | [
"c#",
"python",
"windows",
"cpu",
"cpuid"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 986,515 | <p>A list of <a href="http://www.example-code.com/python/encryption.asp" rel="nofollow">Python encryption examples</a>.</p>
| 2 | 2009-06-12T12:59:18Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 987,942 | <p>SQLite databases are pretty human-readable, and there isn't any built-in encryption.</p>
<p>Are you concerned about someone accessing and reading the database files directly, or accessing them through your program? </p>
<p>I'm assuming the former, because the latter isn't really database related--it's your applic... | 1 | 2009-06-12T17:27:54Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 8,723,718 | <p>You can use SQLCipher.</p>
<p><a href="http://sqlcipher.net/">http://sqlcipher.net/</a></p>
<p>Open Source Full Database Encryption for SQLite</p>
<p>SQLCipher is an SQLite extension that provides transparent 256-bit AES encryption of database files. Pages are encrypted before being written to disk and are decryp... | 9 | 2012-01-04T08:02:47Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 14,290,287 | <p>I had the same problem. My application may have multiple instances running at the same time. Because of this, I can't just encrypt the sqlite db file and be done with it. I also don't believe that encrypting the data in python is a good idea, as you can't do any serious data manipulation in the database with it i... | 1 | 2013-01-12T04:36:58Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 23,161,888 | <p>As Frontware suggests, you can use sqlcipher.</p>
<p><a href="https://pypi.python.org/pypi/pysqlcipher" rel="nofollow">pysqlcipher</a> python package can make it easier to use since it uses the sqlcipher code amalgamation to compile the extension.</p>
<p>It should be just a matter of using pysqlcipher as you woul... | 2 | 2014-04-18T20:35:24Z | [
"python",
"sqlite",
"encryption"
] |
One stop resource for : Will it play in App Engine/Python? | 986,516 | <p>Information on frameworks, languages, and libraries for GAE/J is maintained at
: <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine" rel="nofollow">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine</a></p>
<p>Is there a similar page for GA... | 1 | 2009-06-12T12:59:28Z | 987,787 | <p>From <a href="http://code.google.com/appengine/docs/python/overview.html" rel="nofollow">http://code.google.com/appengine/docs/python/overview.html</a></p>
<p>The Python runtime environment uses Python 2.5.2.</p>
<p>All code for the Python runtime environment must be pure Python, and not include any C extensions o... | 4 | 2009-06-12T16:55:52Z | [
"python",
"google-app-engine",
"frameworks"
] |
Experiences of creating Social Network site in Django | 986,594 | <p>I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility.</p>
<p>Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available.</p>
<p>I would like to hear what kind of experiences yo... | 13 | 2009-06-12T13:17:28Z | 986,729 | <p>If you're interested in creating a social-network site in Django, you should definitely investigate <a href="http://pinaxproject.com/">Pinax</a>. This is a project that integrates a number of apps that are useful for creating this sort of site - friends, messaging, invitations, registration, etc. They're mostly very... | 26 | 2009-06-12T13:48:18Z | [
"python",
"django"
] |
Experiences of creating Social Network site in Django | 986,594 | <p>I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility.</p>
<p>Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available.</p>
<p>I would like to hear what kind of experiences yo... | 13 | 2009-06-12T13:17:28Z | 990,440 | <p>Are you saying that a random survey of some posted Django apps (not Django itself) reveals that some people post code that doesn't meet your standards of quality?</p>
<p>Isn't that universally true of all code posted everywhere on the internet?</p>
<p>A random survey of any code in any language for any framework w... | -2 | 2009-06-13T09:55:37Z | [
"python",
"django"
] |
Python thread exit code | 986,616 | <p>Is there a way to tell if a thread has exited normally or because of an exception?</p>
| 6 | 2009-06-12T13:23:42Z | 986,658 | <p>You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.</p>
<p>However, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it.</p>
| -1 | 2009-06-12T13:33:12Z | [
"python",
"multithreading",
"exit-code"
] |
Python thread exit code | 986,616 | <p>Is there a way to tell if a thread has exited normally or because of an exception?</p>
| 6 | 2009-06-12T13:23:42Z | 986,698 | <p>Have your thread function catch exceptions. (You can do this with a simple wrapper function that just calls the old thread function inside a <code>try</code>...<code>except</code> or <code>try</code>...<code>except</code>...<code>else</code> block). Then the question just becomes "how to pass information from one ... | 0 | 2009-06-12T13:43:05Z | [
"python",
"multithreading",
"exit-code"
] |
Python thread exit code | 986,616 | <p>Is there a way to tell if a thread has exited normally or because of an exception?</p>
| 6 | 2009-06-12T13:23:42Z | 987,139 | <p>As mentioned, a wrapper around the Thread class could catch that state. Here's an example.</p>
<pre><code>>>> from threading import Thread
>>> class MyThread(Thread):
def run(self):
try:
Thread.run(self)
except Exception as self.err:
pass # or raise
else:
self... | 8 | 2009-06-12T15:03:59Z | [
"python",
"multithreading",
"exit-code"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not q... | 4 | 2009-06-12T13:48:29Z | 988,766 | <p>I would stick with smbfs. It's only a matter of time before you want to access those shared files with something other than Python.</p>
| -2 | 2009-06-12T20:02:38Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not q... | 4 | 2009-06-12T13:48:29Z | 989,430 | <p>I also have had trouble using smbfs (random system lockdowns and reboots) and needed a quick answer.</p>
<p>I've also tried the <code>smbc</code> module but couldn't get any data with it. I went just as far as accessing the directory structure, just like you.</p>
<p>Time was up and I had to deliver the code, so I ... | 10 | 2009-06-12T22:56:51Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not q... | 4 | 2009-06-12T13:48:29Z | 11,393,225 | <p>Provided you have an open context (see the unit tests here)<br>
* <a href="https://github.com/ioggstream/pysmbc/tree/master/tests" rel="nofollow">https://github.com/ioggstream/pysmbc/tree/master/tests</a></p>
<pre><code>suri = 'smb://' + settings.SERVER + '/' + settings.SHARE + '/test.dat'
dpath = '/tmp/destina... | 0 | 2012-07-09T10:27:23Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not q... | 4 | 2009-06-12T13:48:29Z | 13,457,331 | <p>If you've managed to get the directory structure then you have a working context. The key to actually accessing files is the undocumented flags argument of <code>Context.open</code>. (I haven't figured out what mode is for either but it doesn't seem necessary.)</p>
<p><code>flags</code> is how you tell pysmbc what... | 0 | 2012-11-19T15:50:31Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not q... | 4 | 2009-06-12T13:48:29Z | 37,755,535 | <p>If don't know if this is more clearly stated, but here's what I gleaned from this page and sorted out from a little extra Google-ing:</p>
<pre><code>def do_auth (server, share, workgroup, username, password):
return ('MYDOMAIN', 'myacct', 'mypassword')
# Create the context
ctx = smbc.Context (auth_fn=do_auth)
d... | 0 | 2016-06-10T19:06:47Z | [
"python",
"samba"
] |
How do I get a value node moved up to be an attribute of its parent node? | 986,925 | <p>What do I need to change so the Name node under FieldRef is an attribute of FieldRef, and not a child node?</p>
<p>Suds currently generates the following soap:</p>
<pre><code><ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef>
<ns0:Name>_ows_ID</ns0:Name>
&... | 0 | 2009-06-12T14:27:37Z | 987,501 | <pre><code>from suds.sax.element import Element
#create the nodes
q = Element('query')
where=Element('Where')
eq=Element('Eq')
fieldref=Element('FieldRef')
fieldref.set('Name', '_ows_ID')
value=Element('Value')
value.setText('66')
#append them
eq.append(fieldref)
eq.append(value)
where.append(eq)
q.append(where)
</cod... | 0 | 2009-06-12T15:59:48Z | [
"python",
"soap",
"suds"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,253 | <p>Using Python you can use <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> to download webpages and use the version value to change the user-agent.</p>
<p>There is a very good example on <a href="http://wolfprojects.altervista.org/changeua.php" rel="nofollow">http://wolfprojects.altervi... | 2 | 2009-06-12T15:22:12Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,257 | <p>I assume you mean a user-agent string in an HTTP request? This is just an HTTP header that gets sent along with your request.</p>
<p>using Python's urllib2:</p>
<pre><code>import urllib2
url = 'http://foo.com/'
# add a header to define a custon User-Agent
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSI... | 7 | 2009-06-12T15:22:40Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,271 | <p>In <code>urllib</code>, it's done like this:</p>
<pre><code>import urllib
class AppURLopener(urllib.FancyURLopener):
version = "MyStrangeUserAgent"
urllib._urlopener = AppURLopener()
</code></pre>
<p>and then just use <code>urllib.urlopen</code> normally. In <code>urllib2</code>, use <code>req = urllib2.Requ... | 3 | 2009-06-12T15:24:28Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,297 | <p>If you want to change the user agent string you send when opening web pages, google around for a Firefox plugin. ;) For example, I found <a href="https://addons.mozilla.org/en-US/firefox/addon/59" rel="nofollow">this one</a>. Or you could write a proxy server in Python, which changes all your requests independent of... | 0 | 2009-06-12T15:28:03Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,360 | <p><code>urllib2</code> is nice because it's built in, but I tend to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> when I have the choice. It extends a lot of <code>urllib2</code>'s functionality (though much of it has been added to python in recent years). Anyhow, if it's what ... | 2 | 2009-06-12T15:38:03Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 8,666,088 | <p>Updated for Python 3.2 (py3k):</p>
<pre><code>import urllib.request
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
url = 'http://www.google.com'
request = urllib.request.Request(url, b'', headers)
response = urllib.request.urlopen(request).read()
</code></pre>
| 0 | 2011-12-29T09:36:56Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 20,447,014 | <p>As mentioned in the answers above, the user-agent field in the http request header can be changed using builtin modules in python such as urllib2. At the same time, it is also important to analyze what exactly the web server sees. A recent post on <a href="http://remotalks.blogspot.com/2013/12/user-agent-method-used... | 1 | 2013-12-07T21:39:02Z | [
"python",
"user-agent"
] |
adding a **kwarg to a class | 987,237 | <pre><code>class StatusForm(ModelForm):
bases = forms.ModelMultipleChoiceField(
queryset=Base.objects.all(), #this should get overwritten
widget=forms.SelectMultiple,
)
class Meta:
model = HiringStatus
exclude = ('company', 'date')
def __init__(self, *args, **kwargs):
super(StatusForm, self).__init... | 3 | 2009-06-12T15:19:15Z | 987,268 | <p>That's because you're unpacking kwargs to the super constructor.
Try to put this before calling super:</p>
<pre><code>if kwargs.has_key('bases_queryset'):
bases_queryset = kwargs['bases_queryset']
del kwargs['bases_queryset']
</code></pre>
<p>but it's not an ideal solution...</p>
| 11 | 2009-06-12T15:24:18Z | [
"python",
"django"
] |
adding a **kwarg to a class | 987,237 | <pre><code>class StatusForm(ModelForm):
bases = forms.ModelMultipleChoiceField(
queryset=Base.objects.all(), #this should get overwritten
widget=forms.SelectMultiple,
)
class Meta:
model = HiringStatus
exclude = ('company', 'date')
def __init__(self, *args, **kwargs):
super(StatusForm, self).__init... | 3 | 2009-06-12T15:19:15Z | 987,307 | <p>As @Keeper indicates, you must not pass your "new" keyword arguments to the superclass. Best may be to do, before you call super's <code>__init__</code>:</p>
<pre><code>bqs = kwargs.pop('bases_queryset', None)
</code></pre>
<p>and after that <code>__init__</code> call, check <code>if bqs is not None:</code> instea... | 11 | 2009-06-12T15:29:33Z | [
"python",
"django"
] |
orbited twisted installation problems | 987,632 | <p>i am geting folloing error when i am trying to start orbited server</p>
<pre><code>C:\Python26\Scripts>orbited
Traceback (most recent call last):
File "C:\Python26\Scripts\orbited-script.py", line 8, in <module>
load_entry_point('orbited==0.7.9', 'console_scripts', 'orbited')()
File "C:\Python26\li... | 1 | 2009-06-12T16:25:56Z | 987,840 | <p>I'd start by installing <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">the win32 extensions</a>. If you have done so already, this is probably a path issue.</p>
| 2 | 2009-06-12T17:07:27Z | [
"python",
"twisted"
] |
How can I change a user agent string programmatically? | 987,802 | <p>I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server. </p>
<p>How can I do this in Python?</p>
| 1 | 2009-06-12T16:59:36Z | 987,812 | <p>Why not use an existing proxy such as <a href="http://www.charlesproxy.com/" rel="nofollow">Charles HTTP Proxy</a>? It has the ability to rewrite headers and do all sorts of cool stuff to requests and responses.</p>
| 2 | 2009-06-12T17:02:10Z | [
"python"
] |
How can I change a user agent string programmatically? | 987,802 | <p>I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server. </p>
<p>How can I do this in Python?</p>
| 1 | 2009-06-12T16:59:36Z | 987,817 | <p><a href="http://proxies.xhaus.com/" rel="nofollow">This</a> is a list of HTTP proxies in python.</p>
| 1 | 2009-06-12T17:02:47Z | [
"python"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 987,914 | <p>According to the documentation is is <a href="http://bugs.python.org/issue3428" rel="nofollow">undocumented</a></p>
<p>to get access to the message it looks like you do something like:</p>
<pre><code>a, b=urllib.urlretrieve('http://google.com/abc.jpg', r'c:\abc.jpg')
</code></pre>
<p>b is the message instance</p>... | 3 | 2009-06-12T17:21:43Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 988,339 | <p>Consider using <code>urllib2</code> if it possible in your case. It is more advanced and easy to use than <code>urllib</code>.</p>
<p>You can detect any HTTP errors easily:</p>
<pre><code>>>> import urllib2
>>> resp = urllib2.urlopen("http://google.com/abc.jpg")
Traceback (most recent call last)... | 20 | 2009-06-12T18:46:04Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 990,378 | <p>I ended up with my own <code>retrieve</code> implementation, with the help of <code>pycurl</code> it supports more protocols than urllib/urllib2, hope it can help other people.</p>
<pre><code>import tempfile
import pycurl
import os
def get_filename_parts_from_url(url):
fullname = url.split('/')[-1].split('#')[... | 1 | 2009-06-13T09:18:53Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 1,993,124 | <p>You can create a new URLopener (inherit from FancyURLopener) and throw exceptions or handle errors any way you want. Unfortunately, FancyURLopener ignores 404 and other errors. See this question:</p>
<p><a href="http://stackoverflow.com/questions/1308542/how-to-catch-404-error-in-urllib-urlretrieve">http://stackove... | 1 | 2010-01-02T22:36:30Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 9,740,603 | <p>I keep it simple:</p>
<pre><code># Simple downloading with progress indicator, by Cees Timmerman, 16mar12.
import urllib2
remote = r"http://some.big.file"
local = r"c:\downloads\bigfile.dat"
u = urllib2.urlopen(remote)
h = u.info()
totalSize = int(h["Content-Length"])
print "Downloading %s bytes..." % totalSize... | 4 | 2012-03-16T16:02:06Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 35,767,309 | <pre><code>class MyURLopener(urllib.FancyURLopener):
http_error_default = urllib.URLopener.http_error_default
url = "http://page404.com"
filename = "download.txt"
def reporthook(blockcount, blocksize, totalsize):
pass
...
try:
(f,headers)=MyURLopener().retrieve(url, filename, reporthook)
except Except... | 0 | 2016-03-03T08:53:22Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 35,856,359 | <p>:) My first post on StackOverflow, have been a lurker for years. :)</p>
<p>Sadly dir(urllib.urlretrieve) is deficient in useful information.
So from this thread thus far I tried writing this:</p>
<pre><code>a,b = urllib.urlretrieve(imgURL, saveTo)
print "A:", a
print "B:", b
</code></pre>
<p>which produced this:<... | 0 | 2016-03-07T23:44:29Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on goo... | 41 | 2009-06-12T17:15:33Z | 35,857,007 | <p>Results against another server/website - what comes back in "B" is a bit random, but one can test for certain values:</p>
<pre><code>A: get_good.jpg
B: Date: Tue, 08 Mar 2016 00:44:19 GMT
Server: Apache
Last-Modified: Sat, 02 Jan 2016 09:17:21 GMT
ETag: "524cf9-18afe-528565aef9ef0"
Accept-Ranges: bytes
Content-Leng... | 0 | 2016-03-08T00:53:37Z | [
"python",
"networking",
"urllib"
] |
How do I operate on the actual object, not a copy, in a python for loop? | 988,155 | <p>let's say I have a list</p>
<pre><code>a = [1,2,3]
</code></pre>
<p>I'd like to increment every item of that list in place. I want to do something as syntactically easy as</p>
<pre><code>for item in a:
item += 1
</code></pre>
<p>but in that example python uses just the value of <code>item</code>, not its ac... | 5 | 2009-06-12T18:08:15Z | 988,161 | <p>Here ya go:</p>
<pre><code># Your for loop should be rewritten as follows:
for index in xrange(len(a)):
a[index] += 1
</code></pre>
<p>Incidentally, item IS a reference to the <code>item</code> in <code>a</code>, but of course you can't assign a new value to an integer. For any mutable type, your code would wo... | 17 | 2009-06-12T18:09:35Z | [
"python"
] |
How do I operate on the actual object, not a copy, in a python for loop? | 988,155 | <p>let's say I have a list</p>
<pre><code>a = [1,2,3]
</code></pre>
<p>I'd like to increment every item of that list in place. I want to do something as syntactically easy as</p>
<pre><code>for item in a:
item += 1
</code></pre>
<p>but in that example python uses just the value of <code>item</code>, not its ac... | 5 | 2009-06-12T18:08:15Z | 988,197 | <p>Instead of your <code>map</code>-based solution, here's a list-comprehension-based solution</p>
<pre><code>a = [item + 1 for item in a]
</code></pre>
| 9 | 2009-06-12T18:19:15Z | [
"python"
] |
How do I operate on the actual object, not a copy, in a python for loop? | 988,155 | <p>let's say I have a list</p>
<pre><code>a = [1,2,3]
</code></pre>
<p>I'd like to increment every item of that list in place. I want to do something as syntactically easy as</p>
<pre><code>for item in a:
item += 1
</code></pre>
<p>but in that example python uses just the value of <code>item</code>, not its ac... | 5 | 2009-06-12T18:08:15Z | 988,218 | <p>In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it.</p>
<p>What's happening is that in the line: <code>item += 1</code> you are creating a new integer (with a value of <code>item + 1</code>) and binding the name <code>item<... | 12 | 2009-06-12T18:23:15Z | [
"python"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 988,249 | <p>If the string can <em>always</em> be trusted, you could use <code>eval</code> (or use <code>literal_eval</code> as suggested; it's safe no matter what the string is.) Otherwise you need a parser. A JSON parser (such as simplejson) would work if he only ever stores content that fits with the JSON scheme.</p>
| 16 | 2009-06-12T18:30:12Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 988,251 | <p>Starting in Python 2.6 you can use the built-in <code>ast.literal_eval</code>:</p>
<pre><code>>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
</code></pre>
<p>This is safer than using <code>eval</code>. As its own docs say:</p>
<pre... | 559 | 2009-06-12T18:30:45Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 988,481 | <p>If you can't use Python 2.6, you can use a simple safeeval implmenentation like <a href="http://code.activestate.com/recipes/364469/" rel="nofollow">http://code.activestate.com/recipes/364469/</a></p>
<p>It piggybacks on the Python compiler so you don't have to do all the gross work yourself.</p>
| 3 | 2009-06-12T19:09:31Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my... | 327 | 2009-06-12T18:25:02Z | 19,391,807 | <p><a href="http://docs.python.org/2/library/json.html">http://docs.python.org/2/library/json.html</a></p>
<p>JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...</p>
<pre><code>import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_accep... | 61 | 2013-10-15T21:54:27Z | [
"python",
"string",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.