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 |
|---|---|---|---|---|---|---|---|---|---|
Python integer division yields float | 1,282,945 | <pre><code>Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
</code></pre>
<p>Is this intended? I strongly remember earlier versions returning <code>int/int=int</code>? What should I do, is there a new division operator or must I always cast?</p>
| 101 | 2009-08-15T21:48:39Z | 39,332,574 | <p>The accepted answer already mentions <a href="https://www.python.org/dev/peps/pep-0238/" rel="nofollow">PEP 238</a>. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.</p>
<p>Python maps operators like <code>+</code>, <code>-</code>, <code>*</code> and <code>/</code> to special functions, such that e.g. <code>a + b</code> is equivalent to</p>
<pre><code>a.__add__(b)
</code></pre>
<p>Regarding division in Python 2, there is by default only <code>/</code> which maps to <code>__div__</code> and the result is dependent on the input types (e.g. <code>int</code>, <code>float</code>).</p>
<p>Python 2.2 introduced the <code>__future__</code> feature <code>division</code>, which changed the division semantics the following way (TL;DR of PEP 238):</p>
<ul>
<li><code>/</code> maps to <code>__truediv__</code> which must "return a reasonable approximation of
the mathematical result of the division" (quote from PEP 238)</li>
<li><code>//</code> maps to <code>__floordiv__</code>, which should return the floored result of <code>/</code></li>
</ul>
<p>With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method <code>__div__</code> in Python's object model.</p>
<p>If you want to use the same code in Python 2 and Python 3 use</p>
<pre><code>from __future__ import division
</code></pre>
<p>and stick to the PEP 238 semantics <code>/</code> of and <code>//</code>.</p>
| 1 | 2016-09-05T14:18:11Z | [
"python",
"integer",
"python-3.x",
"division"
] |
Python - capture Popen stdout AND display on console? | 1,283,061 | <p>I want to capture stdout from a long-ish running process started via <code>subprocess.Popen(...)</code> so I'm using <code>stdout=PIPE</code> as an arg.</p>
<p>However, because it's a long running process I also want to send the output to the console (as if I hadn't piped it) to give the user of the script an idea that it's still working.</p>
<p>Is this at all possible?</p>
<p>Cheers.</p>
| 5 | 2009-08-15T22:48:42Z | 1,283,062 | <p>Can you simply <code>print</code> it as you read it from the pipe?</p>
| 1 | 2009-08-15T22:49:50Z | [
"python",
"pipe",
"popen"
] |
Python - capture Popen stdout AND display on console? | 1,283,061 | <p>I want to capture stdout from a long-ish running process started via <code>subprocess.Popen(...)</code> so I'm using <code>stdout=PIPE</code> as an arg.</p>
<p>However, because it's a long running process I also want to send the output to the console (as if I hadn't piped it) to give the user of the script an idea that it's still working.</p>
<p>Is this at all possible?</p>
<p>Cheers.</p>
| 5 | 2009-08-15T22:48:42Z | 1,283,066 | <p>The buffering your long-running sub-process is probably performing will make your console output jerky and very bad UX. I suggest you consider instead using <a href="http://pexpect.sourceforge.net/pexpect.html">pexpect</a> (or, on Windows, <a href="http://code.google.com/p/wexpect/">wexpect</a>) to defeat such buffering and get smooth, regular output from the sub-process. For example (on just about any unix-y system, after installing pexpect):</p>
<pre><code>>>> import pexpect
>>> child = pexpect.spawn('/bin/bash -c "echo ba; sleep 1; echo bu"', logfile=sys.stdout); x=child.expect(pexpect.EOF); child.close()
ba
bu
>>> child.before
'ba\r\nbu\r\n'
</code></pre>
<p>The ba and bu will come with the proper timing (about a second between them). Note the output is not subject to normal terminal processing, so the carriage returns are left in there -- you'll need to post-process the string yourself (just a simple <code>.replace</code>!-) if you need <code>\n</code> as end-of-line markers (the lack of processing is important just in case the sub-process is writing binary data to its stdout -- this ensures all the data's left intact!-).</p>
| 5 | 2009-08-15T22:52:28Z | [
"python",
"pipe",
"popen"
] |
Python - capture Popen stdout AND display on console? | 1,283,061 | <p>I want to capture stdout from a long-ish running process started via <code>subprocess.Popen(...)</code> so I'm using <code>stdout=PIPE</code> as an arg.</p>
<p>However, because it's a long running process I also want to send the output to the console (as if I hadn't piped it) to give the user of the script an idea that it's still working.</p>
<p>Is this at all possible?</p>
<p>Cheers.</p>
| 5 | 2009-08-15T22:48:42Z | 1,283,191 | <p>Alternatively, you can pipe your process into tee and capture only one of the streams.
Something along the lines of <code>sh -c 'process interesting stuff' | tee /dev/stderr</code>.</p>
<p>Of course, this only works on Unix-like systems.</p>
| 1 | 2009-08-16T00:22:38Z | [
"python",
"pipe",
"popen"
] |
Python - capture Popen stdout AND display on console? | 1,283,061 | <p>I want to capture stdout from a long-ish running process started via <code>subprocess.Popen(...)</code> so I'm using <code>stdout=PIPE</code> as an arg.</p>
<p>However, because it's a long running process I also want to send the output to the console (as if I hadn't piped it) to give the user of the script an idea that it's still working.</p>
<p>Is this at all possible?</p>
<p>Cheers.</p>
| 5 | 2009-08-15T22:48:42Z | 1,284,860 | <p>S. Lott's comment points to <a href="http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess">http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess</a> and <a href="http://stackoverflow.com/questions/1085071/real-time-intercepting-of-stdout-from-another-process-in-python">http://stackoverflow.com/questions/1085071/real-time-intercepting-of-stdout-from-another-process-in-python</a></p>
<p>I'm curious that Alex's answer here is different from his answer 1085071.
My simple little experiments with the answers in the two other referenced questions has given good results...</p>
<p>I went and looked at wexpect as per Alex's answer above, but I have to say reading the comments in the code I was not left a very good feeling about using it.</p>
<p>I guess the meta-question here is when will pexpect/wexpect be one of the Included Batteries?</p>
| 2 | 2009-08-16T17:40:02Z | [
"python",
"pipe",
"popen"
] |
Python - capture Popen stdout AND display on console? | 1,283,061 | <p>I want to capture stdout from a long-ish running process started via <code>subprocess.Popen(...)</code> so I'm using <code>stdout=PIPE</code> as an arg.</p>
<p>However, because it's a long running process I also want to send the output to the console (as if I hadn't piped it) to give the user of the script an idea that it's still working.</p>
<p>Is this at all possible?</p>
<p>Cheers.</p>
| 5 | 2009-08-15T22:48:42Z | 9,172,003 | <p>Inspired by pty.openpty() suggestion somewhere above, tested on python2.6, linux. Publishing since it took a while to make this working properly, w/o buffering...</p>
<pre><code>def call_and_peek_output(cmd, shell=False):
import pty, subprocess
master, slave = pty.openpty()
p = subprocess.Popen(cmd, shell=shell, stdin=None, stdout=slave, close_fds=True)
os.close(slave)
line = ""
while True:
try:
ch = os.read(master, 1)
except OSError:
# We get this exception when the spawn process closes all references to the
# pty descriptor which we passed him to use for stdout
# (typically when it and its childs exit)
break
line += ch
sys.stdout.write(ch)
if ch == '\n':
yield line
line = ""
if line:
yield line
ret = p.wait()
if ret:
raise subprocess.CalledProcessError(ret, cmd)
for l in call_and_peek_output("ls /", shell=True):
pass
</code></pre>
| 1 | 2012-02-07T06:38:04Z | [
"python",
"pipe",
"popen"
] |
Programmatically change font color of text in PDF | 1,283,065 | <p>I'm not familiar with the PDF specification at all. I was wondering if it's possible to directly manipulate a PDF file so that certain blocks of text that I've identified as important are highlighted in colors of my choice. Language of choice would be python. </p>
| 7 | 2009-08-15T22:52:13Z | 1,283,166 | <p>It's possible, but not necessarily easy, because the PDF format is so rich. You can find a document describing it in detail <a href="http://www.adobe.com/devnet/acrobat/pdfs/PDF32000%5F2008.pdf">here</a>. The first elementary example it gives about how PDFs display text is:</p>
<pre><code>BT
/F13 12 Tf
288 720 Td
(ABC) Tj
ET
</code></pre>
<p>BT and ET are commands to begin and end a text object; Tf is a command to use external font resource F13 (which happens to be Helvetica) at size 12; Td is a command to position the cursor at the given coordinates; Tj is a command to write the glyphs for the previous string. The flavor is somewhat "reverse-polish notation"-oid, and indeed quite close to the flavor of Postscript, one of Adobe's other great contributions to typesetting.</p>
<p>The problem is, there is nothing in the PDF specs that says that text that "looks" like it belongs together on the page as displayed must actually "be" together; since precise coordinates can always be given, if the PDF is generated by a sophisticated typography layout system, it might position text precisely, character by character, by coordinates. Reconstructing text in form of words and sentences is therefore not necessarily easy -- it's almost as hard as optical text recognition, except that you are given the characters precisely (well -- almost... some alleged "images" might actually display as characters...;-).</p>
<p><a href="http://pybrary.net/pyPdf/">pyPdf</a> is a very simple pure-Python library that's a good starting point for playing around with PDF files. Its "text extraction" function is quite elementary and does nothing but concatenate the arguments of a few text-drawing commands; you'll see that suffices on some docs, and is quite unusable on others, but at least it's a start. As distributed, pyPdf does just about nothing with colors, but with some hacking that could be remedied.</p>
<p><a href="http://www.reportlab.com/">reportlab</a>'s powerful Python library is entirely focused on generating new PDFs, not on interpreting or modifying existing ones. At the other extreme, pure Python library <a href="http://www.unixuser.org/~euske/python/pdfminer/index.html">pdfminer</a> entirely focusing on parsing PDF files; it does do some clustering to try and reconstruct text in cases in which simpler libraries would be stumped.</p>
<p>I don't know of an existing library that performs the transformational tasks you desire, but it should be feasible to mix and match some of these existing ones to get most of it done... good luck!</p>
| 11 | 2009-08-16T00:07:21Z | [
"python",
"pdf",
"fonts"
] |
Programmatically change font color of text in PDF | 1,283,065 | <p>I'm not familiar with the PDF specification at all. I was wondering if it's possible to directly manipulate a PDF file so that certain blocks of text that I've identified as important are highlighted in colors of my choice. Language of choice would be python. </p>
| 7 | 2009-08-15T22:52:13Z | 1,285,029 | <p>Highlight is possible in pdf file using PDF annotations but doing it natively is not that easy job. If any of the mentioned library provide such facility is something that you may look for.</p>
| 0 | 2009-08-16T18:49:21Z | [
"python",
"pdf",
"fonts"
] |
A python based PowerShell? | 1,283,198 | <p>I just took a brief look at PowerShell (I knew it as Monad shell). My ignorant eyes see it more or less like a hybrid between regular bash and python. I would consider such integration between the two environments very cool on linux and osx, so I was wondering if it already exists (ipython is not really the same), and if not, why ?</p>
| 9 | 2009-08-16T00:35:10Z | 1,283,259 | <p>As far as PowerShell on Linux or OSX, see <a href="http://igorshare.wordpress.com/2008/04/06/pash-cross-platform-powershell-is-out-in-the-wild-announcement/" rel="nofollow">Pash</a>, a cross-platform version of PowerShell using Mono.</p>
| 1 | 2009-08-16T01:17:51Z | [
"python",
"bash",
"powershell"
] |
A python based PowerShell? | 1,283,198 | <p>I just took a brief look at PowerShell (I knew it as Monad shell). My ignorant eyes see it more or less like a hybrid between regular bash and python. I would consider such integration between the two environments very cool on linux and osx, so I was wondering if it already exists (ipython is not really the same), and if not, why ?</p>
| 9 | 2009-08-16T00:35:10Z | 1,283,300 | <p>I've only dabbled in Powershell, but what distinguishes it for me is the ability to pipe actual objects in the shell. In that respect, the closest I've found is actually using the IPython shell with <code>ipipe</code>:</p>
<ul>
<li><a href="http://wiki.ipython.org/Using_ipipe" rel="nofollow">Using ipipe</a></li>
<li><a href="http://wiki.ipython.org/Cookbook/Adding_support_for_ipipe" rel="nofollow">Adding support for ipipe</a></li>
</ul>
<p>Following the recipes shown on that page and cooking up my own extensions, I don't often leave the IPython shell for bash. YMMV. </p>
| 10 | 2009-08-16T01:48:06Z | [
"python",
"bash",
"powershell"
] |
A python based PowerShell? | 1,283,198 | <p>I just took a brief look at PowerShell (I knew it as Monad shell). My ignorant eyes see it more or less like a hybrid between regular bash and python. I would consider such integration between the two environments very cool on linux and osx, so I was wondering if it already exists (ipython is not really the same), and if not, why ?</p>
| 9 | 2009-08-16T00:35:10Z | 3,207,044 | <p>I think Hotwire is basically what you're thinking of:</p>
<p><a href="http://code.google.com/p/hotwire-shell/wiki/GettingStarted0700" rel="nofollow">http://code.google.com/p/hotwire-shell/wiki/GettingStarted0700</a></p>
<p>It's a shell-type environment where you can access the outputs as Python objects.</p>
<p>It doesn't have all PowerShell's handy hooks into various Windows system information, though. For that, you may want to literally integrate Python with PowerShell; that's described in <a href="http://www.ironpythoninaction.com/" rel="nofollow">IronPython In Action</a>.</p>
| 3 | 2010-07-08T19:08:21Z | [
"python",
"bash",
"powershell"
] |
A python based PowerShell? | 1,283,198 | <p>I just took a brief look at PowerShell (I knew it as Monad shell). My ignorant eyes see it more or less like a hybrid between regular bash and python. I would consider such integration between the two environments very cool on linux and osx, so I was wondering if it already exists (ipython is not really the same), and if not, why ?</p>
| 9 | 2009-08-16T00:35:10Z | 39,823,437 | <p>An open source version of powershell does now exist. It can be found at <a href="https://msdn.microsoft.com/en-us/powershell" rel="nofollow">https://msdn.microsoft.com/en-us/powershell</a>.</p>
| 1 | 2016-10-03T01:30:42Z | [
"python",
"bash",
"powershell"
] |
Recursive generation + filtering. Better non-recursive? | 1,283,266 | <p>I have the following need (in python): </p>
<ul>
<li>generate all possible tuples of length 12 (could be more) containing either 0, 1 or 2 (basically, a ternary number with 12 digits)</li>
<li>filter these tuples according to specific criteria, culling those not good, and keeping the ones I need.</li>
</ul>
<p>As I had to deal with small lengths until now, the functional approach was neat and simple: a recursive function generates all possible tuples, then I cull them with a filter function. Now that I have a larger set, the generation step is taking too much time, much longer than needed as most of the paths in the solution tree will be culled later on, so I could skip their creation.</p>
<p>I have two solutions to solve this:</p>
<ol>
<li>derecurse the generation into a loop, and apply the filter criteria on each new 12-digits entity</li>
<li>integrate the filtering in the recursive algorithm, so to prevent it stepping into paths that are already doomed.</li>
</ol>
<p>My preference goes to 1 (seems easier) but I would like to hear your opinion, in particular with an eye towards how a functional programming style deals with such cases.</p>
| 1 | 2009-08-16T01:23:16Z | 1,283,281 | <p>How about</p>
<pre><code>import itertools
results = []
for x in itertools.product(range(3), repeat=12):
if myfilter(x):
results.append(x)
</code></pre>
<p>where <code>myfilter</code> does the selection. Here, for example, only allowing result with 10 or more 1's,</p>
<pre><code>def myfilter(x): # example filter, only take lists with 10 or more 1s
return x.count(1)>=10
</code></pre>
<p>That is, my suggestion is your option 1. For some cases it may be slower because (depending on your criteria) you many generate many lists that you don't need, but it's much more general and very easy to code.</p>
<p>Edit: This approach also has a one-liner form, as suggested in the comments by hughdbrown:</p>
<pre><code>results = [x for x in itertools.product(range(3), repeat=12) if myfilter(x)]
</code></pre>
| 4 | 2009-08-16T01:36:16Z | [
"python",
"functional-programming",
"recursion"
] |
Recursive generation + filtering. Better non-recursive? | 1,283,266 | <p>I have the following need (in python): </p>
<ul>
<li>generate all possible tuples of length 12 (could be more) containing either 0, 1 or 2 (basically, a ternary number with 12 digits)</li>
<li>filter these tuples according to specific criteria, culling those not good, and keeping the ones I need.</li>
</ul>
<p>As I had to deal with small lengths until now, the functional approach was neat and simple: a recursive function generates all possible tuples, then I cull them with a filter function. Now that I have a larger set, the generation step is taking too much time, much longer than needed as most of the paths in the solution tree will be culled later on, so I could skip their creation.</p>
<p>I have two solutions to solve this:</p>
<ol>
<li>derecurse the generation into a loop, and apply the filter criteria on each new 12-digits entity</li>
<li>integrate the filtering in the recursive algorithm, so to prevent it stepping into paths that are already doomed.</li>
</ol>
<p>My preference goes to 1 (seems easier) but I would like to hear your opinion, in particular with an eye towards how a functional programming style deals with such cases.</p>
| 1 | 2009-08-16T01:23:16Z | 1,283,285 | <p><code>itertools</code> has functionality for dealing with this. However, here is a (hardcoded) way of handling with a generator:</p>
<pre><code>T = (0,1,2)
GEN = ((a,b,c,d,e,f,g,h,i,j,k,l) for a in T for b in T for c in T for d in T for e in T for f in T for g in T for h in T for i in T for j in T for k in T for l in T)
for VAL in GEN:
# Filter VAL
print VAL
</code></pre>
| 1 | 2009-08-16T01:39:12Z | [
"python",
"functional-programming",
"recursion"
] |
Recursive generation + filtering. Better non-recursive? | 1,283,266 | <p>I have the following need (in python): </p>
<ul>
<li>generate all possible tuples of length 12 (could be more) containing either 0, 1 or 2 (basically, a ternary number with 12 digits)</li>
<li>filter these tuples according to specific criteria, culling those not good, and keeping the ones I need.</li>
</ul>
<p>As I had to deal with small lengths until now, the functional approach was neat and simple: a recursive function generates all possible tuples, then I cull them with a filter function. Now that I have a larger set, the generation step is taking too much time, much longer than needed as most of the paths in the solution tree will be culled later on, so I could skip their creation.</p>
<p>I have two solutions to solve this:</p>
<ol>
<li>derecurse the generation into a loop, and apply the filter criteria on each new 12-digits entity</li>
<li>integrate the filtering in the recursive algorithm, so to prevent it stepping into paths that are already doomed.</li>
</ol>
<p>My preference goes to 1 (seems easier) but I would like to hear your opinion, in particular with an eye towards how a functional programming style deals with such cases.</p>
| 1 | 2009-08-16T01:23:16Z | 1,283,297 | <p>I'd implement an iterative binary adder or hamming code and run that way.</p>
| 0 | 2009-08-16T01:47:57Z | [
"python",
"functional-programming",
"recursion"
] |
Python Data Descriptor With Pass-through __set__ command | 1,283,435 | <p>I'm having a bit of an issue solving a problem I'm looking at. I have a specialized set of functions which are going to be in use across a program, which are basically dynamic callables which can replace functions and methods. Due to the need to have them work properly to emulate the functionality of methods, these functions override <code>__get__</code> to provide a wrapped version that gives access to the retrieving object.</p>
<p>Unfortunately, <code>__get__</code> does not work if the function is set directly on an instance. This is because only "data descriptors" call the <code>__get__</code> function when the key is found in the <code>__dict__</code> of an instance. The only solution to this that comes to mind is: trick python into thinking this is a data descriptor. This involves creating a <code>__set__</code> function on the descriptor. Ideally, I want this <code>__set__</code> function to work as a pass-through (returns control to the caller and continues evaluating as if it doesn't exist).</p>
<p>Is there any way to trick python into thinking that a descriptor is a data descriptor but letting a containing class/instance still be able to use its setattr command as normal?</p>
<p>Also, I am aware that it is possible to do this with an override of <code>__getattribute__</code> for the caller. However, this is a bad solution because I would have to do this for the 'object' built-in and anything that overrides it. Not exactly a great solution.</p>
<p>Alternatively, if there is any alternative solution I would be happy to hear it.</p>
<h2>Here is a problem example:</h2>
<pre><code>class Descriptor(object):
def __get__(self, obj, objtype = None):
return None
class Caller(object):
a = Descriptor()
print a
>>> None
x = Caller()
print a
>>> None
x.a = Descriptor()
print x.a
>>> <__main__.Descriptor object at 0x011D7F10>
</code></pre>
<p><hr /></p>
<p>The last case should print 'None' to maintain consistency.</p>
<p>If you add a <code>__set__</code> to the Descriptor, this will print 'None' (as desired). However, this messes up any command of x.a = (some value) from working as it had previously. Since I do not want to mess up this functionality, that is not helpful. Any solutions would be great.</p>
<p>Correction: My prior idea would still not work, as I misunderstood the descriptor handling slightly. Apparently if a descriptor is not on a class at all, it will never be called- regardless of the <strong>set</strong>. The condition I had only helps if there is a dict val and a class accessor of the same name. I am actually looking for a solution more along the lines of: <a href="http://blog.brianbeck.com/post/74086029/instance-descriptors" rel="nofollow">http://blog.brianbeck.com/post/74086029/instance-descriptors</a> but that does not involve having everything under the sun inherit a specialized interface.</p>
<p>Unfortunately, given this new understanding of the descriptor interface this may not be possible? Why oh why would python make decorators essentially non-dynamic?</p>
| 1 | 2009-08-16T04:26:11Z | 1,283,461 | <p>I think the cleanest solution is to leave <code>__set__</code> alone, and set the descriptor on the class -- wrapping the original class if needed. I.e., instead of <code>x.a = Descriptor()</code>, do <code>setdesc(x, 'a', Descriptor()</code> where:</p>
<pre><code>class Wrapper(object): pass
def setdesc(x, name, desc):
t = type(x)
if not issubclass(t, wrapper):
class awrap(Wrapper, t): pass
x.__class__ = awrap
setattr(x.__class__, name, desc)
</code></pre>
<p>This is the general approach I suggest when somebody wants to "set on an instance" anything (special method or descriptor) that needs to be set on the class to work, but doesn't want to affect the instance's original class.</p>
<p>Of course, it all works well only if you have new-style classes, but then descriptors don't really play well with old-style classes anyhow;-).</p>
| 1 | 2009-08-16T04:45:30Z | [
"python",
"function",
"methods",
"set",
"descriptor"
] |
Python Data Descriptor With Pass-through __set__ command | 1,283,435 | <p>I'm having a bit of an issue solving a problem I'm looking at. I have a specialized set of functions which are going to be in use across a program, which are basically dynamic callables which can replace functions and methods. Due to the need to have them work properly to emulate the functionality of methods, these functions override <code>__get__</code> to provide a wrapped version that gives access to the retrieving object.</p>
<p>Unfortunately, <code>__get__</code> does not work if the function is set directly on an instance. This is because only "data descriptors" call the <code>__get__</code> function when the key is found in the <code>__dict__</code> of an instance. The only solution to this that comes to mind is: trick python into thinking this is a data descriptor. This involves creating a <code>__set__</code> function on the descriptor. Ideally, I want this <code>__set__</code> function to work as a pass-through (returns control to the caller and continues evaluating as if it doesn't exist).</p>
<p>Is there any way to trick python into thinking that a descriptor is a data descriptor but letting a containing class/instance still be able to use its setattr command as normal?</p>
<p>Also, I am aware that it is possible to do this with an override of <code>__getattribute__</code> for the caller. However, this is a bad solution because I would have to do this for the 'object' built-in and anything that overrides it. Not exactly a great solution.</p>
<p>Alternatively, if there is any alternative solution I would be happy to hear it.</p>
<h2>Here is a problem example:</h2>
<pre><code>class Descriptor(object):
def __get__(self, obj, objtype = None):
return None
class Caller(object):
a = Descriptor()
print a
>>> None
x = Caller()
print a
>>> None
x.a = Descriptor()
print x.a
>>> <__main__.Descriptor object at 0x011D7F10>
</code></pre>
<p><hr /></p>
<p>The last case should print 'None' to maintain consistency.</p>
<p>If you add a <code>__set__</code> to the Descriptor, this will print 'None' (as desired). However, this messes up any command of x.a = (some value) from working as it had previously. Since I do not want to mess up this functionality, that is not helpful. Any solutions would be great.</p>
<p>Correction: My prior idea would still not work, as I misunderstood the descriptor handling slightly. Apparently if a descriptor is not on a class at all, it will never be called- regardless of the <strong>set</strong>. The condition I had only helps if there is a dict val and a class accessor of the same name. I am actually looking for a solution more along the lines of: <a href="http://blog.brianbeck.com/post/74086029/instance-descriptors" rel="nofollow">http://blog.brianbeck.com/post/74086029/instance-descriptors</a> but that does not involve having everything under the sun inherit a specialized interface.</p>
<p>Unfortunately, given this new understanding of the descriptor interface this may not be possible? Why oh why would python make decorators essentially non-dynamic?</p>
| 1 | 2009-08-16T04:26:11Z | 1,283,545 | <p>I think I may have one answer to my question, though it's not all that pretty- it does sidestep the issue. My current plan of attack is to do what python does- bind the functions manually. I was already using my unbound function's <strong>get</strong> command to generate bound-type functions. One possible solution is to force anybody who wants to set a new function to manually bind it. It's annoying but it's not crazy. Python actually makes you do it (if you just set a function onto an instance as an attribute, it doesn't become bound).</p>
<p>It would still be nice to have this happen automatically, but it's not awful to force someone who is setting a new function to use x.a = Descriptor().<strong>get</strong>(x) which in this case will give the desired behavior (as well as for the example, for that matter). It's not a general solution but it will work for this limited problem, where method binding was being emulated basically. With that said, if anybody has a better solution I'd still be very happy to hear it.</p>
| 0 | 2009-08-16T05:51:31Z | [
"python",
"function",
"methods",
"set",
"descriptor"
] |
Entity Framwework-like ORM NOT for .NET | 1,283,646 | <p>What I really like about Entity framework is its drag and drop way of making up the whole model layer of your application. You select the tables, it joins them and you're done. If you update the database scheda, right click -> update and you're done again.</p>
<p>This seems to me miles ahead the competiting ORMs, like the mess of XML (n)Hibernate requires or the hard-to-update Django Models.</p>
<p>Without concentrating on the fact that maybe sometimes more control over the mapping process may be good, are there similar one-click (or one-command) solutions for other (mainly open source like python or php) programming languages or frameworks?</p>
<p>Thanks</p>
| 2 | 2009-08-16T07:03:56Z | 1,284,168 | <p>SQLAlchemy database reflection gets you half way there. You'll still have to declare your classes and relations between them. Actually you could easily autogenerate the classes too, but you'll still need to name the relations somehow so you might as well declare the classes manually.</p>
<p>The code to setup your database would look something like this:</p>
<pre><code>from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
metadata = MetaData(create_engine(database_url), reflect=True)
Base = declarative_base(metadata)
class Order(Base):
__table__ = metadata.tables['orders']
class OrderLine(Base):
__table__ = metadata.tables['orderlines']
order = relation(Order, backref='lines')
</code></pre>
<p>In production code, you'd probably want to cache the reflected database metadata somehow. Like for instance pickle it to a file:</p>
<pre><code>from cPickle import dump, load
import os
if os.path.exists('metadata.cache'):
metadata = load(open('metadata.cache'))
metadata.bind = create_engine(database_url)
else:
metadata = MetaData(create_engine(database_url), reflect=True)
dump(metadata, open('metadata.cache', 'w'))
</code></pre>
| 2 | 2009-08-16T12:13:09Z | [
"php",
"python",
"entity-framework",
"open-source"
] |
Entity Framwework-like ORM NOT for .NET | 1,283,646 | <p>What I really like about Entity framework is its drag and drop way of making up the whole model layer of your application. You select the tables, it joins them and you're done. If you update the database scheda, right click -> update and you're done again.</p>
<p>This seems to me miles ahead the competiting ORMs, like the mess of XML (n)Hibernate requires or the hard-to-update Django Models.</p>
<p>Without concentrating on the fact that maybe sometimes more control over the mapping process may be good, are there similar one-click (or one-command) solutions for other (mainly open source like python or php) programming languages or frameworks?</p>
<p>Thanks</p>
| 2 | 2009-08-16T07:03:56Z | 1,321,695 | <p>I do not like âdrag and dropâ create of data access code. </p>
<p>At first sight it seems easy, but then you make a change to the database and have to update the data access code. This is where it becomes hard, as you often have to redo what you have done before, or hand edit the code the drag/drop designer created. Often when you make a change to one field mapping with a drag/drop designer, the output file has unrelated lines changes, so you can not use your source code control system to confirm you have make the intended change (and not change anything else).</p>
<p>However having to create/edit xml configuring files is not nice every time you refractor your code or change your database schema you have to update the mapping file. It is also very hard to get started with mapping files and tracking down what looks like simple problem can take ages.</p>
<p>There are two other options:</p>
<p>Use a code generator like <a href="http://www.codesmithtools.com/features/frameworks.aspx" rel="nofollow">CodeSmith</a> that comes with templates for many ORM systems. When (not if) you need to customize the output you can edit the template, but the simple case are taken care of for you. That ways you just rerun the code generator every time you change the database schema and get a repeatable result.</p>
<p>And/or use fluent interface (e.g <a href="http://fluentnhibernate.org/" rel="nofollow">Fluent NHibernate</a>) to configure your ORM system, this avoids the need to the Xml config file and in most cases you can use naming conventions to link fields to columns etc. This will be harder to start with then a drag/drop designer but will pay of in the long term if you do match refactoring of the code or database.</p>
<p>Another option is to use a model that you generate both your database and code from. The âmodelâ is your source code and is kept under version control. This is called âModel Driven Developmentâ and can be great if you have lots of classes that have simpler patterns, as you only need to create the template for each pattern once.</p>
| 2 | 2009-08-24T10:54:54Z | [
"php",
"python",
"entity-framework",
"open-source"
] |
Entity Framwework-like ORM NOT for .NET | 1,283,646 | <p>What I really like about Entity framework is its drag and drop way of making up the whole model layer of your application. You select the tables, it joins them and you're done. If you update the database scheda, right click -> update and you're done again.</p>
<p>This seems to me miles ahead the competiting ORMs, like the mess of XML (n)Hibernate requires or the hard-to-update Django Models.</p>
<p>Without concentrating on the fact that maybe sometimes more control over the mapping process may be good, are there similar one-click (or one-command) solutions for other (mainly open source like python or php) programming languages or frameworks?</p>
<p>Thanks</p>
| 2 | 2009-08-16T07:03:56Z | 1,325,558 | <p>I have heard iBattis is good. A few companies fall back to iBattis when their programmer teams are not capable of understanding Hibernate (time issue).</p>
<p>Personally, I still like <strong>Linq2Sql</strong>. Yes, the first time someone needs to delete and redrag over a table seems like too much work, but it really is not. And the time that it doesn't update your class code when you save is really a pain, but you simply control-a your tables and drag them over again. Total remakes are very quick and painless. The classes it creates are extremely simple. You can even create multiple table entities if you like with SPs for CRUD.</p>
<p>Linking SPs to CRUD is similar to EF: You simply setup your SP with the same parameters as your table, then drag it over your table, and poof, it matches the data types.</p>
<p>A lot of people go out of their way to take IQueryable away from the repository, but you <em>can</em> limit what you <em>link</em> in linq2Sql, so IQueryable is not too bad.</p>
<p>Come to think of it, I wonder if there is a way to restrict the relations (and foreign keys).</p>
| 0 | 2009-08-25T01:06:09Z | [
"php",
"python",
"entity-framework",
"open-source"
] |
Python get wrong value for os.environ["ProgramFiles"] on 64bit vista | 1,283,664 | <p>Python 2.4.3 on a Vista64 machine.</p>
<p>The following 2 variables are in the environment:</p>
<pre><code>ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
</code></pre>
<p>But when I run the following</p>
<pre><code>import os
print os.environ["ProgramFiles"]
print os.environ["ProgramFiles(x86)"]
</code></pre>
<p>I get:</p>
<pre><code>C:\Program Files (x86)
C:\Program Files (x86)
</code></pre>
<p>Any idea how can I get the correct value of "ProgramFiles"?</p>
| 3 | 2009-08-16T07:11:16Z | 1,283,667 | <p>From the <a href="http://en.wikipedia.org/wiki/Environment%5Fvariable#Examples%5Ffrom%5FMicrosoft%5FWindows">Wikipedia page</a>:</p>
<blockquote>
<p>%ProgramFiles%</p>
<p>This variable points to Program Files directory, which stores all the installed program of Windows and others. The default on English-language systems is C:\Program Files. In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)% which defaults to C:\Program Files (x86) and %ProgramW6432% which defaults to C:\Program Files. The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).</p>
</blockquote>
<p>So to get just C:\Program Files, you apparently want to check <code>%ProgramW6432%</code>.</p>
| 11 | 2009-08-16T07:14:12Z | [
"python",
"windows",
"64bit"
] |
Python get wrong value for os.environ["ProgramFiles"] on 64bit vista | 1,283,664 | <p>Python 2.4.3 on a Vista64 machine.</p>
<p>The following 2 variables are in the environment:</p>
<pre><code>ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
</code></pre>
<p>But when I run the following</p>
<pre><code>import os
print os.environ["ProgramFiles"]
print os.environ["ProgramFiles(x86)"]
</code></pre>
<p>I get:</p>
<pre><code>C:\Program Files (x86)
C:\Program Files (x86)
</code></pre>
<p>Any idea how can I get the correct value of "ProgramFiles"?</p>
| 3 | 2009-08-16T07:11:16Z | 1,283,711 | <p>Can you install Python 2.5.4 and try again? UPDATE: I meant the x64 release of 2.5.4. AFAIK 2.4 was only available for Windows x86 and IA64, not x64.</p>
<p>I'm running 2.5.4 x64 on Win 7 x64 and I don't get the same result, but I'm not sure if the problem lies with Python or Vista in your case.</p>
<pre><code>Python 2.5.4 (r254:67916, Dec 23 2008, 15:19:34) [MSC v.1400 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print os.environ["ProgramFiles"]
C:\Program Files
>>> print os.environ["ProgramFiles(x86)"]
C:\Program Files (x86)
>>>
</code></pre>
| 4 | 2009-08-16T07:48:22Z | [
"python",
"windows",
"64bit"
] |
Python get wrong value for os.environ["ProgramFiles"] on 64bit vista | 1,283,664 | <p>Python 2.4.3 on a Vista64 machine.</p>
<p>The following 2 variables are in the environment:</p>
<pre><code>ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
</code></pre>
<p>But when I run the following</p>
<pre><code>import os
print os.environ["ProgramFiles"]
print os.environ["ProgramFiles(x86)"]
</code></pre>
<p>I get:</p>
<pre><code>C:\Program Files (x86)
C:\Program Files (x86)
</code></pre>
<p>Any idea how can I get the correct value of "ProgramFiles"?</p>
| 3 | 2009-08-16T07:11:16Z | 1,284,548 | <p>You are using the 32-bit version of Python interpreter. When using 32-bit software, WOW64 will create a new environment, with it own folders and substitutions.</p>
<p>You can see what I am talking about just by starting the 64-bit and the 32-bit version of the command prompt:</p>
<p>64-bit cmd.exe:</p>
<pre><code>C:\Documents and Settings\Administrator>set prog
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
</code></pre>
<p>32-bit cmd.exe:</p>
<pre><code>C:\WINDOWS\SysWOW64>set prog
ProgramFiles=C:\Program Files (x86)
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
</code></pre>
<p>As you can see from the second excerpt above, to get the 64-bit Program Files, you have to use the <code>ProgramW6432</code> environment variable.</p>
<p>Another approach, however, could solve also other issues that may arise in future (especially with registry settings!): just use the 64-bit version of Python - even if I do not know where to download the 64-bit version of 2.4.</p>
| 6 | 2009-08-16T15:32:07Z | [
"python",
"windows",
"64bit"
] |
URLconfs in Django | 1,283,811 | <p>I am going through the Django sample application and come across the URLConf.</p>
<p>I thought the import statement on the top resolves the url location, but for 'mysite.polls.urls' I couldn't remove the quotes by including in the import statement.</p>
<p>Why should I use quotes for 'mysite.polls.urls' and not for admin url? and what should I do if I have to remove the quotes.</p>
<pre><code> from django.conf.urls.defaults import *
...
...
(r'^polls/', include('mysite.polls.urls')),
(r'^admin/', include(admin.site.urls)),
</code></pre>
| 0 | 2009-08-16T08:50:35Z | 1,283,851 | <p>You've elided a bunch of stuff, but do you have the following statement in there?</p>
<pre><code>from django.contrib import admin
</code></pre>
<p>If so, that would explain why you don't need to quote the latter. See the django documentation for <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf" rel="nofollow">AdminSite.urls</a> for more information.</p>
<p>If you want to remove the quotes from the former, then:</p>
<pre><code>import mysite.poll.urls
...
(r'^polls/', include(mysite.poll.urls)),
...
</code></pre>
<p>should work.</p>
| 1 | 2009-08-16T09:10:43Z | [
"python",
"django"
] |
Stackless python stopped mod_python/apache from working | 1,283,856 | <p>I installed stackless pyton 2.6.2 after reading several sites that said its fully compatible with vanilla python. After installing i found that my django applications do not work any more.</p>
<p>I did reinstall django (1.1) again and now im kind of lost. The error that i get is 500:</p>
<p>Internal Server Error</p>
<p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p>
<p>Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.</p>
<p>More information about this error may be available in the server error log.
Apache/2.2.11 (Ubuntu) DAV/2 PHP/5.2.6-3ubuntu4.1 with Suhosin-Patch mod_python/3.3.1 Python/2.6.2 mod_ruby/1.2.6 Ruby/1.8.7(2008-08-11) mod_ssl/2.2.11 OpenSSL/0.9.8g Server at 127.0.0.1 Port 80</p>
<p>What else, could or should i do?</p>
<p>Edit: From 1st comment i understand that the problem is not in django but mod_python & apache? so i edited my question title.</p>
<p>Edit2: I think something is wrong with some paths setup. I tried going from mod_python to mod_wsgi, managed to finally set it up correctly only to get next error:
[Sun Aug 16 12:38:22 2009] [error] [client 127.0.0.1] raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
[Sun Aug 16 12:38:22 2009] [error] [client 127.0.0.1] ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb</p>
<p>Alan</p>
| 0 | 2009-08-16T09:14:18Z | 1,284,586 | <p>When you install a new version of Python (whether stackless or not) you also need to reinstall all of the third party modules you need -- either from sources, which you say you don't want to do, or from packages built for the new version of Python you've just installed. </p>
<p>So, check the repository from which you installed Python 2.6.2 with aptitude: does it also have versions for that specific Python of mod_python, mysqldb, django, and any other third party stuff you may need? There really is no "silver bullet" for package management and I know of no "sumo distribution" of Python bundling all the packages you could ever possibly need (if there were, it would have to be many 10s of GB;-).</p>
| 2 | 2009-08-16T15:46:07Z | [
"python",
"mod-wsgi",
"mod-python",
"stackless",
"python-stackless"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,283,926 | <p>If you're just beginning, all you'll need to know is the stuff you can get from the Python website. Failing that a quick Google is the fastest way to get (most) Python answers these days.</p>
<p>As you develop your skills and become more advanced, you'll start looking for more exciting things to do, at which point you'll naturally start coming across other libraries (for example, pygame) that you can use for your more advanced projects.</p>
| 0 | 2009-08-16T10:00:12Z | [
"python",
"libraries"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,283,941 | <p>It's very hard to answer this without knowing what you're planning on using Python for. I recommend <a href="http://www.diveintopython.org/" rel="nofollow" title="Dive Into Python">Dive Into Python</a> as a useful resource for learning Python.</p>
<p>In terms of popular third party frameworks, for web applications there's the <a href="http://www.djangoproject.com/" rel="nofollow">Django framework</a> and associated documentation, network stuff there's <a href="http://www.twistedmatrix.com/" rel="nofollow">Twisted</a> ... the list goes on. It really depends on what you're hoping to do!</p>
| 0 | 2009-08-16T10:09:17Z | [
"python",
"libraries"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,283,942 | <p>For the basics, yes, the standard Python library is probably all you'll need. But as you continue programming in Python, eventually you will need some other library for some task -- for instance, I recently needed to generate a tone at a specific, but differing, frequency for an application, and pyAudiere did the job just right.</p>
<p>A lot of the other libraries out there generate their documentation differently from the core Python style -- it's just visually different, the content is the same. Some only have docstrings, and you'll be best off reading them in a console, perhaps.</p>
<p>Regardless of how the other documentation is generated, get used to looking through the Python APIs to find the functions/classes/methods you need. When the time comes for you to use non-core libraries, you'll know <em>what</em> you want to do, but you'll have to find <em>how</em> to do it.</p>
<p>For the future, it wouldn't hurt to be familiar with C, either. There's a number of Python libraries that are actually just wrappers around C libraries, and the documentation for the Python libraries is just the same as the documentation for the C libraries. PyOpenGL comes to mind, but it's been a while since I've personally used it.</p>
| 2 | 2009-08-16T10:09:26Z | [
"python",
"libraries"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,283,963 | <p>Assuming that the standard library doesn't provide what we need and we don't have the time, or the knowledge, to implement the code we reuse 3rd party libraries.<br>
<br>
This is a common <em>attitude</em> regardless of the programming language.</p>
| 0 | 2009-08-16T10:20:44Z | [
"python",
"libraries"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,284,028 | <p>As others have said, it depends on what you're into. The package index at <a href="http://pypi.python.org/pypi/" rel="nofollow">http://pypi.python.org/pypi/</a> has categories and summaries that are helpful in seeing what other libraries are available for different purposes. (Select "Browse packages" on the left to see the categories.)</p>
| 2 | 2009-08-16T10:59:44Z | [
"python",
"libraries"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,284,615 | <p>If there's a chance that someone else ever wanted to do what you want to do, there's a chance that someone created a library for it. A few minutes Googling something like "python image library" will find you what you need, or let you know that someone hasn't created a library for your purposes.</p>
| 0 | 2009-08-16T15:55:56Z | [
"python",
"libraries"
] |
Does one often use libraries outside the standard ones? | 1,283,922 | <p>I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.</p>
<p>Edit:
Thanks very much for the responses, they were very useful. My problem is where to start on a script I have been thinking of. I want to write a script that converts images into a web format but I am not completely sure where to begin. Thanks for any more help you can provide.</p>
| 1 | 2009-08-16T09:55:51Z | 1,284,647 | <p>One very common library, that should also fit your current needs, is the <a href="http://effbot.org/zone/pil-index.htm" rel="nofollow">Python Image Library</a> (PIL).<br />
Note: the latest version is still in beta, and available only at <a href="http://effbot.org/zone/pil-index.htm" rel="nofollow">Effbot site</a>.</p>
| 1 | 2009-08-16T16:13:44Z | [
"python",
"libraries"
] |
how can I grab video from usb video capture + dvb device with gstreamer? | 1,284,008 | <p>I own a avermedia volar HX usb stick, I want to capture fromthe composite input , but I can't because I'm unable to select the input. I'm using gstreamer with + python, I think I need to use gsttuner select input but I have no experience using gstreamer's interfaces. Could someone post a simple example?</p>
<p>Thanks! </p>
| 1 | 2009-08-16T10:51:29Z | 2,342,345 | <pre><code>src = gst.element_factory_make("v4l2src", "src")
src.set_state(gst.STATE_PAUSED)
try:
# channel names will be different for each device
channels = src.list_channels()
composite = [x for x in channels if x.label == "Composite1"]
if composite:
self.src.set_channel(composite[0])
except AttributeError, e:
log.warn("Could not tune video source\n")
</code></pre>
| 1 | 2010-02-26T14:43:45Z | [
"python",
"gstreamer"
] |
how can I grab video from usb video capture + dvb device with gstreamer? | 1,284,008 | <p>I own a avermedia volar HX usb stick, I want to capture fromthe composite input , but I can't because I'm unable to select the input. I'm using gstreamer with + python, I think I need to use gsttuner select input but I have no experience using gstreamer's interfaces. Could someone post a simple example?</p>
<p>Thanks! </p>
| 1 | 2009-08-16T10:51:29Z | 2,610,696 | <p>The code shown above seems basically correct, but it will flounder on the rocks of v4l2. The strings you get will depend on what card you have:</p>
<p>On four different cards so far I've encountered:</p>
<ul>
<li>"Composite"</li>
<li>"Composite1"</li>
<li>"composite"</li>
<li>"Composite Video Input"</li>
</ul>
<p>Also be aware that some cards will have the driver lie, since the chip set has four inputs, the driver will often report four, even if the manufacturer only connects to two of them.</p>
| 0 | 2010-04-09T20:29:53Z | [
"python",
"gstreamer"
] |
how can I grab video from usb video capture + dvb device with gstreamer? | 1,284,008 | <p>I own a avermedia volar HX usb stick, I want to capture fromthe composite input , but I can't because I'm unable to select the input. I'm using gstreamer with + python, I think I need to use gsttuner select input but I have no experience using gstreamer's interfaces. Could someone post a simple example?</p>
<p>Thanks! </p>
| 1 | 2009-08-16T10:51:29Z | 4,445,534 | <p>To anyone stumbling on this, some internal gstreamer changes since this was originally posted may require gst.STATE_READY now instead of STATE_PAUSED. Tripped me up as it seems half the capture devices I encounter default to PAL and I need to use the GST_TUNER interface to change it.</p>
| 1 | 2010-12-15T00:02:34Z | [
"python",
"gstreamer"
] |
Piping output of subprocess.call to progress bar | 1,284,196 | <p>I'm using growisofs to burn an iso through my Python application. I have two classes in two different files; GUI() (main.py) and Boxblaze() (core.py). GUI() builds the window and handles all the events and stuff, and Boxblaze() has all the methods that GUI() calls. </p>
<p>Now when the user has selected the device to burn with, and the file to be burned, I need to call a method that calls the following command:`</p>
<pre><code>growisofs -use-the-force-luke=dao -use-the-force-luke=break:1913760 -dvd-compat -speed=2 -Z /burner/device=/full/path/to.iso
</code></pre>
<p>This command should give an output similar to this:</p>
<pre><code>Executing 'builtin_dd if=/home/nevon/games/Xbox 360 isos/The Godfather 2/alls-tgod2.iso of=/dev/scd0 obs=32k seek=0'
/dev/scd0: "Current Write Speed" is 2.5x1352KBps.
#more of the lines below, indicating progress.
7798128640/7835492352 (99.5%) @3.8x, remaining 0:06 RBU 100.0% UBU 99.8%
7815495680/7835492352 (99.7%) @3.8x, remaining 0:03 RBU 59.7% UBU 99.8%
7832862720/7835492352 (100.0%) @3.8x, remaining 0:00 RBU 7.9% UBU 99.8%
builtin_dd: 3825936*2KB out @ average 3.9x1352KBps
/dev/burner: flushing cache
/dev/burner: closing track
/dev/burner: closing disc
</code></pre>
<p>This command is run in a method called burn() in Boxblaze(). It looks simply like this:</p>
<pre><code>def burn(self, file, device):
subprocess.call(["growisofs", '-dry-run', "-use-the-force-luke=dao", "-use-the-force-luke=break:1913760", "-dvd-compat", "-speed=2", "-Z", device +'='+ file])
</code></pre>
<p><strong>Now my questions are the following:</strong></p>
<ol>
<li><p>How can I get the progress from the output (the percentage in brackets) and have my progress bar be set to "follow" that progress? My progress bar is called in the GUI() class, as such: </p>
<p>get = builder.get_object</p>
<p>self.progress_window = get("progressWindow")</p>
<p>self.progressbar = get("progressbar")</p></li>
<li><p>Do I have to run this command in a separate thread in order for the GUI to remain responsive (so that I can update the progress bar and allow the user to cancel the burn if they want to)? If so, how can I do that and still be able to pass the progress to the progress bar?</p></li>
</ol>
<p><hr /></p>
<p>The full code is available <a href="http://www.launchpad.net/boxblaze" rel="nofollow">on Launchpad</a> if you are interested. If you have bazaar installed, just run:</p>
<pre><code>bzr branch lp:boxblaze
</code></pre>
<p>Oh, and in case you were wondering, this application is only meant to work in Linux - so don't worry about cross-platform compatibility. </p>
| 2 | 2009-08-16T12:28:41Z | 1,284,215 | <p>To get the output you need to use the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>subprocess.Popen</code></a> call. (<code>stdout = subprocess.PIPE</code>)</p>
<p>(Second Question)</p>
<p>You probably need a separate thread, unless the GUI framework can select on a filedescriptor in the normal loop.</p>
<p>You can have a background thread read the pipe, process it (to extract the progress), the pass that to the GUI thread.</p>
<pre><code>## You might have to redirect stderr instead/as well
proc = sucprocess.Popen(command,stdout=subprocess.PIPE)
for line in proc.stdout.readlines():
## might not work - not sure about reading lines
## Parse the line to extract progress
## Pass progress to GUI thread
</code></pre>
<p>Edit:</p>
<p>I'm afraid I don't want to waste lots of CDs testing it out, so I haven't run it, but by you're comment it looks like it's not outputing the info to stdout, but to stderr.</p>
<p>I suggest running a sample command directly on the command-line, and redirecting stdout and stderr to different files.</p>
<pre><code>growisofs [options] >stdout 2>stderr
</code></pre>
<p>Then you can work out which things come out on stdout and which on stderr.</p>
<p>If the stuff you want come on stderr, change <code>stdout=subprocess.PIPE</code> to <code>stderr=subprocess.PIPE</code> and see if that works any better.</p>
<p>Edit2:</p>
<p>You're not using threads correctly - you should be starting it - not running it directly.</p>
<p>Also:</p>
<pre><code>gtk.gdk.threads_init()
threading.Thread.__init__(self)
</code></pre>
<p>is very weird - the initialiser calls should be in the initialiser - and I don't think you need to make it a gtk thread?</p>
<p>The way you call the run() method, is weird itself:</p>
<pre><code>core.Burning.run(self.burning, self.filechooser.get_filename(), self.listofdevices[self.combobox.get_active()])
</code></pre>
<p>Call instance methods through the object:</p>
<pre><code>self.burning.run(self.filechooser.get_filename(), self.listofdevices[self.combobox.get_active()])
</code></pre>
<p>(But you should have an <code>__init__()</code> method)</p>
<p>It seems to me that you are trying to run before you can walk. Try writing some simple threading code, then some simple code to run growisofs and parse the output, then some simple gtk+background threading code, and only then try combining them all together.
In fact first start writing some simple Object oriented code, so that you understand methods and object first.</p>
<p>e.g. All classes you create in python should be new-style classes, you should call super-class initialisers from your initialiser etc.</p>
| 1 | 2009-08-16T12:37:23Z | [
"python",
"multithreading",
"progress-bar",
"pygtk",
"subprocess"
] |
Piping output of subprocess.call to progress bar | 1,284,196 | <p>I'm using growisofs to burn an iso through my Python application. I have two classes in two different files; GUI() (main.py) and Boxblaze() (core.py). GUI() builds the window and handles all the events and stuff, and Boxblaze() has all the methods that GUI() calls. </p>
<p>Now when the user has selected the device to burn with, and the file to be burned, I need to call a method that calls the following command:`</p>
<pre><code>growisofs -use-the-force-luke=dao -use-the-force-luke=break:1913760 -dvd-compat -speed=2 -Z /burner/device=/full/path/to.iso
</code></pre>
<p>This command should give an output similar to this:</p>
<pre><code>Executing 'builtin_dd if=/home/nevon/games/Xbox 360 isos/The Godfather 2/alls-tgod2.iso of=/dev/scd0 obs=32k seek=0'
/dev/scd0: "Current Write Speed" is 2.5x1352KBps.
#more of the lines below, indicating progress.
7798128640/7835492352 (99.5%) @3.8x, remaining 0:06 RBU 100.0% UBU 99.8%
7815495680/7835492352 (99.7%) @3.8x, remaining 0:03 RBU 59.7% UBU 99.8%
7832862720/7835492352 (100.0%) @3.8x, remaining 0:00 RBU 7.9% UBU 99.8%
builtin_dd: 3825936*2KB out @ average 3.9x1352KBps
/dev/burner: flushing cache
/dev/burner: closing track
/dev/burner: closing disc
</code></pre>
<p>This command is run in a method called burn() in Boxblaze(). It looks simply like this:</p>
<pre><code>def burn(self, file, device):
subprocess.call(["growisofs", '-dry-run', "-use-the-force-luke=dao", "-use-the-force-luke=break:1913760", "-dvd-compat", "-speed=2", "-Z", device +'='+ file])
</code></pre>
<p><strong>Now my questions are the following:</strong></p>
<ol>
<li><p>How can I get the progress from the output (the percentage in brackets) and have my progress bar be set to "follow" that progress? My progress bar is called in the GUI() class, as such: </p>
<p>get = builder.get_object</p>
<p>self.progress_window = get("progressWindow")</p>
<p>self.progressbar = get("progressbar")</p></li>
<li><p>Do I have to run this command in a separate thread in order for the GUI to remain responsive (so that I can update the progress bar and allow the user to cancel the burn if they want to)? If so, how can I do that and still be able to pass the progress to the progress bar?</p></li>
</ol>
<p><hr /></p>
<p>The full code is available <a href="http://www.launchpad.net/boxblaze" rel="nofollow">on Launchpad</a> if you are interested. If you have bazaar installed, just run:</p>
<pre><code>bzr branch lp:boxblaze
</code></pre>
<p>Oh, and in case you were wondering, this application is only meant to work in Linux - so don't worry about cross-platform compatibility. </p>
| 2 | 2009-08-16T12:28:41Z | 1,284,218 | <p>Can you pass a timeout to reading from subprocess? I guess you can because <a href="http://www.pixelbeat.org/libs/subProcess.py" rel="nofollow">my subProcess module</a> was used as design input for it. You can use that to growiso.read(.1) and then parse and display the percentage from the outdata (or maybe errdata).</p>
| 0 | 2009-08-16T12:38:47Z | [
"python",
"multithreading",
"progress-bar",
"pygtk",
"subprocess"
] |
Piping output of subprocess.call to progress bar | 1,284,196 | <p>I'm using growisofs to burn an iso through my Python application. I have two classes in two different files; GUI() (main.py) and Boxblaze() (core.py). GUI() builds the window and handles all the events and stuff, and Boxblaze() has all the methods that GUI() calls. </p>
<p>Now when the user has selected the device to burn with, and the file to be burned, I need to call a method that calls the following command:`</p>
<pre><code>growisofs -use-the-force-luke=dao -use-the-force-luke=break:1913760 -dvd-compat -speed=2 -Z /burner/device=/full/path/to.iso
</code></pre>
<p>This command should give an output similar to this:</p>
<pre><code>Executing 'builtin_dd if=/home/nevon/games/Xbox 360 isos/The Godfather 2/alls-tgod2.iso of=/dev/scd0 obs=32k seek=0'
/dev/scd0: "Current Write Speed" is 2.5x1352KBps.
#more of the lines below, indicating progress.
7798128640/7835492352 (99.5%) @3.8x, remaining 0:06 RBU 100.0% UBU 99.8%
7815495680/7835492352 (99.7%) @3.8x, remaining 0:03 RBU 59.7% UBU 99.8%
7832862720/7835492352 (100.0%) @3.8x, remaining 0:00 RBU 7.9% UBU 99.8%
builtin_dd: 3825936*2KB out @ average 3.9x1352KBps
/dev/burner: flushing cache
/dev/burner: closing track
/dev/burner: closing disc
</code></pre>
<p>This command is run in a method called burn() in Boxblaze(). It looks simply like this:</p>
<pre><code>def burn(self, file, device):
subprocess.call(["growisofs", '-dry-run', "-use-the-force-luke=dao", "-use-the-force-luke=break:1913760", "-dvd-compat", "-speed=2", "-Z", device +'='+ file])
</code></pre>
<p><strong>Now my questions are the following:</strong></p>
<ol>
<li><p>How can I get the progress from the output (the percentage in brackets) and have my progress bar be set to "follow" that progress? My progress bar is called in the GUI() class, as such: </p>
<p>get = builder.get_object</p>
<p>self.progress_window = get("progressWindow")</p>
<p>self.progressbar = get("progressbar")</p></li>
<li><p>Do I have to run this command in a separate thread in order for the GUI to remain responsive (so that I can update the progress bar and allow the user to cancel the burn if they want to)? If so, how can I do that and still be able to pass the progress to the progress bar?</p></li>
</ol>
<p><hr /></p>
<p>The full code is available <a href="http://www.launchpad.net/boxblaze" rel="nofollow">on Launchpad</a> if you are interested. If you have bazaar installed, just run:</p>
<pre><code>bzr branch lp:boxblaze
</code></pre>
<p>Oh, and in case you were wondering, this application is only meant to work in Linux - so don't worry about cross-platform compatibility. </p>
| 2 | 2009-08-16T12:28:41Z | 1,320,519 | <p>You need to run the command from a separate thread, and update the gui with gobject.idle_add calls. Right now you have a class "Burning" but you are using it wrong, it should be used like this:</p>
<pre><code>self.burning = core.Burning(self.filechooser.get_filename(), self.listofdevices[self.combobox.get_active()], self.progressbar)
self.burning.start()
</code></pre>
<p>Obviously you will have to modify core.Burning.
Then you will have access to the progressbar so you could make a function like this: </p>
<pre><code>def set_progress_bar_fraction(self, fraction):
self.progress_bar.set_fraction(fraction)
</code></pre>
<p>Then every percentage update call it like this: <code>gobject.idle_add(self.set_progress_bar_fraction, fraction)</code></p>
<p>More info on pygtk with threads <a href="http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html" rel="nofollow">here</a>.</p>
| 0 | 2009-08-24T04:44:34Z | [
"python",
"multithreading",
"progress-bar",
"pygtk",
"subprocess"
] |
Piping output of subprocess.call to progress bar | 1,284,196 | <p>I'm using growisofs to burn an iso through my Python application. I have two classes in two different files; GUI() (main.py) and Boxblaze() (core.py). GUI() builds the window and handles all the events and stuff, and Boxblaze() has all the methods that GUI() calls. </p>
<p>Now when the user has selected the device to burn with, and the file to be burned, I need to call a method that calls the following command:`</p>
<pre><code>growisofs -use-the-force-luke=dao -use-the-force-luke=break:1913760 -dvd-compat -speed=2 -Z /burner/device=/full/path/to.iso
</code></pre>
<p>This command should give an output similar to this:</p>
<pre><code>Executing 'builtin_dd if=/home/nevon/games/Xbox 360 isos/The Godfather 2/alls-tgod2.iso of=/dev/scd0 obs=32k seek=0'
/dev/scd0: "Current Write Speed" is 2.5x1352KBps.
#more of the lines below, indicating progress.
7798128640/7835492352 (99.5%) @3.8x, remaining 0:06 RBU 100.0% UBU 99.8%
7815495680/7835492352 (99.7%) @3.8x, remaining 0:03 RBU 59.7% UBU 99.8%
7832862720/7835492352 (100.0%) @3.8x, remaining 0:00 RBU 7.9% UBU 99.8%
builtin_dd: 3825936*2KB out @ average 3.9x1352KBps
/dev/burner: flushing cache
/dev/burner: closing track
/dev/burner: closing disc
</code></pre>
<p>This command is run in a method called burn() in Boxblaze(). It looks simply like this:</p>
<pre><code>def burn(self, file, device):
subprocess.call(["growisofs", '-dry-run', "-use-the-force-luke=dao", "-use-the-force-luke=break:1913760", "-dvd-compat", "-speed=2", "-Z", device +'='+ file])
</code></pre>
<p><strong>Now my questions are the following:</strong></p>
<ol>
<li><p>How can I get the progress from the output (the percentage in brackets) and have my progress bar be set to "follow" that progress? My progress bar is called in the GUI() class, as such: </p>
<p>get = builder.get_object</p>
<p>self.progress_window = get("progressWindow")</p>
<p>self.progressbar = get("progressbar")</p></li>
<li><p>Do I have to run this command in a separate thread in order for the GUI to remain responsive (so that I can update the progress bar and allow the user to cancel the burn if they want to)? If so, how can I do that and still be able to pass the progress to the progress bar?</p></li>
</ol>
<p><hr /></p>
<p>The full code is available <a href="http://www.launchpad.net/boxblaze" rel="nofollow">on Launchpad</a> if you are interested. If you have bazaar installed, just run:</p>
<pre><code>bzr branch lp:boxblaze
</code></pre>
<p>Oh, and in case you were wondering, this application is only meant to work in Linux - so don't worry about cross-platform compatibility. </p>
| 2 | 2009-08-16T12:28:41Z | 1,485,018 | <p>You can use <code>glib.io_add_watch()</code> to watch for output on the pipes connected to stdout and stderr in the subprocess object.</p>
<pre><code>proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_id = glib.io_add_watch(proc.stdout, glib.IO_IN|glib.IO_HUP, stdout_cb)
stderr_id = glib.io_add_watch(proc.stderr, glib.IO_IN|glib.IO_HUP, stderr_cb)
</code></pre>
<p>Then when the callback is called it should check for the condition and reads all the data from the pipe and processes it to get the info to update the ProgressBar. If the app buffers io then you may have to use a pty to fool it into thinking it's connected to a terminal so it will output a line at a time.</p>
| 2 | 2009-09-28T01:28:08Z | [
"python",
"multithreading",
"progress-bar",
"pygtk",
"subprocess"
] |
Debugging multi-threaded Python with Wing IDE | 1,284,382 | <p>I'm debugging a multi-threaded Python program with Wing IDE.</p>
<p>When I press the pause button, it pauses only one thread. I've tried it ten times and it always pauses the same thread, in my case called "ThreadTimer Thread", while the other threads keep on running. I want to pause these other threads so I could step with them. How do I do that?</p>
| 1 | 2009-08-16T14:06:40Z | 1,284,394 | <p>I don't know if multi-thread debugging is possible with Wing IDE. </p>
<p>However you maybe interested in <a href="http://winpdb.org/about/" rel="nofollow">Winpdb</a> which has this capability</p>
| 1 | 2009-08-16T14:16:28Z | [
"python",
"multithreading",
"debugging",
"ide"
] |
Debugging multi-threaded Python with Wing IDE | 1,284,382 | <p>I'm debugging a multi-threaded Python program with Wing IDE.</p>
<p>When I press the pause button, it pauses only one thread. I've tried it ten times and it always pauses the same thread, in my case called "ThreadTimer Thread", while the other threads keep on running. I want to pause these other threads so I could step with them. How do I do that?</p>
| 1 | 2009-08-16T14:06:40Z | 1,284,892 | <p>Per <a href="http://www.wingware.com/doc/debug/threading" rel="nofollow">the docs</a>, all threads that are running Python code are stopped (by default, i.e., unless you're going out of the way to achieve a different effect). Are the threads that you see as not getting stopped running non-Python code (I/O, say: that gives its own issues), or are you doing something else than running in a pristine install without the tweaks the docs describe to only pause some of the threads...?</p>
| 1 | 2009-08-16T17:53:40Z | [
"python",
"multithreading",
"debugging",
"ide"
] |
Python - Use a Regex to Filter Data | 1,284,789 | <p>Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use <code>gsub</code>:</p>
<pre><code>>> key = "cd baz ; ls -l"
=> "cd baz ; ls -l"
>> newkey = key.gsub(/[^\w\d]/, "")
=> "cdbazlsl"
</code></pre>
<p>What would the equivalent function be in Python?</p>
| 4 | 2009-08-16T17:08:16Z | 1,284,802 | <pre><code>import re
re.sub(pattern, '', s)
</code></pre>
<p><a href="http://docs.python.org/library/re.html#re.sub">Docs</a></p>
| 13 | 2009-08-16T17:13:31Z | [
"python",
"regex"
] |
Python - Use a Regex to Filter Data | 1,284,789 | <p>Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use <code>gsub</code>:</p>
<pre><code>>> key = "cd baz ; ls -l"
=> "cd baz ; ls -l"
>> newkey = key.gsub(/[^\w\d]/, "")
=> "cdbazlsl"
</code></pre>
<p>What would the equivalent function be in Python?</p>
| 4 | 2009-08-16T17:08:16Z | 1,284,803 | <p><a href="http://docs.python.org/3.1/library/re.html#re.subn" rel="nofollow">re.subn()</a> is your friend:</p>
<pre><code>>>> import re
>>> key = "cd baz ; ls -l"
>>> re.subn(r'\W', "", key)
('cdbazlsl', 6)
>>> re.subn(r'\W', "", key)[0]
'cdbazlsl'
</code></pre>
<p>Returns a tuple. Take the first element if you only want the resulting string. Or just call re.sub(), as SilentGhost notes. (Which is to say, his answer is more exact.)</p>
| 2 | 2009-08-16T17:14:41Z | [
"python",
"regex"
] |
Python - Use a Regex to Filter Data | 1,284,789 | <p>Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use <code>gsub</code>:</p>
<pre><code>>> key = "cd baz ; ls -l"
=> "cd baz ; ls -l"
>> newkey = key.gsub(/[^\w\d]/, "")
=> "cdbazlsl"
</code></pre>
<p>What would the equivalent function be in Python?</p>
| 4 | 2009-08-16T17:08:16Z | 1,284,807 | <pre><code>import re
old = "cd baz ; ls -l"
regex = r"[^\w\d]" # which is the same as \W btw
pat = re.compile( regex )
new = pat.sub('', old )
</code></pre>
| 2 | 2009-08-16T17:15:54Z | [
"python",
"regex"
] |
Python - Use a Regex to Filter Data | 1,284,789 | <p>Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use <code>gsub</code>:</p>
<pre><code>>> key = "cd baz ; ls -l"
=> "cd baz ; ls -l"
>> newkey = key.gsub(/[^\w\d]/, "")
=> "cdbazlsl"
</code></pre>
<p>What would the equivalent function be in Python?</p>
| 4 | 2009-08-16T17:08:16Z | 1,284,826 | <p>The answers so far have focused on doing the same thing as your Ruby code, which is exactly the reverse of what you're asking in the English part of your question: the code removes character that DO match, while your text asks for</p>
<blockquote>
<p>a simple way to remove all characters
from a given string that fail to match</p>
</blockquote>
<p>For example, suppose your RE's pattern was <code>r'\d{2,}'</code>, "two or more digits" -- so the non-matching parts would be all non-digits plus all single, isolated digits. Removing the NON-matching parts, as your text requires, is also easy:</p>
<pre><code>>>> import re
>>> there = re.compile(r'\d{2,}')
>>> ''.join(there.findall('123foo7bah45xx9za678'))
'12345678'
</code></pre>
<p><strong>Edit</strong>: OK, OP's clarified the question now (he did indeed mean what his code, not his text, said, and now the text is right too;-) but I'm leaving the answer in for completeness (the other answers suggesting <code>re.sub</code> are correct for the question as it now stands).
I realize you probably mean what you "say" in your Ruby code, and not what you say in your English text, but, just in case, I thought I'd better complete the set of answers!-)</p>
| 4 | 2009-08-16T17:23:59Z | [
"python",
"regex"
] |
Python - Use a Regex to Filter Data | 1,284,789 | <p>Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use <code>gsub</code>:</p>
<pre><code>>> key = "cd baz ; ls -l"
=> "cd baz ; ls -l"
>> newkey = key.gsub(/[^\w\d]/, "")
=> "cdbazlsl"
</code></pre>
<p>What would the equivalent function be in Python?</p>
| 4 | 2009-08-16T17:08:16Z | 39,707,425 | <p>May be the shortest way:</p>
<pre><code>In [32]: pattern='[-0-9.]'
....: price_str="Â¥-607.6B"
....: ''.join(re.findall(pattern,price_str))
Out[32]: '-607.6'
</code></pre>
| 0 | 2016-09-26T16:02:48Z | [
"python",
"regex"
] |
django auto entry generation | 1,284,814 | <p>I am trying to make an automated database entry generation with Django, whenever I trigger it to happen.</p>
<p>For instance, assume I have a such model:</p>
<pre><code>class status_entry(models.Model):
name = models.TextField()
date = models.DateField()
status = models.BooleanField()
</code></pre>
<p>and I have several entries to the model such as:</p>
<pre><code>1 - "bla bla" - 2009/11/6 - true
2 - "bla bla" - 2009/11/7 - true
3 - "bla bla" - 2009/11/10 - true
</code></pre>
<p>so as you can see between my 2nd and 3rd entry, I have 2 absent entry days (2009/11/8 and 2009/11/9), via creating some view or script I want to
auto fill these absent day entries such as :</p>
<pre><code>id name date status
------------------------------------
1 - "bla bla" - 2009/11/6 - true
2 - "bla bla" - 2009/11/7 - true
3 - "bla bla" - 2009/11/8 - false
4 - "bla bla" - 2009/11/9 - false
5 - "bla bla" - 2009/11/10 - true
</code></pre>
<p>Thanks </p>
| 0 | 2009-08-16T17:19:06Z | 1,284,971 | <p>You can overwrite <code>save</code> and do the autofill there (<code>daterange</code> function taken from <a href="http://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python">here</a>):</p>
<pre><code>from datetime import timedelta
def daterange(start_date, end_date):
for n in range((end_date - start_date).days):
yield start_date + timedelta(n)
class StatusEntry(models.Model):
name = models.TextField()
date = models.DateField()
status = models.BooleanField()
def __unicode__(self):
return "%s - %s - %s" % (self.name, unicode(self.status), unicode(self.date))
def save(self, fill=True):
if fill and not self.id: # autofill on insert, not on update
newest = StatusEntry.objects.all().order_by("-date")[:1]
if newest and newest[0].date < self.date:
for date in daterange(newest[0].date + timedelta(1), self.date):
entry = StatusEntry(name=self.name, date=date, status=False)
entry.save(fill=False)
super(StatusEntry, self).save()
</code></pre>
<p>You could also use <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">signals</a> or do it with triggers, like hughdbrown suggested</p>
| 0 | 2009-08-16T18:22:01Z | [
"python",
"django",
"django-models",
"scripting"
] |
AJAX upload in Python (WSGI) without Flash/Silverlight, with progress bar | 1,284,922 | <p>I am looking for a pure Javascript/Python upload example, that uses server polling instead of client-side SWF to display upload progress (like the one on rapidshare.com for example)</p>
<p>Currently, website is running on the standalone wsgi server included with Werkzeug framework, but may be moved to mod_wsgi if the load increases.</p>
<p>I've tried the gp.fileupload middleware, but can't get it to work. Examples on their website wont work either :|</p>
<p>Website already uses <a href="http://www.bbc.co.uk/glow/" rel="nofollow">Glow</a> library for other misc client-side stuff, but there is no specific upload-related functionality in it.</p>
| 1 | 2009-08-16T18:03:48Z | 1,844,737 | <p>If you don't have support on the web side to track the size of the temporary file (or in-memory buffer) of the uploading data as it arrives, I don't know how you'll do this. Some of the popular web servers have special support for this, mostly experimental, but it's not widely supported and what you're trying to do is pretty awkward in general. I've researched this recently and it's pretty poorly supported all around.</p>
| 0 | 2009-12-04T03:55:09Z | [
"python",
"ajax",
"upload",
"progress",
"werkzeug"
] |
How can I check to see if a Python script was started interactively? | 1,285,024 | <p>I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness?</p>
<p>EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.</p>
| 2 | 2009-08-16T18:48:54Z | 1,285,045 | <p>If you want to know if you're reading from a terminal (not clear if that is enough of a distinction, please clarify) you can use</p>
<pre><code>sys.stdin.isatty()
</code></pre>
| 7 | 2009-08-16T18:53:11Z | [
"python",
"interactive"
] |
How can I check to see if a Python script was started interactively? | 1,285,024 | <p>I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness?</p>
<p>EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.</p>
| 2 | 2009-08-16T18:48:54Z | 1,285,056 | <p>You should simply add a command-line switch in the scheduled task, and check for it in your script, modifying the behavior as appropriate. Explicit is better than implicit.</p>
<p>One benefit to this design: you'll be able to test both behaviors, regardless of how you actually invoked the script.</p>
| 11 | 2009-08-16T18:55:54Z | [
"python",
"interactive"
] |
How can I check to see if a Python script was started interactively? | 1,285,024 | <p>I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness?</p>
<p>EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.</p>
| 2 | 2009-08-16T18:48:54Z | 1,286,066 | <p>I'd just add a command line switch when you're calling it with cron:</p>
<p>python yourscript.py -scheduled</p>
<p>then in your program</p>
<pre><code>import sys
if "-scheduled" in sys.argv:
#--non-interactive code--
else:
#--interactive code--
</code></pre>
| 0 | 2009-08-17T03:41:55Z | [
"python",
"interactive"
] |
How to avoid html-escaping in evoque | 1,285,134 | <p>I try to make my evoque templates color-code a bit,
but the html I get is already escaped with lt-gt's</p>
<p>I read there should be something like a quoted-no-more class
but I haven't been able to find the evoque.quoted package</p>
<p>My aim is to not have escaped html coming out of the template, but 'real'.</p>
<pre><code>from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from evoque.domain import Domain
import os
tmpl="""
$begin{code}
${codyfy(evoque(name=label), lang=label.split()[0][1:])}
$end{code}
$begin{c 0}
int main(void){printf("hello world");return 0;}
$end{c 0}
$begin{python 0}
print "hello world"
$end{python 0}
$evoque{#code, label="#c 0"}
$evoque{#code, label="#python 0"}
"""
td = Domain(os.path.abspath("."))
def codyfy(src,lang="python"):
return highlight(src,get_lexer_by_name(lang, stripall=True),HtmlFormatter())
td.set_on_globals('codyfy',codyfy)
td.set_template("testtmpl", src=tmpl, from_string=True)
t = td.get_template("testtmpl")
print t.evoque()
</code></pre>
| 1 | 2009-08-16T19:28:35Z | 1,285,174 | <p>Have you tried it with <code>raw=True</code>? See:</p>
<ul>
<li><a href="http://evoque.gizmojo.org/howto/source/" rel="nofollow">http://evoque.gizmojo.org/howto/source/</a></li>
</ul>
<p>I haven't used Qpy before, but perhaps this note will help:</p>
<blockquote>
<p><a href="http://evoque.gizmojo.org/howto/quoted-no-more/" rel="nofollow">Defining custom quoted-no-more classes</a></p>
<p>[...] It is also highly recommended to download and install the Qpy unicode templating utility that provides the qpy.xml Quoted-No-More class for automatic input escaping. [...]</p>
</blockquote>
| 1 | 2009-08-16T19:41:39Z | [
"python"
] |
How to avoid html-escaping in evoque | 1,285,134 | <p>I try to make my evoque templates color-code a bit,
but the html I get is already escaped with lt-gt's</p>
<p>I read there should be something like a quoted-no-more class
but I haven't been able to find the evoque.quoted package</p>
<p>My aim is to not have escaped html coming out of the template, but 'real'.</p>
<pre><code>from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from evoque.domain import Domain
import os
tmpl="""
$begin{code}
${codyfy(evoque(name=label), lang=label.split()[0][1:])}
$end{code}
$begin{c 0}
int main(void){printf("hello world");return 0;}
$end{c 0}
$begin{python 0}
print "hello world"
$end{python 0}
$evoque{#code, label="#c 0"}
$evoque{#code, label="#python 0"}
"""
td = Domain(os.path.abspath("."))
def codyfy(src,lang="python"):
return highlight(src,get_lexer_by_name(lang, stripall=True),HtmlFormatter())
td.set_on_globals('codyfy',codyfy)
td.set_template("testtmpl", src=tmpl, from_string=True)
t = td.get_template("testtmpl")
print t.evoque()
</code></pre>
| 1 | 2009-08-16T19:28:35Z | 1,285,281 | <p>Yeps - we got in parallel, ars and I.
The answer is here - snip it into above:</p>
<pre><code>from qpy import xml
def codyfy(src,lang="python"):
return xml(highlight(src,get_lexer_by_name(lang, stripall=True),HtmlFormatter()))
</code></pre>
<p>xml() is apparently sort of a payload making subsequent escapers lay off.</p>
| 1 | 2009-08-16T20:32:12Z | [
"python"
] |
How to avoid html-escaping in evoque | 1,285,134 | <p>I try to make my evoque templates color-code a bit,
but the html I get is already escaped with lt-gt's</p>
<p>I read there should be something like a quoted-no-more class
but I haven't been able to find the evoque.quoted package</p>
<p>My aim is to not have escaped html coming out of the template, but 'real'.</p>
<pre><code>from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from evoque.domain import Domain
import os
tmpl="""
$begin{code}
${codyfy(evoque(name=label), lang=label.split()[0][1:])}
$end{code}
$begin{c 0}
int main(void){printf("hello world");return 0;}
$end{c 0}
$begin{python 0}
print "hello world"
$end{python 0}
$evoque{#code, label="#c 0"}
$evoque{#code, label="#python 0"}
"""
td = Domain(os.path.abspath("."))
def codyfy(src,lang="python"):
return highlight(src,get_lexer_by_name(lang, stripall=True),HtmlFormatter())
td.set_on_globals('codyfy',codyfy)
td.set_template("testtmpl", src=tmpl, from_string=True)
t = td.get_template("testtmpl")
print t.evoque()
</code></pre>
| 1 | 2009-08-16T19:28:35Z | 1,386,097 | <p>qpy.xml() is the quoted-no-more class for XML (and HTML) provided by the Qpy package -- in both superfast C and alternative python versions. Evoque looks for this specific class when quoting="xml" (i.e. equivalent to: quoting=qpy.xml) is used on template loading or rendering. </p>
<p>But any custom quoted-no-more type may be specified as value to the quoting parameter. The evoque.quoted package provides a base quoted-no-more type, and some concrete examples, to make the definition of your custom quoted-no-more types easier. However, as noted, the evoque.quoted is not yet available -- it is mentioned in the changelog but for an as yet unreleased version of Evoque (see the changelog page).</p>
<p>If you pass the output of a whole bunch of templates thru codyfy(), you might also wish to consider specifying it as a filter, either on each template, or as default filter on a collection. An example of using filters is:
<a href="http://evoque.gizmojo.org/howto/markdown/" rel="nofollow">http://evoque.gizmojo.org/howto/markdown/</a></p>
<p>Using filters would in fact be a better approach as it is more general -- you will:<br />
a) not have to hard-wire the qpy.xml() call within codyfy(), and<br />
b) be able to use the exact same codyfy() function as filter in <em>all templates</em>, even when these specify a quoting other than qpy.xml. </p>
| 0 | 2009-09-06T16:45:12Z | [
"python"
] |
Implement Comet / Server push in Google App Engine in Python | 1,285,150 | <p>How can I implement Comet / Server push in Google App Engine in Python?</p>
| 25 | 2009-08-16T19:34:16Z | 1,285,251 | <p>At this time, I would rule out doing Comet in App Engine (any language). Comet is based on long-lived HTTP connections, and App Engine will time out any single connection in about 30 seconds or so at most; it's hard to conceive of a worse match!</p>
| 3 | 2009-08-16T20:14:58Z | [
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api"
] |
Implement Comet / Server push in Google App Engine in Python | 1,285,150 | <p>How can I implement Comet / Server push in Google App Engine in Python?</p>
| 25 | 2009-08-16T19:34:16Z | 1,285,914 | <p>Comet (or something like it - XMPP API) is on the google app engine roadmap. For now, stay away.</p>
<p><a href="http://code.google.com/appengine/docs/roadmap.html" rel="nofollow">http://code.google.com/appengine/docs/roadmap.html</a></p>
| 2 | 2009-08-17T02:14:21Z | [
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api"
] |
Implement Comet / Server push in Google App Engine in Python | 1,285,150 | <p>How can I implement Comet / Server push in Google App Engine in Python?</p>
| 25 | 2009-08-16T19:34:16Z | 2,784,805 | <p>30 seconds is more than enough; either way you should return a no-op message when a time passed and no new events occur.</p>
<p>This prevents client timeouts and is done by everybody who does comet.</p>
<p>Just send the request, and on the server make it wait until an event or timeout after 25 seconds.</p>
| 1 | 2010-05-06T21:56:36Z | [
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api"
] |
Implement Comet / Server push in Google App Engine in Python | 1,285,150 | <p>How can I implement Comet / Server push in Google App Engine in Python?</p>
| 25 | 2009-08-16T19:34:16Z | 2,870,191 | <p>We just announced the Channel API to do comet push with App Engine apps: <a href="http://googleappengine.blogspot.com/2010/05/app-engine-at-google-io-2010.html">http://googleappengine.blogspot.com/2010/05/app-engine-at-google-io-2010.html</a></p>
<p>If you're at Google IO, I'll be talking about this at 1pm tomorrow (on the APIs track): <a href="http://code.google.com/events/io/2010/sessions/building-real-time-apps-app-engine-feed-api.html">http://code.google.com/events/io/2010/sessions/building-real-time-apps-app-engine-feed-api.html</a></p>
<p>Here's the YouTube video of the session: <a href="http://www.youtube.com/watch?v=oMXe-xK0BWA">http://www.youtube.com/watch?v=oMXe-xK0BWA</a></p>
<p>Hopefully last update! This is now released: <a href="http://code.google.com/appengine/docs/python/channel">code.google.com/appengine/docs/python/channel</a></p>
| 69 | 2010-05-19T23:43:54Z | [
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api"
] |
Implement Comet / Server push in Google App Engine in Python | 1,285,150 | <p>How can I implement Comet / Server push in Google App Engine in Python?</p>
| 25 | 2009-08-16T19:34:16Z | 3,918,651 | <p>Looking inside the App Engine 1.3.8-pre release, I see the Channel API service stub and more code. So it looks like we can start trying it out locally.</p>
| 0 | 2010-10-12T20:19:03Z | [
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api"
] |
Implement Comet / Server push in Google App Engine in Python | 1,285,150 | <p>How can I implement Comet / Server push in Google App Engine in Python?</p>
| 25 | 2009-08-16T19:34:16Z | 4,480,891 | <p>Google App Engine supports server push using the Channel API since 2nd December.</p>
| 0 | 2010-12-19T00:03:00Z | [
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api"
] |
How does one make logging color in Django/Google App Engine? | 1,285,372 | <p>If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?</p>
<p>I've copied the helpful solution from <a href="http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored">this question</a>, but I'm not sure how to integrate it into Django/Google App Engine.</p>
<p>I figured one would put the following in the application's main.py (i.e. essentially from the example here: <a href="http://code.google.com/appengine/articles/django.html">Running Django on Google App Engine</a>):</p>
<pre><code>from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)
</code></pre>
<p>... where contrib.utils is where I put airmind's code from the above link to his SO answer.</p>
<p>However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.</p>
<p>Suggestions and input would be much appreciated.</p>
<p>Cheers,
Brian</p>
| 11 | 2009-08-16T21:20:08Z | 1,287,640 | <p>The reset codes mentioned in the answer you linked to will work on a console in the local development server (but will likely take some tweaking - you'll have to chain it with the existing App Engine logging handler), but won't work in production, since in production log entries are output to an HTML page in your admin console.</p>
<p>You can, however, filter by log level in the admin console.</p>
| 2 | 2009-08-17T12:19:02Z | [
"python",
"django",
"google-app-engine",
"logging",
"colors"
] |
How does one make logging color in Django/Google App Engine? | 1,285,372 | <p>If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?</p>
<p>I've copied the helpful solution from <a href="http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored">this question</a>, but I'm not sure how to integrate it into Django/Google App Engine.</p>
<p>I figured one would put the following in the application's main.py (i.e. essentially from the example here: <a href="http://code.google.com/appengine/articles/django.html">Running Django on Google App Engine</a>):</p>
<pre><code>from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)
</code></pre>
<p>... where contrib.utils is where I put airmind's code from the above link to his SO answer.</p>
<p>However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.</p>
<p>Suggestions and input would be much appreciated.</p>
<p>Cheers,
Brian</p>
| 11 | 2009-08-16T21:20:08Z | 1,287,645 | <p>I don't believe that you should create a logger subclass just for this - airmind's answer is fine as far as creating a specialised <code>Formatter</code> and specifying its use on a <code>StreamHandler</code>. But there's no need for a logger subclass. In fact airmind's use of a logger class adds a handler to every logger created, which is not what you want.</p>
<p>The solution airmind gave only works for terminals which support ANSI escape sequences - are you sure that your console does support them?</p>
| 2 | 2009-08-17T12:19:42Z | [
"python",
"django",
"google-app-engine",
"logging",
"colors"
] |
How does one make logging color in Django/Google App Engine? | 1,285,372 | <p>If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?</p>
<p>I've copied the helpful solution from <a href="http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored">this question</a>, but I'm not sure how to integrate it into Django/Google App Engine.</p>
<p>I figured one would put the following in the application's main.py (i.e. essentially from the example here: <a href="http://code.google.com/appengine/articles/django.html">Running Django on Google App Engine</a>):</p>
<pre><code>from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)
</code></pre>
<p>... where contrib.utils is where I put airmind's code from the above link to his SO answer.</p>
<p>However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.</p>
<p>Suggestions and input would be much appreciated.</p>
<p>Cheers,
Brian</p>
| 11 | 2009-08-16T21:20:08Z | 2,998,155 | <p>Here is a sample formater:</p>
<pre><code>class Formatter(logging.Formatter) :
_level_colors = {
"DEBUG": "\033[22;32m", "INFO": "\033[01;34m",
"WARNING": "\033[22;35m", "ERROR": "\033[22;31m",
"CRITICAL": "\033[01;31m"
};
def format(self, record):
if(Formatter._level_colors.has_key(record.levelname)):
record.levelname = "%s%s\033[0;0m" % \
(Formatter._level_colors[record.levelname],
record.levelname)
record.name = "\033[37m\033[1m%s\033[0;0m" % record.name
return logging.Formatter.format(self, record)
</code></pre>
<p>You need to configure it, for example:</p>
<pre><code>...
[formatters]
keys=console_formatter
...
[handler_console_handler]
class=StreamHandler
formatter=console_formatter
args=(sys.stdout,)
</code></pre>
| 2 | 2010-06-08T14:21:53Z | [
"python",
"django",
"google-app-engine",
"logging",
"colors"
] |
How does one make logging color in Django/Google App Engine? | 1,285,372 | <p>If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?</p>
<p>I've copied the helpful solution from <a href="http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored">this question</a>, but I'm not sure how to integrate it into Django/Google App Engine.</p>
<p>I figured one would put the following in the application's main.py (i.e. essentially from the example here: <a href="http://code.google.com/appengine/articles/django.html">Running Django on Google App Engine</a>):</p>
<pre><code>from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)
</code></pre>
<p>... where contrib.utils is where I put airmind's code from the above link to his SO answer.</p>
<p>However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.</p>
<p>Suggestions and input would be much appreciated.</p>
<p>Cheers,
Brian</p>
| 11 | 2009-08-16T21:20:08Z | 3,080,300 | <p>I also wanted color output for the dev_appserver. I found the solutions here a little OTT (all I wanted was to make my logging.error() calls stand out. I ended up monkeypatching the logging module by dropping this in my main.py as a quick solution:</p>
<pre><code># monkey patch logger to dump ERRORs in red
import os
if os.environ['SERVER_SOFTWARE'].find('Development') >= 0:
import logging
old_error = logging.error
def red_error(msg,*args,**kwargs):
old_error("\033[22;31m%s\033[0;0m" % msg, *args, **kwargs)
logging.error = red_error
</code></pre>
<p>This will only for on ANSI-color terminals.</p>
| 2 | 2010-06-20T17:53:19Z | [
"python",
"django",
"google-app-engine",
"logging",
"colors"
] |
How does one make logging color in Django/Google App Engine? | 1,285,372 | <p>If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?</p>
<p>I've copied the helpful solution from <a href="http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored">this question</a>, but I'm not sure how to integrate it into Django/Google App Engine.</p>
<p>I figured one would put the following in the application's main.py (i.e. essentially from the example here: <a href="http://code.google.com/appengine/articles/django.html">Running Django on Google App Engine</a>):</p>
<pre><code>from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)
</code></pre>
<p>... where contrib.utils is where I put airmind's code from the above link to his SO answer.</p>
<p>However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.</p>
<p>Suggestions and input would be much appreciated.</p>
<p>Cheers,
Brian</p>
| 11 | 2009-08-16T21:20:08Z | 16,349,987 | <p>We use <a href="https://pypi.python.org/pypi/colorlog">colorlog</a> and it does exactly what you expect.</p>
<p>For posterity, the formatter config we use is:</p>
<pre><code>'color': {
'()': 'colorlog.ColoredFormatter',
'format': '%(log_color)s%(levelname)-8s %(message)s',
'log_colors': {
'DEBUG': 'bold_black',
'INFO': 'white',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
},
}
</code></pre>
| 13 | 2013-05-03T00:53:38Z | [
"python",
"django",
"google-app-engine",
"logging",
"colors"
] |
How does one make logging color in Django/Google App Engine? | 1,285,372 | <p>If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up?</p>
<p>I've copied the helpful solution from <a href="http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored">this question</a>, but I'm not sure how to integrate it into Django/Google App Engine.</p>
<p>I figured one would put the following in the application's main.py (i.e. essentially from the example here: <a href="http://code.google.com/appengine/articles/django.html">Running Django on Google App Engine</a>):</p>
<pre><code>from contrib.utils import ColouredLogger # from the SO question above
logging.setLoggerClass(ColouredLogger)
</code></pre>
<p>... where contrib.utils is where I put airmind's code from the above link to his SO answer.</p>
<p>However, that doesn't seem to do anything to the output to the console for GAE, which continues to be in the original format + plain color.</p>
<p>Suggestions and input would be much appreciated.</p>
<p>Cheers,
Brian</p>
| 11 | 2009-08-16T21:20:08Z | 16,819,871 | <p>Django already has support for color output through the '<a href="https://docs.djangoproject.com/en/dev/ref/django-admin/#syntax-coloring">DJANGO_COLORS</a>' environment variable used for example when running the built in development server. Some person has noticed this and created a plug-and-play solution <a href="https://github.com/tiliv/django-colors-formatter">https://github.com/tiliv/django-colors-formatter</a>; with that package on the project's python path my logging <code>settings.py</code> is as follow:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'()': 'djangocolors_formatter.DjangoColorsFormatter', # colored output
'format': '%(levelname)s %(name)s %(asctime)s %(module)s %(process)d %(thread)d %(pathname)s@%(lineno)s: %(message)s'
},
'simple': {
'()': 'djangocolors_formatter.DjangoColorsFormatter', # colored output
'format': '%(levelname)s %(name)s %(filename)s@%(lineno)s: %(message)s'
},
},
# omitting the handler 'level' setting so that all messages are passed and we do level filtering in 'loggers'
'handlers': {
'null': {
'class':'django.utils.log.NullHandler',
},
'console':{
'class':'logging.StreamHandler',
'formatter': 'simple',
},
'mail_admins': {
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
'formatter': 'verbose'
}
},
'loggers': {
'': {
'handlers': ['mail_admins', 'console'],
'level': 'WARNING',
},
}
}
</code></pre>
<p>Sample console logging output using django-colors-formatter:
<img src="http://i.stack.imgur.com/GVe4r.png" alt="Sample console logging output"></p>
| 6 | 2013-05-29T17:00:14Z | [
"python",
"django",
"google-app-engine",
"logging",
"colors"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,475 | <p>You'll need two loops (or equivalently a loop and a listcomp, like below), but not nested ones:</p>
<pre><code>import collections
d = collections.defaultdict(int)
for x in L: d[x] += 1
L[:] = [x for x in L if d[x] == 1]
</code></pre>
<p>This solution assumes that the list items are <em>hashable</em>, that is, that they're usable as indices into dicts, members of sets, etc.</p>
<p>The OP indicates they care about object IDENTITY and not VALUE (so for example two sublists both worth <code>[1,2,3</code> which are equal but may not be identical would not be considered duplicates). If that's indeed the case then this code is usable, just replace <code>d[x]</code> with <code>d[id(x)]</code> in both occurrences and it will work for ANY types of objects in list L.</p>
<p>Mutable objects (lists, dicts, sets, ...) are typically not hashable and therefore cannot be used in such ways. User-defined objects are by default hashable (with <code>hash(x) == id(x)</code>) unless their class defines comparison special methods (<code>__eq__</code>, <code>__cmp__</code>, ...) in which case they're hashable if and only if their class also defines a <code>__hash__</code> method.</p>
<p>If list L's items are not hashable, but <em>are</em> comparable for inequality (and therefore sortable), and you don't care about their order within the list, you can perform the task in time <code>O(N log N)</code> by first sorting the list and then applying <code>itertools.groupby</code> (almost but not quite in the way another answer suggested).</p>
<p>Other approaches, of gradually decreasing perfomance and increasing generality, can deal with unhashable sortables when you DO care about the list's original order (make a sorted copy and in a second loop check out repetitions on it with the help of <code>bisect</code> -- also O(N log N) but a tad slower), and with objects whose only applicable property is that they're comparable for equality (no way to avoid the dreaded O(N**2) performance in that maximally general case).</p>
<p>If the OP can clarify which case applies to his specific problem I'll be glad to help (and in particular, if the objects in his are ARE hashable, the code I've already given above should suffice;-).</p>
| 12 | 2009-08-16T22:16:56Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,482 | <pre><code>[x for x in the_list if the_list.count(x)==1]
</code></pre>
<p>Though that's still a nested loop behind the scenes.</p>
| 8 | 2009-08-16T22:18:33Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,484 | <pre><code>>>> l = [0,1,1,2,2]
>>> [x for x in l if l.count(x) is 1]
[0]
</code></pre>
| 3 | 2009-08-16T22:20:29Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,648 | <pre><code>l = [0,1,2,1,2]
def justonce( l ):
once = set()
more = set()
for x in l:
if x not in more:
if x in once:
more.add(x)
once.remove( x )
else:
once.add( x )
return once
print justonce( l )
</code></pre>
| 3 | 2009-08-16T23:37:19Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,770 | <p>Here's another dictionary oriented way:</p>
<pre><code>l = [0, 1, 1, 2, 2]
d = {}
for i in l: d[i] = d.has_key(i)
[k for k in d.keys() if not d[k]]
</code></pre>
| 5 | 2009-08-17T00:58:17Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,810 | <p>In the same spirit as Alex's solution you can use a <a href="http://code.activestate.com/recipes/576611/" rel="nofollow">Counter</a>/multiset (built in 2.7, recipe compatible from 2.5 and above) to do the same thing:</p>
<pre><code>In [1]: from counter import Counter
In [2]: L = [0, 1, 1, 2, 2]
In [3]: multiset = Counter(L)
In [4]: [x for x in L if multiset[x] == 1]
Out[4]: [0]
</code></pre>
| 4 | 2009-08-17T01:18:15Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,285,916 | <p>I think the actual timings are kind of interesting:</p>
<p>Alex' answer:</p>
<pre><code>python -m timeit -s "l = range(1,1000,2) + range(1,1000,3); import collections" "d = collections.defaultdict(int)" "for x in l: d[x] += 1" "l[:] = [x for x in l if d[x] == 1]"
1000 loops, best of 3: 370 usec per loop
</code></pre>
<p>Mine:</p>
<pre><code>python -m timeit -s "l = range(1,1000,2) + range(1,1000,3)" "once = set()" "more = set()" "for x in l:" " if x not in more:" " if x in once:" " more.add(x)" " once.remove( x )" " else:" " once.add( x )"
1000 loops, best of 3: 275 usec per loop
</code></pre>
<p>sepp2k's O(n**2) version, to demonstrate why compexity matters ;-)</p>
<pre><code>python -m timeit -s "l = range(1,1000,2) + range(1,1000,3)" "[x for x in l if l.count(x)==1]"
100 loops, best of 3: 16 msec per loop
</code></pre>
<p>Roberto's + sorted:</p>
<pre><code>python -m timeit -s "l = range(1,1000,2) + range(1,1000,3); import itertools" "[elem[0] for elem in itertools.groupby(sorted(l)) if elem[1].next()== 0]"
1000 loops, best of 3: 316 usec per loop
</code></pre>
<p>mhawke's:</p>
<pre><code>python -m timeit -s "l = range(1,1000,2) + range(1,1000,3)" "d = {}" "for i in l: d[i] = d.has_key(i)" "[k for k in d.keys() if not d[k]]"
1000 loops, best of 3: 251 usec per loop
</code></pre>
<p>I like the last, clever and fast ;-)</p>
| 1 | 2009-08-17T02:16:14Z | [
"python",
"list",
"filter"
] |
Python filter a list to only leave objects that occur once | 1,285,468 | <p>I would like to filter this list,</p>
<p>l = [0,1,1,2,2]</p>
<p>to only leave,</p>
<p>[0].</p>
<p>I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?</p>
| 5 | 2009-08-16T22:13:05Z | 1,286,037 | <pre><code>>>> l = [0,1,1,2,2]
>>> [x for x in l if l.count(x) == 1]
[0]
</code></pre>
| 1 | 2009-08-17T03:27:06Z | [
"python",
"list",
"filter"
] |
What would you call a non-persistent data structure that allows persistent operations? | 1,285,657 | <p>I've got a class that is essentially mutable, but allows for some "persistent-like" operations. For example, I can mutate the object like this (in Python):</p>
<pre><code># create an object with y equal to 3 and z equal to "foobar"
x = MyDataStructure(y = 3, z = "foobar")
x.y = 4
</code></pre>
<p>However, in lieu of doing things this way, there are a couple of methods that instead make a copy and then mutate it:</p>
<pre><code>x = MyDataStructure(y=3, z="foobar")
# a is just like x, but with y equal to 4.
a = x.using(y = 4)
</code></pre>
<p>This is making a duplicate of x with different values. Apparently, this doesn't meet the definition of partially persistent given by <a href="http://en.wikipedia.org/wiki/Persistent%5Fdata%5Fstructure" rel="nofollow">wikipedia</a>.</p>
<p>So what would you call a class like this? QuasiPersistentObject? PersistableObject? SortOfPersistentObject? Better yet, are there any technical names for this?</p>
| 4 | 2009-08-16T23:43:37Z | 1,285,668 | <p>I call this kind of data <strong>Persistable</strong> but not sure if it's a word
.</p>
| 2 | 2009-08-16T23:48:39Z | [
"python",
"data-structures",
"functional-programming",
"persistence",
"naming"
] |
What would you call a non-persistent data structure that allows persistent operations? | 1,285,657 | <p>I've got a class that is essentially mutable, but allows for some "persistent-like" operations. For example, I can mutate the object like this (in Python):</p>
<pre><code># create an object with y equal to 3 and z equal to "foobar"
x = MyDataStructure(y = 3, z = "foobar")
x.y = 4
</code></pre>
<p>However, in lieu of doing things this way, there are a couple of methods that instead make a copy and then mutate it:</p>
<pre><code>x = MyDataStructure(y=3, z="foobar")
# a is just like x, but with y equal to 4.
a = x.using(y = 4)
</code></pre>
<p>This is making a duplicate of x with different values. Apparently, this doesn't meet the definition of partially persistent given by <a href="http://en.wikipedia.org/wiki/Persistent%5Fdata%5Fstructure" rel="nofollow">wikipedia</a>.</p>
<p>So what would you call a class like this? QuasiPersistentObject? PersistableObject? SortOfPersistentObject? Better yet, are there any technical names for this?</p>
| 4 | 2009-08-16T23:43:37Z | 1,285,682 | <p>It's just a optimized copy, I'd rather rename the operation to reflect that. </p>
<pre><code>a = x.copy_with(y=4)
</code></pre>
| 2 | 2009-08-16T23:56:42Z | [
"python",
"data-structures",
"functional-programming",
"persistence",
"naming"
] |
Using Python Mechanize like "Tamper Data" | 1,285,895 | <p>I'm writing a web testing script with python (2.6) and mechanize (0.1.11). The page I'm working with has an html form with a select field like this:</p>
<pre><code><select name="field1" size="1">
<option value="A" selected>A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</code></pre>
<p>In mechanize, if I try something like this:</p>
<pre><code>browser.form['field1'] = ['E']
</code></pre>
<p>Then I get an error: <code>ClientForm.ItemNotFoundError: insufficient items with name 'E'</code></p>
<p>I can do this manually with the "Tamper Data" firefox extension. Is there a way to do this with python and mechanize? Can I somehow convince mechanize that the form actually has the value I want to submit?</p>
| 3 | 2009-08-17T02:05:02Z | 1,286,047 | <p>After poking around with the guts of ClientForm, it looks like you can trick it into adding another item.</p>
<p>For a select field, something like this seems to work:</p>
<pre><code>xitem = ClientForm.Item(browser.form.find_control(name="field1"),
{'contents':'E', 'value':'E', 'label':'E'})
</code></pre>
<p>Similarly, for a radio button control</p>
<pre><code>xitem = ClientForm.Item(browser.form.find_control(name="field2"),
{'type':'radio', 'name':'field2', 'value':'X'})
</code></pre>
<p>Note that the Item initializer will automatically update the list of items for the specified control, so you only need to create the item properly for it to appear.</p>
| 7 | 2009-08-17T03:33:46Z | [
"python",
"forms",
"mechanize",
"tampering"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,919 | <p>How about this:</p>
<pre><code>if all(key in foo for key in ["foo","bar"]):
# do stuff
pass
</code></pre>
| 8 | 2009-08-17T02:17:41Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,920 | <p>Well, you could do this:</p>
<pre><code>>>> if all (k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
</code></pre>
| 174 | 2009-08-17T02:18:15Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,925 | <p>How about using lambda?</p>
<pre><code> if reduce( (lambda x, y: x and foo.has_key(y) ), [ True, "foo", "bar"] ): # do stuff
</code></pre>
| 1 | 2009-08-17T02:20:29Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,926 | <pre><code>if set(("foo", "bar")) <= set(myDict): ...
</code></pre>
| 67 | 2009-08-17T02:22:13Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,930 | <p>Using <strong><a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset">sets</a></strong>:</p>
<pre><code>if set(("foo", "bar")).issubset(foo):
#do stuff
</code></pre>
<p>Alternatively:</p>
<pre><code>if set(("foo", "bar")) <= set(foo):
#do stuff
</code></pre>
| 17 | 2009-08-17T02:25:15Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,931 | <p>In case you want to: </p>
<ul>
<li>also get the values for the keys</li>
<li>check more than one dictonary</li>
</ul>
<p>then:</p>
<pre><code>from operator import itemgetter
foo = {'foo':1,'zip':2,'zam':3,'bar':4}
keys = ("foo","bar")
getter = itemgetter(*keys) # returns all values
try:
values = getter(foo)
except KeyError:
# not both keys exist
pass
</code></pre>
| 1 | 2009-08-17T02:25:45Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,285,936 | <p>Not to suggest that this isn't something that you haven't thought of, but I find that the simplest thing is usually the best:</p>
<pre><code>if ("foo" in foo) and ("bar" in foo):
# do stuff
</code></pre>
| 0 | 2009-08-17T02:28:47Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,286,027 | <pre><code>>>> if 'foo' in foo and 'bar' in foo:
... print 'yes'
...
yes
</code></pre>
<p>Jason, () aren't necessary in Python.</p>
| 1 | 2009-08-17T03:22:50Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,286,040 | <p>Alex Martelli's solution <code>set(queries) <= set(my_dict)</code> is the shortest code but may not be the fastest. Assume Q = len(queries) and D = len(my_dict).</p>
<p>This takes O(Q) + O(D) to make the two sets, and then (one hopes!) only O(min(Q,D)) to do the subset test -- assuming of course that Python set look-up is O(1) -- this is worst case (when the answer is True).</p>
<p>The generator solution of hughdbrown (et al?) <code>all(k in my_dict for k in queries)</code> is worst-case O(Q).</p>
<p>Complicating factors:<br />
(1) the loops in the set-based gadget are all done at C-speed whereas the any-based gadget is looping over bytecode.<br />
(2) The caller of the any-based gadget may be able to use any knowledge of probability of failure to order the query items accordingly whereas the set-based gadget allows no such control.</p>
<p>As always, if speed is important, benchmarking under operational conditions is a good idea.</p>
| 3 | 2009-08-17T03:28:50Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 1,552,005 | <h2>Simple benchmarking rig for 3 of the alternatives. </h2>
<p>Put in your own values for D and Q</p>
<pre><code>
>>> from timeit import Timer
>>> setup='''from random import randint as R;d=dict((str(R(0,1000000)),R(0,1000000)) for i in range(D));q=dict((str(R(0,1000000)),R(0,1000000)) for i in range(Q));print("looking for %s items in %s"%(len(q),len(d)))'''
>>> Timer('set(q) <= set(d)','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632499
0.28672504425048828
#This one only works for Python3
>>> Timer('set(q) <= d.keys()','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632084
2.5987625122070312e-05
>>> Timer('all(k in d for k in q)','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632219
1.1920928955078125e-05
</code></pre>
| 23 | 2009-10-11T22:51:48Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 25,458,648 | <p>You don't have to wrap the left side in a set. You can just do this:</p>
<pre class="lang-py prettyprint-override"><code>if {'foo', 'bar'} <= set(some_dict):
pass
</code></pre>
<p>This also performs better than the <code>all(k in d...)</code> solution.</p>
| 10 | 2014-08-23T05:06:54Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 31,413,508 | <pre><code>>>> ok
{'five': '5', 'two': '2', 'one': '1'}
>>> if ('two' and 'one' and 'five') in ok:
... print "cool"
...
cool
</code></pre>
<p>This seems to work</p>
| -1 | 2015-07-14T17:33:05Z | [
"python",
"dictionary"
] |
python: How do I check that multiple keys are in a dict in one go? | 1,285,911 | <p>I want to do something like:</p>
<pre><code>foo = {'foo':1,'zip':2,'zam':3,'bar':4}
if ("foo","bar") in foo:
#do stuff
</code></pre>
<p>I'm not sure if its possible but would like to know. :-)</p>
| 101 | 2009-08-17T02:12:35Z | 38,833,839 | <p>While I like Alex Martelli's answer, it doesn't seem Pythonic to me. That is, I thought an important part of being Pythonic is to be easily understandable. With that goal, <code><=</code> isn't easy to understand.</p>
<p>While it's more characters, using <code>issubset()</code> as suggested by Karl Voigtland's answer is more understandable. Since that method can use a dictionary as an argument, a short, understandable solution is:</p>
<pre class="lang-py prettyprint-override"><code>foo = {'foo': 1, 'zip': 2, 'zam': 3, 'bar': 4}
if set(('foo', 'bar')).issubset(foo):
#do stuff
</code></pre>
<p>I'd like to use <code>{'foo', 'bar'}</code> in place of <code>set(('foo', 'bar'))</code>, because it's shorter. However, it's not that understandable and I think the braces are too easily confused as being a dictionary.</p>
| 2 | 2016-08-08T16:04:35Z | [
"python",
"dictionary"
] |
How To Clone/Mutate A Model In Django Without Subclassing | 1,285,977 | <p>'Ello, all. I'm trying to create a model in Django based on - but not subclassing or having a DB relation to - another model. My original model looks something like this: it stores some data with a date/time stamp. </p>
<pre><code>class Entry(Model):
data1 = FloatField()
data2 = FloatField()
entered = DateTimeField()
</code></pre>
<p>I'd also like to aggregate the numeric data for each of these entries on a daily basis, using a model that is almost identical. For the DailyAvg() variant, we'll use a DateField() instead of a DateTimeField(), as there'll only be one average per day:</p>
<pre><code>class EntryDailyAvg(Model):
data1 = FloatField()
data2 = FloatField()
entered = DateField()
</code></pre>
<p>Thus the problem: There's going to be a lot of these data classes that will need a corresponding daily average model stored in the DB, and the definitions are almost identical. I could just re-type a definition for an equivalent DailyAvg() class for each data class, but that seems to violate DRY, and is also a huge pain in the arse. I also can't have EntryDailyAvg subclass Entry, as Django will save a new Entry base every time I save a new EntryDailyAvg. </p>
<p>Is there a way to automaticaly (-magically?) generate the DailyAvg() class?</p>
<p>Thanks in advance!</p>
| 0 | 2009-08-17T02:53:09Z | 1,285,995 | <p>What if you create a AbstractEntry class with all the data1 stuff and then, two subclasses: Entry and EntryDailyAvg.</p>
<p>Check the docs for info on how to tell django that one class is abstract.</p>
| 2 | 2009-08-17T03:04:09Z | [
"python",
"django",
"django-models",
"dry",
"aggregation"
] |
Is the order of results coming from a list comprehension guaranteed? | 1,286,167 | <p>When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension:</p>
<pre><code>>> a = [x for x in [1,2,3]]
>> a
[1, 2, 3]
</code></pre>
<p>Equally, is the following equality guaranteed:</p>
<pre><code>>> lroot = [1, 2, 3]
>> la = [x for x in lroot]
>> lb = []
>> for x in lroot:
lb.append(x)
>> lb == la
True
</code></pre>
<p>Specifically, it's the ordering I'm interested in here.</p>
| 14 | 2009-08-17T04:33:24Z | 1,286,180 | <p>Yes, the list comprehension preserves the order of the original iterable (if there is one).
If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.</p>
| 20 | 2009-08-17T04:40:01Z | [
"python",
"list-comprehension"
] |
Is the order of results coming from a list comprehension guaranteed? | 1,286,167 | <p>When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension:</p>
<pre><code>>> a = [x for x in [1,2,3]]
>> a
[1, 2, 3]
</code></pre>
<p>Equally, is the following equality guaranteed:</p>
<pre><code>>> lroot = [1, 2, 3]
>> la = [x for x in lroot]
>> lb = []
>> for x in lroot:
lb.append(x)
>> lb == la
True
</code></pre>
<p>Specifically, it's the ordering I'm interested in here.</p>
| 14 | 2009-08-17T04:33:24Z | 1,286,181 | <p>Yes, a list is a sequence. Sequence order is significant.</p>
| 1 | 2009-08-17T04:40:22Z | [
"python",
"list-comprehension"
] |
Where can i get technical information on how the internals of Django works? | 1,286,176 | <p>Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;</p>
<ul>
<li>which django function receives it? </li>
<li>what middleware get called? </li>
<li>how is the request object created? and what class/function creates it?</li>
<li>What function maps the request to the necessary view? </li>
<li>How does your code/view get called</li>
</ul>
<p>?
etc...</p>
<p>Paul.G</p>
| 6 | 2009-08-17T04:38:12Z | 1,286,186 | <p>"Use the source, Luke." The beauty of open source software is that you can view (and modify) the code yourself.</p>
| 8 | 2009-08-17T04:42:23Z | [
"python",
"django"
] |
Where can i get technical information on how the internals of Django works? | 1,286,176 | <p>Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;</p>
<ul>
<li>which django function receives it? </li>
<li>what middleware get called? </li>
<li>how is the request object created? and what class/function creates it?</li>
<li>What function maps the request to the necessary view? </li>
<li>How does your code/view get called</li>
</ul>
<p>?
etc...</p>
<p>Paul.G</p>
| 6 | 2009-08-17T04:38:12Z | 1,286,187 | <p>I doubt there are technical manuals on the subject. It might take a bit of digging, but the API documentation and the source code are your best bets for reliable, up-to-date information.</p>
| 1 | 2009-08-17T04:43:43Z | [
"python",
"django"
] |
Where can i get technical information on how the internals of Django works? | 1,286,176 | <p>Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;</p>
<ul>
<li>which django function receives it? </li>
<li>what middleware get called? </li>
<li>how is the request object created? and what class/function creates it?</li>
<li>What function maps the request to the necessary view? </li>
<li>How does your code/view get called</li>
</ul>
<p>?
etc...</p>
<p>Paul.G</p>
| 6 | 2009-08-17T04:38:12Z | 1,286,191 | <p>The documentation often goes into detail when it has to in order to explain why things work the way they do. One of Django's design goals is to not rely on "magic" as much as possible. However, whenever Django <em>does</em> assume something (template locations within apps, for example) its clearly explained why in the documentation and it always occurs predictably.</p>
<p>Most of your questions would be answered by implementing a single page.</p>
<ol>
<li>A request is made from the client for a particular url.</li>
<li>The url resolves what view to call based on the url pattern match.</li>
<li>The request is passed through the middleware.</li>
<li>The view is called and explicitly passed the request object.</li>
<li>The view explicitly calls the template you specify and passes it the context (variables) you specify.</li>
<li>Template context processors, if there are any, then add their own variables to the context.</li>
<li>The context is passed to the template and it is rendered.</li>
<li>The rendered template is returned to the client.</li>
</ol>
<p><a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">Django Documentation</a></p>
<p><a href="http://www.djangobook.com/" rel="nofollow">Django Book</a></p>
| 0 | 2009-08-17T04:46:09Z | [
"python",
"django"
] |
Where can i get technical information on how the internals of Django works? | 1,286,176 | <p>Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;</p>
<ul>
<li>which django function receives it? </li>
<li>what middleware get called? </li>
<li>how is the request object created? and what class/function creates it?</li>
<li>What function maps the request to the necessary view? </li>
<li>How does your code/view get called</li>
</ul>
<p>?
etc...</p>
<p>Paul.G</p>
| 6 | 2009-08-17T04:38:12Z | 1,286,241 | <p>Besides reading the source, here's a few articles I've tagged and bookmarked from a little while ago:</p>
<ul>
<li><a href="http://www.b-list.org/weblog/2006/jun/13/how-django-processes-request/">How Django processes a request</a></li>
<li><a href="http://uswaretech.com/blog/2009/06/django-request-response-processing/">Django Request Response processing</a></li>
<li><a href="http://jacobian.org/writing/django-internals-authen/">Django internals: authentication</a></li>
<li><a href="http://lazypython.blogspot.com/2008/11/how-heck-do-django-models-work.html">How the Heck do Django Models Work</a></li>
</ul>
<p>I've found James Bennet's <a href="http://www.b-list.org">blog</a> to be a a great source for information about django workings. His book, <a href="http://apress.com/book/view/1590599969">Practical Django Projects</a>, is also a must read -- though it isn't focused on internals, you'll still learn about how django works.</p>
| 10 | 2009-08-17T05:09:40Z | [
"python",
"django"
] |
Where can i get technical information on how the internals of Django works? | 1,286,176 | <p>Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;</p>
<ul>
<li>which django function receives it? </li>
<li>what middleware get called? </li>
<li>how is the request object created? and what class/function creates it?</li>
<li>What function maps the request to the necessary view? </li>
<li>How does your code/view get called</li>
</ul>
<p>?
etc...</p>
<p>Paul.G</p>
| 6 | 2009-08-17T04:38:12Z | 1,287,116 | <p>Easiest way to understand the internals of django, is by reading a book specifically written for that.</p>
<p>Read <a href="http://rads.stackoverflow.com/amzn/click/1430210478">Pro Django</a>. It provides you a good in depth understanding of the meta programming first and demonstrates how it is used in django models, to create them dynamically.</p>
<p>It deals similarly with many other python concepts and how django uses it.</p>
| 8 | 2009-08-17T09:57:49Z | [
"python",
"django"
] |
Where can i get technical information on how the internals of Django works? | 1,286,176 | <p>Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;</p>
<ul>
<li>which django function receives it? </li>
<li>what middleware get called? </li>
<li>how is the request object created? and what class/function creates it?</li>
<li>What function maps the request to the necessary view? </li>
<li>How does your code/view get called</li>
</ul>
<p>?
etc...</p>
<p>Paul.G</p>
| 6 | 2009-08-17T04:38:12Z | 1,287,730 | <p>Simply reading the source might be a bit overwhelming, especially since the upper-most part is a bit confusing (how the webserver hands off the request to Django code). I find a good way to get started reading the code is to set a debugger breakpoint in your view function:</p>
<pre><code>def time(request):
import pdb; pdb.set_trace()
return HttpResponse(blah blah)
</code></pre>
<p>then hit your URL. When the debugger breaks at your breakpoint, examine the stack:</p>
<pre><code>(Pdb) where
c:\abcxyzproject\django\core\management\commands\runserver.py(60)inner_run()
-> run(addr, int(port), handler)
c:\abcxyzproject\django\core\servers\basehttp.py(698)run()
-> httpd.serve_forever()
c:\python25\lib\socketserver.py(201)serve_forever()
-> self.handle_request()
c:\python25\lib\socketserver.py(222)handle_request()
-> self.process_request(request, client_address)
c:\python25\lib\socketserver.py(241)process_request()
-> self.finish_request(request, client_address)
c:\python25\lib\socketserver.py(254)finish_request()
-> self.RequestHandlerClass(request, client_address, self)
c:\abcxyzproject\django\core\servers\basehttp.py(560)__init__()
-> BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
c:\python25\lib\socketserver.py(522)__init__()
-> self.handle()
c:\abcxyzproject\django\core\servers\basehttp.py(605)handle()
-> handler.run(self.server.get_app())
c:\abcxyzproject\django\core\servers\basehttp.py(279)run()
-> self.result = application(self.environ, self.start_response)
c:\abcxyzproject\django\core\servers\basehttp.py(651)__call__()
-> return self.application(environ, start_response)
c:\abcxyzproject\django\core\handlers\wsgi.py(241)__call__()
-> response = self.get_response(request)
c:\abcxyzproject\django\core\handlers\base.py(92)get_response()
-> response = callback(request, *callback_args, **callback_kwargs)
> c:\abcxyzproject\abcxyz\helpers\views.py(118)time()
-> return HttpResponse(
(Pdb)
</code></pre>
<p>Now you can see a summary of the path from the deepest part of the web server to your view function. Use the "up" command to move up the stack, and the "list" and "print" command to examine the code and variables at those stack frames.</p>
| 5 | 2009-08-17T12:37:37Z | [
"python",
"django"
] |
Why does this python method gives an error saying global name not defined? | 1,286,235 | <p>I have a single code file for my Google App Engine project. This simple file has one class, and inside it a few methods.
Why does this python method gives an error saying global name not defined?
<br>Erro NameError: global name 'gen_groups' is not defined</p>
<pre><code>import wsgiref.handlers
from google.appengine.ext import webapp
from django.utils import simplejson
class MainHandler(webapp.RequestHandler):
def gen_groups(self, lines):
""" Returns contiguous groups of lines in a file """
group = []
for line in lines:
line = line.strip()
if not line and group:
yield group
group = []
elif line:
group.append(line)
def gen_albums(self, groups):
""" Given groups of lines in an album file, returns albums """
for group in groups:
title = group.pop(0)
songinfo = zip(*[iter(group)]*2)
songs = [dict(title=title,url=url) for title,url in songinfo]
album = dict(title=title, songs=songs)
yield album
def get(self):
input = open('links.txt')
groups = gen_groups(input)
albums = gen_albums(groups)
print simplejson.dumps(list(albums))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2009-08-17T05:07:54Z | 1,286,247 | <p>You need to call it explicitly with an instance:</p>
<pre><code>groups = self.gen_groups(input)
</code></pre>
<p>Similarly for some of the other calls you're making in there, e.g. <code>gen_album</code>.</p>
<p>Also, see <a href="http://diveintopython.net/object_oriented_framework/defining_classes.html#d0e11896" rel="nofollow">Knowing When to Use self and <code>__init__</code></a> for more information.</p>
| 1 | 2009-08-17T05:11:27Z | [
"python",
"google-app-engine"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.