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 |
|---|---|---|---|---|---|---|---|---|---|
Bind event to wx.Menu() instead of to the menu item in wxPython | 1,191,221 | <p>My problem can be easily defined with the following code:</p>
<pre><code>self.Bind(wx.EVT_MENU_OPEN, self.OnAbout)
</code></pre>
<p>This will mean that when I click on any wx.Menu() in the MenuBar, the function 'onAbout()' is called. How do I bind this event to a specific wx.Menu() which is called wx.MenuAbout() ?</p>
<p>If you are feeling extra helpful, perhaps you could provide me with a link to the documentation for event handlers. I could find documentation for the event handler function but not for the actual event handlers (such as wx.EVT_MENU).</p>
<p>Similar question but I am not looking to bind a range of wx.Menu()'s to the event: <a href="http://stackoverflow.com/questions/300032/is-it-possible-to-bind-an-event-against-a-menu-instead-of-a-menu-item-in-wxpython">http://stackoverflow.com/questions/300032/is-it-possible-to-bind-an-event-against-a-menu-instead-of-a-menu-item-in-wxpython</a></p>
<p>Edit: Ideally, this is what I'd like to be able to do:</p>
<pre><code>menuAbout = wx.Menu()
self.Bind(wx.EVT_MENU, self.OnAbout, id=menuAbout.GetId())
</code></pre>
<p>The result would be that any other items in the .menuBar() (such as: File, Edit, Tools) work as normal menu's, but 'About' works like a clickable link.</p>
<p>Using the wx.EVT_MENU_OPEN means that the File menu can be opened, then when the mouse hovers over 'about', the self.OnAbout function get's called which I only what to happen when the user clicks specifically on the 'About' menu.</p>
| 1 | 2009-07-27T23:39:46Z | 27,258,400 | <p>This works for me:</p>
<pre><code>class myFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "my frame")
#give the Frame a menu bar
self.frame_menubar = wx.MenuBar()
fileMenu = wx.Menu()
self.frame_menubar.Append(fileMenu, "File")
self.rotMenu = wx.Menu()
self.frame_menubar.Append(self.rotMenu, "Rotate")
self.SetMenuBar(self.frame_menubar)
self.Bind(wx.EVT_MENU_OPEN, self.rot)
def rot(self, event):
if event.GetMenu() == self.rotMenu:
print 'rotate clicked'
</code></pre>
| 0 | 2014-12-02T20:32:01Z | [
"python",
"wxpython"
] |
FormEncode, pylons, and mako example | 1,191,265 | <p>I'm working in pylons with mako, and I'd like to create forms and validations with FormEncode for several parts of my application. I can't seem to find any good examples of the whole process. My question is twofold:</p>
<p>Technical</p>
<ul>
<li> FancyValidators and Schemas - Their relationship and syntax</li>
<li> Pylons controllers and mako templates - how to collect, handle, and validate the data</li>
</ul>
<p>Stylistic</p>
<ul>
<li> Best practices for controller methods</li>
<li> Easing the reuse of forms (for update vs create, for example)</li>
</ul>
<p>So if you know of any complete examples, it would be much appreciated. I would think this would be a common combination with more examples/tutorials out there.</p>
| 1 | 2009-07-27T23:56:40Z | 1,197,076 | <p>I don't know if you've gone through the pylons book, but I found <a href="http://pylonsbook.com/en/1.0/working-with-forms-and-validators.html" rel="nofollow">chapter 6</a> to be very thorough in regards to forms. </p>
<p>As far as best practices go, I'm not exactly sure what you are looking for. A controller method maps to a url and needs to return a string-like object. How you arrive at that is largely application specific and you are free to choose how you structure the application.</p>
<p>For form reuse, I don't know if it would be considered a best practice but tw.forms I find pretty useful for just that (and toscawidgets for general html snippet reuse). If you anticipate having to reuse fields in forms, you may have some success with fieldsets.</p>
<p>If you are looking for complete examples, I would consider turbogears2 a good resource. It's built on top of pylons so any information on tg2 is equally applicable to pylons. </p>
<p>You can also look at the <a href="http://code.reddit.com/" rel="nofollow">reddit source code</a></p>
<p>And finally, someone will suggest django. :) </p>
| 1 | 2009-07-28T22:20:59Z | [
"python",
"validation",
"pylons",
"mako",
"formencode"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 1,191,537 | <p>If you're on Unix,</p>
<pre><code>import signal
...
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(5*60) # 5 minutes
try:
stdoutdata, stderrdata = proc.communicate()
signal.alarm(0) # reset the alarm
except Alarm:
print "Oops, taking too long!"
# whatever else
</code></pre>
| 70 | 2009-07-28T01:43:16Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 1,557,452 | <p>I've used <a href="http://benjamin.smedbergs.us/blog/2006-12-11/killableprocesspy/" rel="nofollow">killableprocess</a> successfully on Windows, Linux and Mac. If you are using Cygwin Python, you'll need <a href="http://svn.osafoundation.org/chandler/trunk/chandler/tools/killableprocess.py" rel="nofollow">OSAF's version of killableprocess</a> because otherwise native Windows processes won't get killed.</p>
| 1 | 2009-10-12T23:15:47Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 3,326,559 | <p>Here is Alex Martelli's solution as a module with proper process killing. The other approaches do not work because they do not use proc.communicate(). So if you have a process that produces lots of output, it will fill its output buffer and then block until you read something from it.</p>
<pre><code>from os import kill
from signal import alarm, signal, SIGALRM, SIGKILL
from subprocess import PIPE, Popen
def run(args, cwd = None, shell = False, kill_tree = True, timeout = -1, env = None):
'''
Run a command with a timeout after which it will be forcibly
killed.
'''
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env)
if timeout != -1:
signal(SIGALRM, alarm_handler)
alarm(timeout)
try:
stdout, stderr = p.communicate()
if timeout != -1:
alarm(0)
except Alarm:
pids = [p.pid]
if kill_tree:
pids.extend(get_process_children(p.pid))
for pid in pids:
# process might have died before getting to this line
# so wrap to avoid OSError: no such process
try:
kill(pid, SIGKILL)
except OSError:
pass
return -9, '', ''
return p.returncode, stdout, stderr
def get_process_children(pid):
p = Popen('ps --no-headers -o pid --ppid %d' % pid, shell = True,
stdout = PIPE, stderr = PIPE)
stdout, stderr = p.communicate()
return [int(p) for p in stdout.split()]
if __name__ == '__main__':
print run('find /', shell = True, timeout = 3)
print run('find', shell = True)
</code></pre>
| 39 | 2010-07-24T19:29:54Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 4,144,642 | <p>Another option is to write to a temporary file to prevent the stdout blocking instead of needing to poll with communicate(). This worked for me where the other answers did not; for example on windows.</p>
<pre><code> outFile = tempfile.SpooledTemporaryFile()
errFile = tempfile.SpooledTemporaryFile()
proc = subprocess.Popen(args, stderr=errFile, stdout=outFile, universal_newlines=False)
wait_remaining_sec = timeout
while proc.poll() is None and wait_remaining_sec > 0:
time.sleep(1)
wait_remaining_sec -= 1
if wait_remaining_sec <= 0:
killProc(proc.pid)
raise ProcessIncompleteError(proc, timeout)
# read temp streams from start
outFile.seek(0);
errFile.seek(0);
out = outFile.read()
err = errFile.read()
outFile.close()
errFile.close()
</code></pre>
| 9 | 2010-11-10T12:51:15Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 4,825,933 | <p>I don't know much about the low level details; but, given that in
python 2.6 the API offers the ability to wait for threads and
terminate processes, what about running the process in a separate
thread?</p>
<pre><code>import subprocess, threading
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print 'Thread started'
self.process = subprocess.Popen(self.cmd, shell=True)
self.process.communicate()
print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.terminate()
thread.join()
print self.process.returncode
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=3)
command.run(timeout=1)
</code></pre>
<p>The output of this snippet in my machine is:</p>
<pre><code>Thread started
Process started
Process finished
Thread finished
0
Thread started
Process started
Terminating process
Thread finished
-15
</code></pre>
<p>where it can be seen that, in the first execution, the process
finished correctly (return code 0), while the in the second one the
process was terminated (return code -15).</p>
<p>I haven't tested in windows; but, aside from updating the example
command, I think it should work since I haven't found in the
documentation anything that says that thread.join or process.terminate
is not supported.</p>
| 165 | 2011-01-28T07:39:08Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 4,878,500 | <p>I've implemented what I could gather from a few of these. This works in Windows, and since this is a community wiki, I figure I would share my code as well:</p>
<pre><code>class Command(threading.Thread):
def __init__(self, cmd, outFile, errFile, timeout):
threading.Thread.__init__(self)
self.cmd = cmd
self.process = None
self.outFile = outFile
self.errFile = errFile
self.timed_out = False
self.timeout = timeout
def run(self):
self.process = subprocess.Popen(self.cmd, stdout = self.outFile, \
stderr = self.errFile)
while (self.process.poll() is None and self.timeout > 0):
time.sleep(1)
self.timeout -= 1
if not self.timeout > 0:
self.process.terminate()
self.timed_out = True
else:
self.timed_out = False
</code></pre>
<p>Then from another class or file:</p>
<pre><code> outFile = tempfile.SpooledTemporaryFile()
errFile = tempfile.SpooledTemporaryFile()
executor = command.Command(c, outFile, errFile, timeout)
executor.daemon = True
executor.start()
executor.join()
if executor.timed_out:
out = 'timed out'
else:
outFile.seek(0)
errFile.seek(0)
out = outFile.read()
err = errFile.read()
outFile.close()
errFile.close()
</code></pre>
| 2 | 2011-02-02T18:47:14Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 5,611,718 | <p>I added the solution with threading from <code>jcollado</code> to my Python module <a href="http://code.activestate.com/pypm/easyprocess/" rel="nofollow">easyprocess</a>.</p>
<p>Install:</p>
<pre><code>pip install easyprocess
</code></pre>
<p>Example:</p>
<pre><code>from easyprocess import Proc
# shell is not supported!
stdout=Proc('ping localhost').call(timeout=1.5).stdout
print stdout
</code></pre>
| 4 | 2011-04-10T12:28:02Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 7,169,548 | <p>Although I haven't looked at it extensively, this <a href="http://code.activestate.com/recipes/307871-timing-out-function/" rel="nofollow">decorator</a> I found at ActiveState seems to be quite useful for this sort of thing. Along with <code>subprocess.Popen(..., close_fds=True)</code>, at least I'm ready for shell-scripting in Python.</p>
| 1 | 2011-08-24T01:42:21Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 8,507,775 | <p>The solution I use is to prefix the shell command with <a href="http://devel.ringlet.net/sysutils/timelimit/" rel="nofollow">timelimit</a>. If the comand takes too long, timelimit will stop it and Popen will have a returncode set by timelimit. If it is > 128, it means timelimit killed the process.</p>
<p>See also <a href="http://stackoverflow.com/questions/3575554/python-subprocess-with-timeout-and-large-output-64k">python subprocess with timeout and large output (>64K)</a></p>
| 4 | 2011-12-14T16:14:40Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 10,012,262 | <p>jcollado's answer can be simplified using the threading.Timer class:</p>
<pre><code>import subprocess, shlex
from threading import Timer
def run(cmd, timeout_sec):
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
kill_proc = lambda p: p.kill()
timer = Timer(timeout_sec, kill_proc, [proc])
try:
timer.start()
stdout,stderr = proc.communicate()
finally:
timer.cancel()
</code></pre>
| 46 | 2012-04-04T13:36:49Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 10,552,626 | <p>Once you understand full process running machinery in *unix, you will easily find simplier solution:</p>
<p>Consider this simple example how to make timeoutable communicate() meth using select.select() (available alsmost everythere on *nix nowadays). This also can be written with epoll/poll/kqueue, but select.select() variant could be a good example for you. And major limitations of select.select() (speed and 1024 max fds) are not applicapable for your task.</p>
<p>This works under *nix, does not create threads, does not uses signals, can be lauched from any thread (not only main), and fast enought to read 250mb/s of data from stdout on my machine (i5 2.3ghz).</p>
<p>There is a problem in join'ing stdout/stderr at the end of communicate. If you have huge program output this could lead to big memory usage. But you can call communicate() several times with smaller timeouts.</p>
<pre><code>class Popen(subprocess.Popen):
def communicate(self, input=None, timeout=None):
if timeout is None:
return subprocess.Popen.communicate(self, input)
if self.stdin:
# Flush stdio buffer, this might block if user
# has been writing to .stdin in an uncontrolled
# fashion.
self.stdin.flush()
if not input:
self.stdin.close()
read_set, write_set = [], []
stdout = stderr = None
if self.stdin and input:
write_set.append(self.stdin)
if self.stdout:
read_set.append(self.stdout)
stdout = []
if self.stderr:
read_set.append(self.stderr)
stderr = []
input_offset = 0
deadline = time.time() + timeout
while read_set or write_set:
try:
rlist, wlist, xlist = select.select(read_set, write_set, [], max(0, deadline - time.time()))
except select.error as ex:
if ex.args[0] == errno.EINTR:
continue
raise
if not (rlist or wlist):
# Just break if timeout
# Since we do not close stdout/stderr/stdin, we can call
# communicate() several times reading data by smaller pieces.
break
if self.stdin in wlist:
chunk = input[input_offset:input_offset + subprocess._PIPE_BUF]
try:
bytes_written = os.write(self.stdin.fileno(), chunk)
except OSError as ex:
if ex.errno == errno.EPIPE:
self.stdin.close()
write_set.remove(self.stdin)
else:
raise
else:
input_offset += bytes_written
if input_offset >= len(input):
self.stdin.close()
write_set.remove(self.stdin)
# Read stdout / stderr by 1024 bytes
for fn, tgt in (
(self.stdout, stdout),
(self.stderr, stderr),
):
if fn in rlist:
data = os.read(fn.fileno(), 1024)
if data == '':
fn.close()
read_set.remove(fn)
tgt.append(data)
if stdout is not None:
stdout = ''.join(stdout)
if stderr is not None:
stderr = ''.join(stderr)
return (stdout, stderr)
</code></pre>
| 1 | 2012-05-11T13:46:13Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 10,768,774 | <p>I've modified <strong>sussudio</strong> answer. Now function returns: (<code>returncode</code>, <code>stdout</code>, <code>stderr</code>, <code>timeout</code>) - <code>stdout</code> and <code>stderr</code> is decoded to utf-8 string</p>
<pre><code>def kill_proc(proc, timeout):
timeout["value"] = True
proc.kill()
def run(cmd, timeout_sec):
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
timeout = {"value": False}
timer = Timer(timeout_sec, kill_proc, [proc, timeout])
timer.start()
stdout, stderr = proc.communicate()
timer.cancel()
return proc.returncode, stdout.decode("utf-8"), stderr.decode("utf-8"), timeout["value"]
</code></pre>
| 13 | 2012-05-26T18:30:19Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 12,677,928 | <p>Unfortunately, I'm bound by very strict policies on the disclosure of source code by my employer, so I can't provide actual code. But for my taste the best solution is to create a subclass overriding <code>Popen.wait()</code> to poll instead of wait indefinitely, and <code>Popen.__init__</code> to accept a timeout parameter. Once you do that, all the other <code>Popen</code> methods (which call <code>wait</code>) will work as expected, including <code>communicate</code>.</p>
| 0 | 2012-10-01T17:17:49Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 12,698,328 | <p>In Python 3.3+:</p>
<pre><code>from subprocess import STDOUT, check_output
output = check_output(cmd, stderr=STDOUT, timeout=seconds)
</code></pre>
<p><code>output</code> is a byte string that contains command's merged stdout, stderr data. </p>
<p>This code raises <code>CalledProcessError</code> on non-zero exit status as specified in the question's text unlike <code>proc.communicate()</code> method.</p>
<p>I've removed <code>shell=True</code> because it is often used unnecessarily. You can always add it back if <code>cmd</code> indeed requires it. If you add <code>shell=True</code> i.e., if the child process spawns its own descendants; <code>check_output()</code> can return much later than the timeout indicates, see <a href="http://stackoverflow.com/q/36952245/4279">Subprocess timeout failure</a>.</p>
<p>The timeout feature is available on Python 2.x via the <a href="http://pypi.python.org/pypi/subprocess32/"><code>subprocess32</code></a> backport of the 3.2+ subprocess module.</p>
| 75 | 2012-10-02T21:06:25Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 21,845,629 | <pre><code>import subprocess, optparse, os, sys, re, datetime, threading, time, glob, shutil, xml.dom.minidom, traceback
class OutputManager:
def __init__(self, filename, mode, console, logonly):
self.con = console
self.logtoconsole = True
self.logtofile = False
if filename:
try:
self.f = open(filename, mode)
self.logtofile = True
if logonly == True:
self.logtoconsole = False
except IOError:
print (sys.exc_value)
print ("Switching to console only output...\n")
self.logtofile = False
self.logtoconsole = True
def write(self, data):
if self.logtoconsole == True:
self.con.write(data)
if self.logtofile == True:
self.f.write(data)
sys.stdout.flush()
def getTimeString():
return time.strftime("%Y-%m-%d", time.gmtime())
def runCommand(command):
'''
Execute a command in new thread and return the
stdout and stderr content of it.
'''
try:
Output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
except Exception as e:
print ("runCommand failed :%s" % (command))
print (str(e))
sys.stdout.flush()
return None
return Output
def GetOs():
Os = ""
if sys.platform.startswith('win32'):
Os = "win"
elif sys.platform.startswith('linux'):
Os = "linux"
elif sys.platform.startswith('darwin'):
Os = "mac"
return Os
def check_output(*popenargs, **kwargs):
try:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
# Get start time.
startTime = datetime.datetime.now()
timeoutValue=3600
cmd = popenargs[0]
if sys.platform.startswith('win32'):
process = subprocess.Popen( cmd, stdout=subprocess.PIPE, shell=True)
elif sys.platform.startswith('linux'):
process = subprocess.Popen( cmd , stdout=subprocess.PIPE, shell=True )
elif sys.platform.startswith('darwin'):
process = subprocess.Popen( cmd , stdout=subprocess.PIPE, shell=True )
stdoutdata, stderrdata = process.communicate( timeout = timeoutValue )
retcode = process.poll()
####################################
# Catch crash error and log it.
####################################
OutputHandle = None
try:
if retcode >= 1:
OutputHandle = OutputManager( 'CrashJob_' + getTimeString() + '.txt', 'a+', sys.stdout, False)
OutputHandle.write( cmd )
print (stdoutdata)
print (stderrdata)
sys.stdout.flush()
except Exception as e:
print (str(e))
except subprocess.TimeoutExpired:
####################################
# Catch time out error and log it.
####################################
Os = GetOs()
if Os == 'win':
killCmd = "taskkill /FI \"IMAGENAME eq {0}\" /T /F"
elif Os == 'linux':
killCmd = "pkill {0)"
elif Os == 'mac':
# Linux, Mac OS
killCmd = "killall -KILL {0}"
runCommand(killCmd.format("java"))
runCommand(killCmd.format("YouApp"))
OutputHandle = None
try:
OutputHandle = OutputManager( 'KillJob_' + getTimeString() + '.txt', 'a+', sys.stdout, False)
OutputHandle.write( cmd )
except Exception as e:
print (str(e))
except Exception as e:
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname,lineno,fn,text = frame
print "Error in %s on line %d" % (fname, lineno)
</code></pre>
| -1 | 2014-02-18T06:09:01Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 22,886,770 | <p>Was just trying to write something simpler.</p>
<pre><code>#!/usr/bin/python
from subprocess import Popen, PIPE
import datetime
import time
popen = Popen(["/bin/sleep", "10"]);
pid = popen.pid
sttime = time.time();
waittime = 3
print "Start time %s"%(sttime)
while True:
popen.poll();
time.sleep(1)
rcode = popen.returncode
now = time.time();
if [ rcode is None ] and [ now > (sttime + waittime) ] :
print "Killing it now"
popen.kill()
</code></pre>
| -1 | 2014-04-05T21:01:52Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 24,539,984 | <p>Here is my solution, I was using Thread and Event:</p>
<pre><code>import subprocess
from threading import Thread, Event
def kill_on_timeout(done, timeout, proc):
if not done.wait(timeout):
proc.kill()
def exec_command(command, timeout):
done = Event()
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
watcher = Thread(target=kill_on_timeout, args=(done, timeout, proc))
watcher.daemon = True
watcher.start()
data, stderr = proc.communicate()
done.set()
return data, stderr, proc.returncode
</code></pre>
<p>In action:</p>
<pre><code>In [2]: exec_command(['sleep', '10'], 5)
Out[2]: ('', '', -9)
In [3]: exec_command(['sleep', '10'], 11)
Out[3]: ('', '', 0)
</code></pre>
| 4 | 2014-07-02T19:59:19Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 28,660,503 | <p><a href="https://docs.python.org/3/library/subprocess.html#subprocess.call" rel="nofollow"><code>timeout</code> is now supported</a> by <code>call()</code> and <code>communicate()</code> in the subprocess module (as of Python3.3):</p>
<pre><code>import subprocess
subprocess.call("command", timeout=20, shell=True)
</code></pre>
<p>This will call the command and raise the exception</p>
<pre><code>subprocess.TimeoutExpired
</code></pre>
<p>if the command doesn't finish after 20 seconds.</p>
<p>You can then handle the exception to continue your code, something like:</p>
<pre><code>try:
subprocess.call("command", timeout=20, shell=True)
except subprocess.TimeoutExpired:
# insert code here
</code></pre>
<p>Hope this helps.</p>
| 4 | 2015-02-22T16:51:55Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 29,763,091 | <p>surprised nobody mentioned using <code>timeout</code></p>
<p><code>timeout 5 ping -c 3 somehost</code></p>
<p>This won't for work for every use case obviously, but if your dealing with a simple script, this is hard to beat.</p>
<p>Also available as gtimeout in coreutils via <code>homebrew</code> for mac users.</p>
| 9 | 2015-04-21T04:43:41Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 32,783,644 | <p><a href="https://pypi.python.org/pypi/python-subprocess2" rel="nofollow">https://pypi.python.org/pypi/python-subprocess2</a> provides extensions to the subprocess module which allow you to wait up to a certain period of time, otherwise terminate. </p>
<p>So, to wait up to 10 seconds for the process to terminate, otherwise kill:</p>
<pre><code>pipe = subprocess.Popen('...')
timeout = 10
results = pipe.waitOrTerminate(timeout)
</code></pre>
<p>This is compatible with both windows and unix. "results" is a dictionary, it contains "returnCode" which is the return of the app (or None if it had to be killed), as well as "actionTaken". which will be "SUBPROCESS2_PROCESS_COMPLETED" if the process completed normally, or a mask of "SUBPROCESS2_PROCESS_TERMINATED" and SUBPROCESS2_PROCESS_KILLED depending on action taken (see documentation for full details)</p>
| 0 | 2015-09-25T13:45:41Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 38,391,072 | <p>if you are using python 2, give it a try</p>
<pre><code>import subprocess32
try:
output = subprocess32.check_output(command, shell=True, timeout=3)
except subprocess32.TimeoutExpired as e:
print e
</code></pre>
| 1 | 2016-07-15T08:10:19Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Using module 'subprocess' with timeout | 1,191,374 | <p>Here's the Python code to run an arbitrary command returning its <code>stdout</code> data, or raise an exception on non-zero exit codes:</p>
<pre><code>proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
</code></pre>
<p><code>communicate</code> is used to wait for the process to exit:</p>
<pre><code>stdoutdata, stderrdata = proc.communicate()
</code></pre>
<p>The <code>subprocess</code> module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, <code>communicate</code> may take forever to run.</p>
<p>What is the <strong>simplest</strong> way to implement timeouts in a Python program meant to run on Windows and Linux?</p>
| 198 | 2009-07-28T00:41:23Z | 39,108,864 | <p>This solution kills the process tree in case of shell=True, passes parameters to the process (or not), has a timeout and gets the stdout, stderr and process output of the call back (it uses psutil for the kill_proc_tree). This was based on several solutions posted in SO including jcollado's. Posting in response to comments by Anson and jradice in jcollado's answer. Tested in Windows Srvr 2012 and Ubuntu 14.04. Please note that for Ubuntu you need to change the parent.children(...) call to parent.get_children(...).</p>
<pre><code>def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
children = parent.children(recursive=True)
for child in children:
child.kill()
psutil.wait_procs(children, timeout=5)
if including_parent:
parent.kill()
parent.wait(5)
def run_with_timeout(cmd, current_dir, cmd_parms, timeout):
def target():
process = subprocess.Popen(cmd, cwd=current_dir, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
# wait for the process to terminate
if (cmd_parms == ""):
out, err = process.communicate()
else:
out, err = process.communicate(cmd_parms)
errcode = process.returncode
thread = Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
me = os.getpid()
kill_proc_tree(me, including_parent=False)
thread.join()
</code></pre>
| 0 | 2016-08-23T19:04:00Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] |
Sorting and indexing into a list in a Django template? | 1,191,439 | <p>How can you perform complex sorting on an object before passing it to the template? For example, here is my view:</p>
<pre><code>@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
</code></pre>
<p>The physicians object is not ordered correctly in the template. Why not?</p>
<p>Additionally, how do you index into a list inside the template? For example, (this doesn't work):</p>
<pre><code>{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
</code></pre>
<p>Thanks a bunch, Pete</p>
| 5 | 2009-07-28T01:07:41Z | 1,191,500 | <p><strong>"I'd like to do this from within a template:"</strong></p>
<p>Don't. Do it in the view function where it belongs.</p>
<p>Since the question is incomplete, it's impossible to guess at the data model and provide the exact solution. </p>
<pre><code>results= physician.patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
</code></pre>
<p>Should be sufficient. Provide <code>results</code> to the template for rendering. It's in the proper order.</p>
<p>If this isn't sorting properly (perhaps because of some model subtletly) then you always have this kind of alternative.</p>
<pre><code>def by_unit_room_bed( patient ):
return patient.bed.room.unit, patient.bed.room.order, patient.bed.order
patient_list = list( physician.patients )
patient_list.sort( key=by_unit_room_bed )
</code></pre>
<p>Provide <code>patient_list</code> to the template for rendering. It's in the proper order.</p>
<p><strong>"how do you index into a list inside the template"</strong></p>
<p>I'm not sure what you're trying to do, but most of the time, the answer is "Don't". Do it in the view function.</p>
<p>The template just iterate through simple lists filling in simple HTML templates. </p>
<p>If it seems too complex for a template, it is. Keep the template simple -- it's only presentation. The processing goes in the view function</p>
| 4 | 2009-07-28T01:29:05Z | [
"python",
"django",
"django-templates"
] |
Sorting and indexing into a list in a Django template? | 1,191,439 | <p>How can you perform complex sorting on an object before passing it to the template? For example, here is my view:</p>
<pre><code>@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
</code></pre>
<p>The physicians object is not ordered correctly in the template. Why not?</p>
<p>Additionally, how do you index into a list inside the template? For example, (this doesn't work):</p>
<pre><code>{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
</code></pre>
<p>Thanks a bunch, Pete</p>
| 5 | 2009-07-28T01:07:41Z | 1,191,596 | <p>You should be able to construct the ordered query set in your view and pass it to your template:</p>
<pre><code>def myview(request):
patients = Physician.patients.order_by('bed__room__unit',
'bed__room__order',
'bed__order')
return render_to_response('some_template.html',
dict(patients=patients),
mimetype='text/html')
</code></pre>
<p>Your template can then loop over <code>patients</code> which will contain the ordered results. Does this not work for you?</p>
<p>EDIT: For indexing, just use the dot syntax: <code>mylist.3</code> in a template becomes <code>mylist[3]</code> in python. See <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#rendering-a-context" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/templates/api/#rendering-a-context</a> for more information.</p>
| 1 | 2009-07-28T02:05:28Z | [
"python",
"django",
"django-templates"
] |
Sorting and indexing into a list in a Django template? | 1,191,439 | <p>How can you perform complex sorting on an object before passing it to the template? For example, here is my view:</p>
<pre><code>@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
</code></pre>
<p>The physicians object is not ordered correctly in the template. Why not?</p>
<p>Additionally, how do you index into a list inside the template? For example, (this doesn't work):</p>
<pre><code>{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
</code></pre>
<p>Thanks a bunch, Pete</p>
| 5 | 2009-07-28T01:07:41Z | 1,216,920 | <p>As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.</p>
<p>Getting a sorted list of a physician's patients:</p>
<pre><code>class Physician(Model):
...
def sorted_patients(self):
return self.patients.order_by('bed__room__unit',
'bed__room__order',
'bed__order')
</code></pre>
<p>And in the template, use <code>physician.sorted_patients</code> rather than <code>physician.patients</code>.</p>
<p>For the "display the notes of this note_type", it sounds like you might want a <code>notes</code> method for the note_type class. From your description I'm not sure if this is a model class or not, but the principle is the same:</p>
<pre><code>class NoteType:
...
def notes(self):
return <calculate note set>
</code></pre>
<p>And then the template:</p>
<pre><code>{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3></div>
{% for note in note_type.notes %}
<p>{{ note }}</p>
{% endfor %}
</div>
{% endfor %}
</code></pre>
| 11 | 2009-08-01T16:17:19Z | [
"python",
"django",
"django-templates"
] |
Sorting and indexing into a list in a Django template? | 1,191,439 | <p>How can you perform complex sorting on an object before passing it to the template? For example, here is my view:</p>
<pre><code>@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
</code></pre>
<p>The physicians object is not ordered correctly in the template. Why not?</p>
<p>Additionally, how do you index into a list inside the template? For example, (this doesn't work):</p>
<pre><code>{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
</code></pre>
<p>Thanks a bunch, Pete</p>
| 5 | 2009-07-28T01:07:41Z | 2,558,284 | <p>This is one way of doing it, although very ugly :</p>
<p><code>{% for note in note_sets|slice:"forloop.counter0"|first %}</code></p>
| 0 | 2010-04-01T05:19:31Z | [
"python",
"django",
"django-templates"
] |
imagefield won't validate | 1,191,487 | <p>I moved a site to a mediatemple server using python 2.3, now ImageField won't work in the admin. Upon saving, validation gives the "not valid image" error. </p>
<p>checked:</p>
<ul>
<li>media_root and media_url are correct</li>
<li>PIL contains jpg support</li>
<li>upload folders set to 775</li>
<li>image is not corrupted</li>
</ul>
<p>Ideas? Thanks.</p>
| 0 | 2009-07-28T01:24:20Z | 1,663,358 | <p>If you read documentation here: <a href="http://docs.djangoproject.com/en/dev/intro/install/" rel="nofollow">http://docs.djangoproject.com/en/dev/intro/install/</a>
You will find the answer. </p>
<blockquote>
<p>It works with any Python version from
2.4 to 2.6!</p>
</blockquote>
<p>And :</p>
<blockquote>
<p>Set up a database</p>
<p>If you installed Python 2.5 or later,
you can skip this step for now.</p>
<p>If not, or if you'd like to work with
a "large" database engine like
PostgreSQL, MySQL, or Oracle, consult
the database installation information.</p>
</blockquote>
<p>I think that the problem is python 2.3 do you consider upgrade of it to 2.4, 2.5 or 2.6?</p>
| 1 | 2009-11-02T20:02:44Z | [
"python",
"django",
"django-models"
] |
Hello World from cython wiki not working | 1,191,600 | <p>I'm trying to follow this tutorial from Cython: <a href="http://docs.cython.org/docs/tutorial.html#the-basics-of-cython" rel="nofollow">http://docs.cython.org/docs/tutorial.html#the-basics-of-cython</a> and I'm having a problem. </p>
<p>The files are very simple. I have a helloworld.pyx:</p>
<pre><code>print "Hello World"
</code></pre>
<p>and a setup.py:</p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("helloworld", ["helloworld.pyx"])]
)
</code></pre>
<p>and I compile it with the standard command:</p>
<pre><code>python setup.py build_ext --inplace
</code></pre>
<p>I got the following error:</p>
<pre><code>running build
running build_ext
building 'helloworld' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c helloworld.c -o build/temp.linux-x86_64-2.6/helloworld.o
helloworld.c:4:20: error: Python.h: No such file or directory
helloworld.c:5:26: error: structmember.h: No such file or directory
helloworld.c:34: error: expected specifier-qualifier-list before âPyObjectâ
helloworld.c:121: error: expected specifier-qualifier-list before âPyObjectâ
helloworld.c:139: error: expected â)â before â*â token
helloworld.c:140: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsLongLongâ
helloworld.c:141: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsUnsignedLongLongâ
helloworld.c:142: error: expected â)â before â*â token
helloworld.c:147: error: expected â)â before â*â token
helloworld.c:148: error: expected â)â before â*â token
helloworld.c:149: error: expected â)â before â*â token
helloworld.c:150: error: expected â)â before â*â token
helloworld.c:151: error: expected â)â before â*â token
helloworld.c:152: error: expected â)â before â*â token
helloworld.c:153: error: expected â)â before â*â token
helloworld.c:154: error: expected â)â before â*â token
helloworld.c:155: error: expected â)â before â*â token
helloworld.c:156: error: expected â)â before â*â token
helloworld.c:157: error: expected â)â before â*â token
helloworld.c:172: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:173: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:174: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:181: error: expected â)â before â*â token
helloworld.c:198: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:200: error: array type has incomplete element type
helloworld.c:221: error: â__pyx_kp_1â undeclared here (not in a function)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:237: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before âinithelloworldâ
helloworld.c:238: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before âinithelloworldâ
helloworld.c:305: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:313: error: expected â)â before â*â token
helloworld.c:379:21: error: compile.h: No such file or directory
helloworld.c:380:25: error: frameobject.h: No such file or directory
helloworld.c:381:23: error: traceback.h: No such file or directory
helloworld.c: In function â__Pyx_AddTracebackâ:
helloworld.c:384: error: âPyObjectâ undeclared (first use in this function)
helloworld.c:384: error: (Each undeclared identifier is reported only once
helloworld.c:384: error: for each function it appears in.)
helloworld.c:384: error: âpy_srcfileâ undeclared (first use in this function)
helloworld.c:385: error: âpy_funcnameâ undeclared (first use in this function)
helloworld.c:386: error: âpy_globalsâ undeclared (first use in this function)
helloworld.c:387: error: âempty_stringâ undeclared (first use in this function)
helloworld.c:388: error: âPyCodeObjectâ undeclared (first use in this function)
helloworld.c:388: error: âpy_codeâ undeclared (first use in this function)
helloworld.c:389: error: âPyFrameObjectâ undeclared (first use in this function)
helloworld.c:389: error: âpy_frameâ undeclared (first use in this function)
helloworld.c:392: warning: implicit declaration of function âPyString_FromStringâ
helloworld.c:399: warning: implicit declaration of function âPyString_FromFormatâ
helloworld.c:412: warning: implicit declaration of function âPyModule_GetDictâ
helloworld.c:412: error: â__pyx_mâ undeclared (first use in this function)
helloworld.c:415: warning: implicit declaration of function âPyString_FromStringAndSizeâ
helloworld.c:420: warning: implicit declaration of function âPyCode_Newâ
helloworld.c:429: error: â__pyx_empty_tupleâ undeclared (first use in this function)
helloworld.c:440: warning: implicit declaration of function âPyFrame_Newâ
helloworld.c:441: warning: implicit declaration of function âPyThreadState_GETâ
helloworld.c:448: warning: implicit declaration of function âPyTraceBack_Hereâ
helloworld.c:450: warning: implicit declaration of function âPy_XDECREFâ
helloworld.c: In function â__Pyx_InitStringsâ:
helloworld.c:458: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:460: error: â__Pyx_StringTabEntryâ has no member named âis_unicodeâ
helloworld.c:460: error: â__Pyx_StringTabEntryâ has no member named âis_identifierâ
helloworld.c:461: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:461: warning: implicit declaration of function âPyUnicode_DecodeUTF8â
helloworld.c:461: error: â__Pyx_StringTabEntryâ has no member named âsâ
helloworld.c:461: error: â__Pyx_StringTabEntryâ has no member named ânâ
helloworld.c:461: error: âNULLâ undeclared (first use in this function)
helloworld.c:462: error: â__Pyx_StringTabEntryâ has no member named âinternâ
helloworld.c:463: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:463: warning: implicit declaration of function âPyString_InternFromStringâ
helloworld.c:463: error: â__Pyx_StringTabEntryâ has no member named âsâ
helloworld.c:465: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:465: error: â__Pyx_StringTabEntryâ has no member named âsâ
helloworld.c:465: error: â__Pyx_StringTabEntryâ has no member named ânâ
helloworld.c:476: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c: At top level:
helloworld.c:485: error: expected â)â before â*â token
helloworld.c:494: error: expected â)â before â*â token
helloworld.c:500: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsLongLongâ
helloworld.c:516: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsUnsignedLongLongâ
helloworld.c:538: error: expected â)â before â*â token
helloworld.c:553: error: expected â)â before â*â token
helloworld.c:568: error: expected â)â before â*â token
helloworld.c:583: error: expected â)â before â*â token
helloworld.c:598: error: expected â)â before â*â token
helloworld.c:613: error: expected â)â before â*â token
helloworld.c:628: error: expected â)â before â*â token
helloworld.c:643: error: expected â)â before â*â token
helloworld.c:658: error: expected â)â before â*â token
helloworld.c:673: error: expected â)â before â*â token
helloworld.c:688: error: expected â)â before â*â token
error: command 'gcc' failed with exit status 1
</code></pre>
<p>I have python and cython installed from Ubuntu 9.04 repositories. I can't figure why the compiler can't find Python.h.</p>
<p>I tried doing:</p>
<pre><code>cython helloworld.pyx
</code></pre>
<p>and then compiling the result manually with gcc:</p>
<pre><code>gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.5 -o helloworld.so helloworld.c
</code></pre>
<p>and got the same exact error message.</p>
<p>Any clues?</p>
| 2 | 2009-07-28T02:06:04Z | 1,191,622 | <p>Oh damn... forget it... </p>
<p>I forgot to install the dev packages. </p>
<p>Duh. Stupid. Sorry guys.</p>
| 1 | 2009-07-28T02:17:09Z | [
"c++",
"python",
"cython"
] |
Hello World from cython wiki not working | 1,191,600 | <p>I'm trying to follow this tutorial from Cython: <a href="http://docs.cython.org/docs/tutorial.html#the-basics-of-cython" rel="nofollow">http://docs.cython.org/docs/tutorial.html#the-basics-of-cython</a> and I'm having a problem. </p>
<p>The files are very simple. I have a helloworld.pyx:</p>
<pre><code>print "Hello World"
</code></pre>
<p>and a setup.py:</p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("helloworld", ["helloworld.pyx"])]
)
</code></pre>
<p>and I compile it with the standard command:</p>
<pre><code>python setup.py build_ext --inplace
</code></pre>
<p>I got the following error:</p>
<pre><code>running build
running build_ext
building 'helloworld' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c helloworld.c -o build/temp.linux-x86_64-2.6/helloworld.o
helloworld.c:4:20: error: Python.h: No such file or directory
helloworld.c:5:26: error: structmember.h: No such file or directory
helloworld.c:34: error: expected specifier-qualifier-list before âPyObjectâ
helloworld.c:121: error: expected specifier-qualifier-list before âPyObjectâ
helloworld.c:139: error: expected â)â before â*â token
helloworld.c:140: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsLongLongâ
helloworld.c:141: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsUnsignedLongLongâ
helloworld.c:142: error: expected â)â before â*â token
helloworld.c:147: error: expected â)â before â*â token
helloworld.c:148: error: expected â)â before â*â token
helloworld.c:149: error: expected â)â before â*â token
helloworld.c:150: error: expected â)â before â*â token
helloworld.c:151: error: expected â)â before â*â token
helloworld.c:152: error: expected â)â before â*â token
helloworld.c:153: error: expected â)â before â*â token
helloworld.c:154: error: expected â)â before â*â token
helloworld.c:155: error: expected â)â before â*â token
helloworld.c:156: error: expected â)â before â*â token
helloworld.c:157: error: expected â)â before â*â token
helloworld.c:172: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:173: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:174: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:181: error: expected â)â before â*â token
helloworld.c:198: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:200: error: array type has incomplete element type
helloworld.c:221: error: â__pyx_kp_1â undeclared here (not in a function)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:221: warning: excess elements in struct initializer
helloworld.c:221: warning: (near initialization for â__pyx_string_tab[0]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:222: warning: excess elements in struct initializer
helloworld.c:222: warning: (near initialization for â__pyx_string_tab[1]â)
helloworld.c:237: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before âinithelloworldâ
helloworld.c:238: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before âinithelloworldâ
helloworld.c:305: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â*â token
helloworld.c:313: error: expected â)â before â*â token
helloworld.c:379:21: error: compile.h: No such file or directory
helloworld.c:380:25: error: frameobject.h: No such file or directory
helloworld.c:381:23: error: traceback.h: No such file or directory
helloworld.c: In function â__Pyx_AddTracebackâ:
helloworld.c:384: error: âPyObjectâ undeclared (first use in this function)
helloworld.c:384: error: (Each undeclared identifier is reported only once
helloworld.c:384: error: for each function it appears in.)
helloworld.c:384: error: âpy_srcfileâ undeclared (first use in this function)
helloworld.c:385: error: âpy_funcnameâ undeclared (first use in this function)
helloworld.c:386: error: âpy_globalsâ undeclared (first use in this function)
helloworld.c:387: error: âempty_stringâ undeclared (first use in this function)
helloworld.c:388: error: âPyCodeObjectâ undeclared (first use in this function)
helloworld.c:388: error: âpy_codeâ undeclared (first use in this function)
helloworld.c:389: error: âPyFrameObjectâ undeclared (first use in this function)
helloworld.c:389: error: âpy_frameâ undeclared (first use in this function)
helloworld.c:392: warning: implicit declaration of function âPyString_FromStringâ
helloworld.c:399: warning: implicit declaration of function âPyString_FromFormatâ
helloworld.c:412: warning: implicit declaration of function âPyModule_GetDictâ
helloworld.c:412: error: â__pyx_mâ undeclared (first use in this function)
helloworld.c:415: warning: implicit declaration of function âPyString_FromStringAndSizeâ
helloworld.c:420: warning: implicit declaration of function âPyCode_Newâ
helloworld.c:429: error: â__pyx_empty_tupleâ undeclared (first use in this function)
helloworld.c:440: warning: implicit declaration of function âPyFrame_Newâ
helloworld.c:441: warning: implicit declaration of function âPyThreadState_GETâ
helloworld.c:448: warning: implicit declaration of function âPyTraceBack_Hereâ
helloworld.c:450: warning: implicit declaration of function âPy_XDECREFâ
helloworld.c: In function â__Pyx_InitStringsâ:
helloworld.c:458: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:460: error: â__Pyx_StringTabEntryâ has no member named âis_unicodeâ
helloworld.c:460: error: â__Pyx_StringTabEntryâ has no member named âis_identifierâ
helloworld.c:461: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:461: warning: implicit declaration of function âPyUnicode_DecodeUTF8â
helloworld.c:461: error: â__Pyx_StringTabEntryâ has no member named âsâ
helloworld.c:461: error: â__Pyx_StringTabEntryâ has no member named ânâ
helloworld.c:461: error: âNULLâ undeclared (first use in this function)
helloworld.c:462: error: â__Pyx_StringTabEntryâ has no member named âinternâ
helloworld.c:463: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:463: warning: implicit declaration of function âPyString_InternFromStringâ
helloworld.c:463: error: â__Pyx_StringTabEntryâ has no member named âsâ
helloworld.c:465: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c:465: error: â__Pyx_StringTabEntryâ has no member named âsâ
helloworld.c:465: error: â__Pyx_StringTabEntryâ has no member named ânâ
helloworld.c:476: error: â__Pyx_StringTabEntryâ has no member named âpâ
helloworld.c: At top level:
helloworld.c:485: error: expected â)â before â*â token
helloworld.c:494: error: expected â)â before â*â token
helloworld.c:500: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsLongLongâ
helloworld.c:516: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â__pyx_PyInt_AsUnsignedLongLongâ
helloworld.c:538: error: expected â)â before â*â token
helloworld.c:553: error: expected â)â before â*â token
helloworld.c:568: error: expected â)â before â*â token
helloworld.c:583: error: expected â)â before â*â token
helloworld.c:598: error: expected â)â before â*â token
helloworld.c:613: error: expected â)â before â*â token
helloworld.c:628: error: expected â)â before â*â token
helloworld.c:643: error: expected â)â before â*â token
helloworld.c:658: error: expected â)â before â*â token
helloworld.c:673: error: expected â)â before â*â token
helloworld.c:688: error: expected â)â before â*â token
error: command 'gcc' failed with exit status 1
</code></pre>
<p>I have python and cython installed from Ubuntu 9.04 repositories. I can't figure why the compiler can't find Python.h.</p>
<p>I tried doing:</p>
<pre><code>cython helloworld.pyx
</code></pre>
<p>and then compiling the result manually with gcc:</p>
<pre><code>gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.5 -o helloworld.so helloworld.c
</code></pre>
<p>and got the same exact error message.</p>
<p>Any clues?</p>
| 2 | 2009-07-28T02:06:04Z | 1,192,043 | <p>Looks like you're missing some package like <code>python_dev</code> or the like -- Debian and derivatives (including Ubuntu) have long preferred to isolate everything that could possibly be of "developer"'s use from the parts of a package that are for "everybody"... a philosophical stance I could debate against (and <em>have</em> debated against, without much practical success, in mahy fora), but one that, sadly, can't just be ignored:-(</p>
| 4 | 2009-07-28T05:17:10Z | [
"c++",
"python",
"cython"
] |
Hierarchical Bayes for R or Python | 1,191,689 | <p>Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is <code>bayesm</code>, which is really a companion to a book (<em>Bayesian Statistics and Marketing</em>, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language? </p>
| 11 | 2009-07-28T02:43:03Z | 1,191,708 | <p>There's OpenBUGS and R helper packages. Check out Gelman's site for his book, which has most of the relevant links:</p>
<ul>
<li><a href="http://www.stat.columbia.edu/~gelman/software/">http://www.stat.columbia.edu/~gelman/software/</a></li>
<li><a href="http://www.stat.columbia.edu/~gelman/bugsR/software.pdf">Example of computation in R and Bugs</a></li>
</ul>
<p>On the Python side, I only know of PyMC:</p>
<ul>
<li><a href="http://code.google.com/p/pymc/">http://code.google.com/p/pymc/</a></li>
<li><a href="http://pymc.googlecode.com/svn/doc/tutorial.html">An example statistical model</a></li>
</ul>
<p>EDIT: Added a link to the appropriate appendix from Gelman's book, available online, for an example using R and BUGS. </p>
| 13 | 2009-07-28T02:55:08Z | [
"python",
"statistics"
] |
Hierarchical Bayes for R or Python | 1,191,689 | <p>Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is <code>bayesm</code>, which is really a companion to a book (<em>Bayesian Statistics and Marketing</em>, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language? </p>
| 11 | 2009-07-28T02:43:03Z | 1,192,044 | <p>Here are four books on hierarchical modeling and bayesian analysis written with R code throughout the books.</p>
<p>Hierarchical Modeling and Analysis for Spatial Data (Monographs on Statistics and Applied Probability) (Hardcover)
<a href="http://rads.stackoverflow.com/amzn/click/158488410X">http://www.amazon.com/gp/product/158488410X</a></p>
<p>Data Analysis Using Regression and Multilevel/Hierarchical Models (Paperback)
<a href="http://rads.stackoverflow.com/amzn/click/052168689X">http://www.amazon.com/Analysis-Regression-Multilevel-Hierarchical-Models/dp/052168689X/ref=pd_sim_b_1</a></p>
<p>Bayesian Computation with R (Use R) (Paperback)
<a href="http://rads.stackoverflow.com/amzn/click/0387922970">http://www.amazon.com/Bayesian-Computation-R-Use/dp/0387922970/ref=pd_bxgy_b_img_c</a></p>
<p>Hierarchical Modelling for the Environmental Sciences: Statistical Methods and Applications (Oxford Biology) (Paperback) (I'm assuming this one has R code as both authors use R extensively)</p>
<p>I know some python books dabble in multivariate analysis (Collective Intelligence, for example) but I haven't seen any that really delve into bayesian or hierarchical modeling.</p>
| 8 | 2009-07-28T05:17:52Z | [
"python",
"statistics"
] |
Hierarchical Bayes for R or Python | 1,191,689 | <p>Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is <code>bayesm</code>, which is really a companion to a book (<em>Bayesian Statistics and Marketing</em>, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language? </p>
| 11 | 2009-07-28T02:43:03Z | 1,196,932 | <p>There are a few hierarchical models in <a href="http://mcmcpack.wustl.edu" rel="nofollow">MCMCpack</a> for R, which to my knowledge is the fastest sampler for many common model types. (I wrote the [hierarchical item response][2] model in it.)</p>
<p>[RJAGS][3] does what its name sounds like. Code up a jags-flavored .bug model, provide data in R, and call Jags from R.</p>
| 3 | 2009-07-28T21:45:12Z | [
"python",
"statistics"
] |
Hierarchical Bayes for R or Python | 1,191,689 | <p>Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is <code>bayesm</code>, which is really a companion to a book (<em>Bayesian Statistics and Marketing</em>, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language? </p>
| 11 | 2009-07-28T02:43:03Z | 1,197,766 | <p>The lme4 package, which estimates hierarchical models using frequentist methods, has a function called mcmcsamp that allows you to sample from the posterior distribution of the model using MCMC. This currently works only for linear models, quite unfortunately.</p>
| 0 | 2009-07-29T02:19:51Z | [
"python",
"statistics"
] |
Hierarchical Bayes for R or Python | 1,191,689 | <p>Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is <code>bayesm</code>, which is really a companion to a book (<em>Bayesian Statistics and Marketing</em>, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language? </p>
| 11 | 2009-07-28T02:43:03Z | 1,830,888 | <p>in python, try PyMC. There is an example of multilevel modeling with it here: <a href="http://groups.google.com/group/pymc/browse%5Fthread/thread/c6ce37a80edf7f85/1bfd9138c8db891d" rel="nofollow">http://groups.google.com/group/pymc/browse%5Fthread/thread/c6ce37a80edf7f85/1bfd9138c8db891d</a></p>
| 2 | 2009-12-02T05:45:59Z | [
"python",
"statistics"
] |
Hierarchical Bayes for R or Python | 1,191,689 | <p>Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is <code>bayesm</code>, which is really a companion to a book (<em>Bayesian Statistics and Marketing</em>, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language? </p>
| 11 | 2009-07-28T02:43:03Z | 1,832,314 | <p>I apply hierarchical Bayes models in R in combination with JAGS (Linux) or sometimes WinBUGS (Windows, or Wine). Check out the book of Andrew Gelman, as referred to above.</p>
| 2 | 2009-12-02T11:22:36Z | [
"python",
"statistics"
] |
Is it possible to install SSL on Google app engine for iPhone application? | 1,191,936 | <p>I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urgent.</p>
| 1 | 2009-07-28T04:27:59Z | 1,193,063 | <p>See the App Engine Python documentation on setting up <a href="http://code.google.com/appengine/docs/python/config/appconfig.html#Secure%5FURLs" rel="nofollow">secure URLs</a>. Note that this will only work when accessed via your appspot.com domain - it's not possible to have SSL on a custom domain through App Engine, currently.</p>
| 5 | 2009-07-28T09:49:23Z | [
"python",
"google-app-engine",
"ssl"
] |
Is it possible to install SSL on Google app engine for iPhone application? | 1,191,936 | <p>I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urgent.</p>
| 1 | 2009-07-28T04:27:59Z | 2,602,904 | <p>Nick Johnson has already provided a link and mentioned that this functionality is not currently available on your domain (only on apps running on Google's hotspot domain).</p>
<p>Obviously, most developers need their apps to run on their own domains, so this is a <a href="http://code.google.com/p/googleappengine/issues/detail?id=792&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component" rel="nofollow">very highly requested feature</a>. Fortunately, Google has recently added this feature to <a href="http://code.google.com/intl/ko-KR/appengine/docs/roadmap.html" rel="nofollow">their GAE roadmap</a> indicating that it will be available soon. Unfortunately, we don't know what 'soon' means.</p>
| 0 | 2010-04-08T19:44:33Z | [
"python",
"google-app-engine",
"ssl"
] |
SQLAlchemy: Operating on results | 1,192,269 | <p>I'm trying to do something relatively simple, spit out the column names and respective column values, and possibly filter out some columns so they aren't shown.</p>
<p>This is what I attempted ( after the initial connection of course ):</p>
<pre><code>metadata = MetaData(engine)
users_table = Table('fusion_users', metadata, autoload=True)
s = users_table.select(users_table.c.user_name == username)
results = s.execute()
if results.rowcount != 1:
return 'Sorry, user not found.'
else:
for result in results:
for x, y in result.items()
print x, y
</code></pre>
<p>I looked at the API on SQLAlchemy ( v.5 ) but was rather confused. my 'result' in 'results' is a RowProxy, yet I don't think it's returning the right object for the .items() invocation. </p>
<p>Let's say my table structure is so:</p>
<pre><code>user_id user_name user_password user_country
0 john a9fu93f39uf usa
</code></pre>
<p>i want to filter and specify the column names to show ( i dont want to show the user_password obviously ) - how can I accomplish this?</p>
| 5 | 2009-07-28T06:45:37Z | 1,192,439 | <p>You can use <code>results</code> instantly as an iterator.</p>
<pre><code>results = s.execute()
for row in results:
print row
</code></pre>
<p>Selecting specific columns is done the following way:</p>
<pre><code>from sqlalchemy.sql import select
s = select([users_table.c.user_name, users_table.c.user_country], users_table.c.user_name == username)
for user_name, user_country in s.execute():
print user_name, user_country
</code></pre>
<p>To print the column names additional to the values the way you have done it in your question should be the best because RowProxy is really nothing more than a ordered dictionary.</p>
<p>IMO the API documentation for SqlAlchemy is not really helpfull to learn how to use it. I would suggest you to read the <a href="http://www.sqlalchemy.org/docs/05/sqlexpression.html">SQL Expression Language Tutorial</a>. It contains the most vital information about basic querying with SqlAlchemy.</p>
| 8 | 2009-07-28T07:38:52Z | [
"python",
"sql",
"sqlalchemy"
] |
SQLAlchemy: Operating on results | 1,192,269 | <p>I'm trying to do something relatively simple, spit out the column names and respective column values, and possibly filter out some columns so they aren't shown.</p>
<p>This is what I attempted ( after the initial connection of course ):</p>
<pre><code>metadata = MetaData(engine)
users_table = Table('fusion_users', metadata, autoload=True)
s = users_table.select(users_table.c.user_name == username)
results = s.execute()
if results.rowcount != 1:
return 'Sorry, user not found.'
else:
for result in results:
for x, y in result.items()
print x, y
</code></pre>
<p>I looked at the API on SQLAlchemy ( v.5 ) but was rather confused. my 'result' in 'results' is a RowProxy, yet I don't think it's returning the right object for the .items() invocation. </p>
<p>Let's say my table structure is so:</p>
<pre><code>user_id user_name user_password user_country
0 john a9fu93f39uf usa
</code></pre>
<p>i want to filter and specify the column names to show ( i dont want to show the user_password obviously ) - how can I accomplish this?</p>
| 5 | 2009-07-28T06:45:37Z | 1,194,760 | <p>A SQLAlchemy <a href="http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/connections.html#sqlalchemy.engine.base.RowProxy">RowProxy</a> object has dict-like methods -- <code>.items()</code> to get all name/value pairs, <code>.keys()</code> to get just the names (e.g. to display them as a header line, then use <code>.values()</code> for the corresponding values or use each key to index into the <code>RowProxy</code> object, etc, etc -- so it being a "smart object" rather than a plain dict shouldn't inconvenience you unduly.</p>
| 8 | 2009-07-28T15:05:24Z | [
"python",
"sql",
"sqlalchemy"
] |
What's a good way to replace international characters with their base Latin counterparts using Python? | 1,192,367 | <p>Say I have the string <code>"blöt träbåt"</code> which has a few <code>a</code> and <code>o</code> with umlaut and ring above. I want it to become <code>"blot trabat"</code> as simply as possibly. I've done some digging and found the following method:</p>
<pre><code>import unicodedata
unicode_string = unicodedata.normalize('NFKD', unicode(string))
</code></pre>
<p>This will give me the string in unicode format with the international characters split into base letter and combining character (<code>\u0308</code> for umlauts.) Now to get this back to an ASCII string I could do <code>ascii_string = unicode_string.encode('ASCII', 'ignore')</code> and it'll just ignore the combining characters, resulting in the string <code>"blot trabat"</code>.</p>
<p>The question here is: is there a better way to do this? It feels like a roundabout way, and I was thinking there might be something I don't know about. I could of course wrap it up in a helper function, but I'd rather check if this doesn't exist in Python already.</p>
| 5 | 2009-07-28T07:21:11Z | 1,192,471 | <p>It would be better if you created an explicit table, and then used the unicode.translate method. The advantage would be that transliteration is more precise, e.g. transliterating "ö" to "oe" and "Ã" to "ss", as should be done in German.</p>
<p>There are several transliteration packages on PyPI: <a href="http://pypi.python.org/pypi/translitcodec/0.1">translitcodec</a>, <a href="http://pypi.python.org/pypi/Unidecode/0.04.1">Unidecode</a>, and <a href="http://pypi.python.org/pypi/trans/1.0">trans</a>.</p>
| 7 | 2009-07-28T07:45:57Z | [
"python",
"string",
"internationalization"
] |
Making tabulation look different than just whitespace | 1,192,480 | <p>How to make tabulation look different than whitespace in vim (highlighted for example).</p>
<p>That would be useful for code in Python.</p>
| 9 | 2009-07-28T07:47:21Z | 1,192,495 | <p>Use the <code>list</code> and <code>listchars</code> options, something like this:</p>
<pre><code>:set list
:set listchars=tab:>-
</code></pre>
| 5 | 2009-07-28T07:50:15Z | [
"python",
"vim"
] |
Making tabulation look different than just whitespace | 1,192,480 | <p>How to make tabulation look different than whitespace in vim (highlighted for example).</p>
<p>That would be useful for code in Python.</p>
| 9 | 2009-07-28T07:47:21Z | 1,192,516 | <p>I use something like this:</p>
<pre><code>set list listchars=tab:»·,trail:·,precedes:â¦,extends:â¦,nbsp:â
</code></pre>
<p>Requires Vim7 and I'm not sure how well this is going to show up in a browser, because it uses some funky Unicode characters. It's good to use some oddball characters so that you can distinguish a tab from something you may have typed yourself.</p>
<p>In addition to showing tabs, showing spaces at the end of lines is useful so you know to remove them (they are annoying).</p>
| 16 | 2009-07-28T07:55:37Z | [
"python",
"vim"
] |
Making tabulation look different than just whitespace | 1,192,480 | <p>How to make tabulation look different than whitespace in vim (highlighted for example).</p>
<p>That would be useful for code in Python.</p>
| 9 | 2009-07-28T07:47:21Z | 1,192,811 | <p>If you do the following:</p>
<pre><code>:set list
</code></pre>
<p>then all TAB characters will appear as <code>^I</code> and all trailing spaces will appear as <code>$</code>.</p>
<p>Using <code>listchars</code>, you can control what characters to use for any whitespace. So,</p>
<pre><code>:set listchars=tab:...
</code></pre>
<p>in conjunction with <code>:set list</code> makes TABs visible as <code>...</code>.</p>
| 3 | 2009-07-28T08:55:03Z | [
"python",
"vim"
] |
Making tabulation look different than just whitespace | 1,192,480 | <p>How to make tabulation look different than whitespace in vim (highlighted for example).</p>
<p>That would be useful for code in Python.</p>
| 9 | 2009-07-28T07:47:21Z | 1,195,462 | <p>Also, when cutting and pasting text around, it's useful to disable the display of tabs and spaces. You can do that with</p>
<pre><code>:set list!
</code></pre>
<p>And you enable it again with repeating the command.</p>
| 2 | 2009-07-28T17:09:45Z | [
"python",
"vim"
] |
Making tabulation look different than just whitespace | 1,192,480 | <p>How to make tabulation look different than whitespace in vim (highlighted for example).</p>
<p>That would be useful for code in Python.</p>
| 9 | 2009-07-28T07:47:21Z | 1,195,534 | <p>Many others have mentioned the 'listchars' and 'list' options, but just to add another interesting alternative:</p>
<pre><code>if &expandtab == 0
execute 'syn match MixedIndentationError display "^\([\t]*\)\@<=\( \{'.&ts.'}\)\+"'
else
execute 'syn match MixedIndentationError display "^\(\( \{' . &ts . '}\)*\)\@<=\t\+"'
endif
hi link MixedIndentationError Error
</code></pre>
<p>This will look at the current setting of 'expandtab' (i.e. whether you've got hard tabs or spaces pretending to be tabs) and will highlight anything that would <em>look</em> like correct indentation but be of the wrong form. These are designed to work by looking at the tab stops, so tabs used for indentation followed by spaces used for simple alignment (not a multiple of 'tabstop') won't be highlighted as erroneous.</p>
<p>Simpler options are available: if you just want to highlight any tabs in the wrong file in bright red (or whatever your Error colour is), you could do:</p>
<pre><code>syn match TabShouldNotBeThereError display "\t"
hi link TabShouldNotBeThereError Error
</code></pre>
<p>or if you want spaces at the start of a line to be considered an error, you could do:</p>
<pre><code>syn match SpacesUsedForIndentationError display "^ +"
hi link SpacesUsedForIndentationError Error
</code></pre>
<p>Just a few more thoughts to add to the mix... more information here:</p>
<pre><code>:help 'expandtab'
:help 'tabstop'
:help 'listchars'
:help 'list'
:help :exe
:help let-option
:help :hi-link
:help :syn-match
:help :syn-display
</code></pre>
| 7 | 2009-07-28T17:26:06Z | [
"python",
"vim"
] |
Making tabulation look different than just whitespace | 1,192,480 | <p>How to make tabulation look different than whitespace in vim (highlighted for example).</p>
<p>That would be useful for code in Python.</p>
| 9 | 2009-07-28T07:47:21Z | 1,214,504 | <p><em>glenn jackman</em> asked how to enter the characters (I'm assuming he means characters like "»").</p>
<p><em>Brian Carper</em> suggests a method using the character's Unicode index number. Since many of these distinctive-looking characters are digraphs [ :help digraphs ], you can also use the CNTL-k shortcut, which is generally easier to remember.</p>
<p>So, for example, you can generate the "»" in Insert mode by typing CNTL-k and the ">" character twice.</p>
| 2 | 2009-07-31T19:46:03Z | [
"python",
"vim"
] |
python stdout flush and tee | 1,192,870 | <p>The following code ends with broken pipe when piped into tee, but behave correctly when not piped :</p>
<pre><code>#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
sys.stdout.flush()
return
print s
if __name__ == "__main__":
testfun()
sys.exit()
</code></pre>
<p>Expected output :</p>
<pre><code>./bug.py
Ctrl-C pressed
</code></pre>
<p>What is observed when piped into tee is either a broken pipe or no output at all, ie nothing on tee stdout, and nothing in bug.log :</p>
<pre><code>./bug.py | tee bug.log
Traceback (most recent call last):
File "./bug.py", line 14, in <module>
sys.stdout.flush()
IOError: [Errno 32] Broken pipe
</code></pre>
<p>What can be the reason for this ?</p>
| 2 | 2009-07-28T09:07:35Z | 1,192,880 | <p>When you hit Ctrl-C, the shell will terminate <em>both</em> processes (<code>python</code> and <code>tee</code>) and tear down the pipe connecting them. </p>
<p>So when you handle the Ctrl-C in your <code>python</code> process and flush, it'll find that <code>tee</code> has been terminated and the pipe is no more. Hence the error message.</p>
<p>(As an aside, would you expect anything in the log ? I don't see your process outputting anything other than the flush on exit)</p>
| 2 | 2009-07-28T09:10:07Z | [
"python",
"tee"
] |
python stdout flush and tee | 1,192,870 | <p>The following code ends with broken pipe when piped into tee, but behave correctly when not piped :</p>
<pre><code>#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
sys.stdout.flush()
return
print s
if __name__ == "__main__":
testfun()
sys.exit()
</code></pre>
<p>Expected output :</p>
<pre><code>./bug.py
Ctrl-C pressed
</code></pre>
<p>What is observed when piped into tee is either a broken pipe or no output at all, ie nothing on tee stdout, and nothing in bug.log :</p>
<pre><code>./bug.py | tee bug.log
Traceback (most recent call last):
File "./bug.py", line 14, in <module>
sys.stdout.flush()
IOError: [Errno 32] Broken pipe
</code></pre>
<p>What can be the reason for this ?</p>
| 2 | 2009-07-28T09:07:35Z | 1,192,955 | <p>This is not a python problem but a shell problem, as pointed by Brian, hitting Ctrl-C will terminate both process. Workaround is to use named pipes :</p>
<pre><code>mknod mypipe p
cat mypipe | tee somefile.log &
./bug.py > mypipe
</code></pre>
| 4 | 2009-07-28T09:25:35Z | [
"python",
"tee"
] |
python stdout flush and tee | 1,192,870 | <p>The following code ends with broken pipe when piped into tee, but behave correctly when not piped :</p>
<pre><code>#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
sys.stdout.flush()
return
print s
if __name__ == "__main__":
testfun()
sys.exit()
</code></pre>
<p>Expected output :</p>
<pre><code>./bug.py
Ctrl-C pressed
</code></pre>
<p>What is observed when piped into tee is either a broken pipe or no output at all, ie nothing on tee stdout, and nothing in bug.log :</p>
<pre><code>./bug.py | tee bug.log
Traceback (most recent call last):
File "./bug.py", line 14, in <module>
sys.stdout.flush()
IOError: [Errno 32] Broken pipe
</code></pre>
<p>What can be the reason for this ?</p>
| 2 | 2009-07-28T09:07:35Z | 7,251,469 | <p>Nope, hitting Ctrl-C does NOT terminate both processes. It terminates the tee process only,
the end of the tee process close the pipe between your script and tee, and hence your script dies with the broken pipe message.</p>
<p>To fix that, tee has an option to pass the Ctrl-C to its previous process in the pipe: -i</p>
<p>try: man tee</p>
<pre><code>./bug.py
^CCtrl-C pressed
./bug.py | tee log
^CTraceback (most recent call last):
File "./bug.py", line 14, in <module>
testfun()
File "./bug.py", line 9, in testfun
sys.stdout.flush()
IOError: [Errno 32] Broken pipe
./bug.py | tee -i log
^CCtrl-C pressed
</code></pre>
| 8 | 2011-08-31T00:52:17Z | [
"python",
"tee"
] |
How to find the longest word with python? | 1,192,881 | <p>How can I use python to find the longest word from a set of words?
I can find the first word like this: </p>
<pre><code>'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
'a'
rfind is another subset
'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]
'a aa aaa'
</code></pre>
| 1 | 2009-07-28T09:10:08Z | 1,192,898 | <p>If I understand your question correctly:</p>
<pre><code>>>> s = "a aa aaa aa"
>>> max(s.split(), key=len)
'aaa'
</code></pre>
<p><code>split()</code> splits the string into words (seperated by whitespace); <code>max()</code> finds the largest element using the builtin <code>len()</code> function, i.e. the string length, as the key to find out what "largest" means.</p>
| 31 | 2009-07-28T09:15:30Z | [
"python",
"word",
"max"
] |
How to find the longest word with python? | 1,192,881 | <p>How can I use python to find the longest word from a set of words?
I can find the first word like this: </p>
<pre><code>'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
'a'
rfind is another subset
'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]
'a aa aaa'
</code></pre>
| 1 | 2009-07-28T09:10:08Z | 1,193,087 | <p>Here is one from the category "How difficult can you make it", also violating the requirement that there should be no own class involved:</p>
<pre><code>class C(object): pass
o = C()
o.i = 0
ss = 'a aa aaa aa'.split()
([setattr(o,'i',x) for x in range(len(ss)) if len(ss[x]) > len(ss[o.i])], ss[o.i])[1]
</code></pre>
<p>The interesting bit is that you use an object member to maintain state while the list is being computed in the comprehension, eventually discarding the list and only using the side-effect.</p>
<p>But please do use one of the <strong>max()</strong> solutions above :-) .</p>
| 2 | 2009-07-28T09:53:49Z | [
"python",
"word",
"max"
] |
Can someone explain this Python re.sub() unexpected output? | 1,192,918 | <p>I am using Python 2.6 and am getting [what I think is] unexpected output from re.sub()</p>
<pre><code>>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'
</code></pre>
<p>If this output is what is expected, what is the logic behind it?</p>
| 3 | 2009-07-28T09:19:45Z | 1,192,965 | <p>Yes, the fourth parameter is count, not flags. You're telling it to apply the pattern twice (re.IGNORECASE = 2).</p>
| 7 | 2009-07-28T09:28:36Z | [
"python",
"regex"
] |
Can someone explain this Python re.sub() unexpected output? | 1,192,918 | <p>I am using Python 2.6 and am getting [what I think is] unexpected output from re.sub()</p>
<pre><code>>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'
</code></pre>
<p>If this output is what is expected, what is the logic behind it?</p>
| 3 | 2009-07-28T09:19:45Z | 1,192,991 | <p>To pass flags you can use re.compile</p>
<pre><code>expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
</code></pre>
| 4 | 2009-07-28T09:34:14Z | [
"python",
"regex"
] |
Can someone explain this Python re.sub() unexpected output? | 1,192,918 | <p>I am using Python 2.6 and am getting [what I think is] unexpected output from re.sub()</p>
<pre><code>>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'
</code></pre>
<p>If this output is what is expected, what is the logic behind it?</p>
| 3 | 2009-07-28T09:19:45Z | 27,368,978 | <p>In case you've upgraded since asking this question. If you are using Python 2.7+, you don't need to use <code>re.compile</code>. You can call <code>sub</code> and specify <code>flags</code> with a named argument.</p>
<pre><code>>>> import re
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', flags=re.IGNORECASE)
'th- c-t s-t -n th- m-t'
</code></pre>
<p>Reference: <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">https://docs.python.org/2/library/re.html#re.sub</a></p>
| 0 | 2014-12-08T23:33:05Z | [
"python",
"regex"
] |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | <p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p>
<p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p>
<pre><code>myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
</code></pre>
<p>Any other suggestions?</p>
<p>Thanks</p>
| 22 | 2009-07-28T09:31:08Z | 1,192,992 | <p>Thats probably the best way to be honest: you can use <code>glob</code> to go a certain number of layers down, but if you need it to be recursive you have to <code>walk</code>.</p>
| 2 | 2009-07-28T09:34:41Z | [
"python"
] |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | <p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p>
<p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p>
<pre><code>myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
</code></pre>
<p>Any other suggestions?</p>
<p>Thanks</p>
| 22 | 2009-07-28T09:31:08Z | 1,193,070 | <p>What you are doing is perfectly right and I think should be done that way, BUT just for the sake of alternative, here is an attempt</p>
<pre><code>import os
def getFiles(myFolder):
old = os.getcwd()
os.chdir(myFolder)
fileSet = set()
for root, dirs, files in os.walk(""):
for f in files:
fileSet.add(os.path.join(root, f))
os.chdir(old)
return fileSet
</code></pre>
| 1 | 2009-07-28T09:51:02Z | [
"python"
] |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | <p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p>
<p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p>
<pre><code>myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
</code></pre>
<p>Any other suggestions?</p>
<p>Thanks</p>
| 22 | 2009-07-28T09:31:08Z | 1,193,105 | <p>I think os.walk is the right choice here.<br />
maybe <code>root.replace(myFolder, "")</code> should change to <code>root.replace(myFolder, "", 1)</code> to avoid potential sth. you know.<br />
If you already get the files and (sub)folders, <a href="http://docs.python.org/library/os.path.html#os.path.commonprefix" rel="nofollow">os.path.commonprefix</a> worth a look too.</p>
| 3 | 2009-07-28T09:57:41Z | [
"python"
] |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | <p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p>
<p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p>
<pre><code>myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
</code></pre>
<p>Any other suggestions?</p>
<p>Thanks</p>
| 22 | 2009-07-28T09:31:08Z | 1,193,171 | <pre><code>myFolder = "myfolder"
fileSet = set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add( os.path.join( root[len(myFolder):], fileName ))
</code></pre>
| 8 | 2009-07-28T10:10:39Z | [
"python"
] |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | <p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p>
<p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p>
<pre><code>myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
</code></pre>
<p>Any other suggestions?</p>
<p>Thanks</p>
| 22 | 2009-07-28T09:31:08Z | 1,208,379 | <p>You can also use <a href="http://docs.python.org/library/os.html#os.listdir" rel="nofollow">os.listdir()</a> if you are just searching for an alternative to your solution.</p>
<p>But basically the logic will stay the same: iterate over the files - if directory, iterate through the subdirectory. </p>
| 1 | 2009-07-30T18:19:54Z | [
"python"
] |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | <p>I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. </p>
<p>For my current approach I am using <code>os.walk()</code>. It is working but it does not seem "pythonic" to me:</p>
<pre><code>myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
</code></pre>
<p>Any other suggestions?</p>
<p>Thanks</p>
| 22 | 2009-07-28T09:31:08Z | 13,617,120 | <p>Use <a href="http://docs.python.org/2/library/os.path.html#os.path.relpath"><code>os.path.relpath()</code></a>. This is exactly its intended use.</p>
<pre><code>import os
rootDir = "myfolder"
fileSet = set()
for dir_, _, files in os.walk(rootDir):
for fileName in files:
relDir = os.path.relpath(dir_, rootDir)
relFile = os.path.join(relDir, fileName)
fileSet.add(relFile)
</code></pre>
<p>Note that <code>os.path.relpath()</code> was added in Python 2.6 and is supported on Windows and Unix.</p>
| 37 | 2012-11-29T01:00:36Z | [
"python"
] |
User in Form-Class | 1,193,084 | <p>I have a form like this:</p>
<pre><code>class MyForm(forms.Form):
[...]
</code></pre>
<p>which is rendered in my view:</p>
<pre><code>if request.method == 'GET':
form = MyForm(request.GET)
</code></pre>
<p>Now, i want to add a form field which contains a set of values in a select-field, and the queryset must be filtered by the currently logged in user. So I changed the method signature so that it contains the request-object:</p>
<pre><code>class MyForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.myfield = forms.ChoiceField([('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)])
</code></pre>
<p>but all I get after rendering the form is an object-reference as string instead of the select-widget. I seems that a form field, once declared, can not be modified.</p>
<p>Any ideas?</p>
| 0 | 2009-07-28T09:53:46Z | 1,193,205 | <p>Replace your last line of code with this:</p>
<pre><code>self.fields['myfield'].choices = [('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)]
</code></pre>
| 2 | 2009-07-28T10:20:54Z | [
"python",
"django"
] |
User in Form-Class | 1,193,084 | <p>I have a form like this:</p>
<pre><code>class MyForm(forms.Form):
[...]
</code></pre>
<p>which is rendered in my view:</p>
<pre><code>if request.method == 'GET':
form = MyForm(request.GET)
</code></pre>
<p>Now, i want to add a form field which contains a set of values in a select-field, and the queryset must be filtered by the currently logged in user. So I changed the method signature so that it contains the request-object:</p>
<pre><code>class MyForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.myfield = forms.ChoiceField([('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)])
</code></pre>
<p>but all I get after rendering the form is an object-reference as string instead of the select-widget. I seems that a form field, once declared, can not be modified.</p>
<p>Any ideas?</p>
| 0 | 2009-07-28T09:53:46Z | 1,193,943 | <p>I think here's what you're after:</p>
<pre><code>class MyForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'] = forms.ModelChoiceField(MyModel.objects.filter(owners=user))
</code></pre>
<p>That's assuming that the <code>__unicode__</code> method of your <code>MyModel</code> returns <code>self.name</code>.
If this <em>isn't</em> the case, then you can subclass <code>ModelChoiceField</code> and override the <code>label_from_instance</code> method.</p>
| 0 | 2009-07-28T13:03:06Z | [
"python",
"django"
] |
What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python? | 1,193,583 | <p>The code below is outdated in Python 3.0 by being replaced by <code>subprocess.getstatusoutput()</code>. </p>
<pre><code>import commands
(ret, out) = commands.getstatusoutput('some command')
print ret
print out
</code></pre>
<p>The real question is what's the multiplatform alternative to this command from Python because the above code does fail ugly under Windows because getstatusoutput is supported only under Unix and Python does not tell you this, instead you get something like:</p>
<pre><code>>test.py
1
'{' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
| 7 | 2009-07-28T11:47:02Z | 1,193,824 | <p>I wouldn't really consider this <em>multiplatform</em>, but you can use <code>subprocess.Popen</code>:</p>
<pre><code>import subprocess
pipe = subprocess.Popen('dir', stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = pipe.stdout.readlines()
sts = pipe.wait()
print sts
print output
</code></pre>
<p><hr /></p>
<p>Here's a drop-in replacement for <code>getstatusoutput</code>:</p>
<pre><code>def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
"""This new implementation should work on all platforms."""
import subprocess
pipe = subprocess.Popen(cmd, shell=True, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = str.join("", pipe.stdout.readlines())
sts = pipe.wait()
if sts is None:
sts = 0
return sts, output
</code></pre>
<p>This snippet was proposed by the original poster. I made some changes since <code>getstatusoutput</code> duplicates <code>stderr</code> onto <code>stdout</code>. </p>
<p><hr /></p>
<p>The problem is that <code>dir</code> isn't really a multiplatform call but <a href="http://docs.python.org/3.1/library/subprocess.html#subprocess.Popen"><code>subprocess.Popen</code></a> allows you to execute shell commands on any platform. I would steer clear of using shell commands unless you absolutely need to. Investigate the contents of the <a href="http://docs.python.org/3.1/library/os.html"><code>os</code></a>, <a href="http://docs.python.org/3.1/library/os.path.html"><code>os.path</code></a>, and <a href="http://docs.python.org/3.1/library/shutil.html"><code>shutil</code></a> packages instead.</p>
<pre><code>import os
import os.path
for rel_name in os.listdir(os.curdir):
abs_name = os.path.join(os.curdir, rel_name)
if os.path.isdir(abs_name):
print('DIR: ' + rel_name)
elif os.path.isfile(abs_name):
print('FILE: ' + rel_name)
else:
print('UNK? ' + rel_name)
</code></pre>
| 7 | 2009-07-28T12:37:16Z | [
"python",
"redirect",
"process"
] |
What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python? | 1,193,583 | <p>The code below is outdated in Python 3.0 by being replaced by <code>subprocess.getstatusoutput()</code>. </p>
<pre><code>import commands
(ret, out) = commands.getstatusoutput('some command')
print ret
print out
</code></pre>
<p>The real question is what's the multiplatform alternative to this command from Python because the above code does fail ugly under Windows because getstatusoutput is supported only under Unix and Python does not tell you this, instead you get something like:</p>
<pre><code>>test.py
1
'{' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
| 7 | 2009-07-28T11:47:02Z | 1,197,469 | <p>getstatusoutput docs say it runs the command like so:</p>
<p>{ cmd } 2>&1</p>
<p>Which obviously doesn't work with cmd.exe (the 2>&1 works fine if you need it though).</p>
<p>You can use Popen as above, but also include the parameter 'stderr=subprocess.STDOUT' to get the same behaviour as getstatusoutput.</p>
<p>My tests on Windows had returncode set to None though, which is not ideal if you're counting on the return value.</p>
| 1 | 2009-07-29T00:24:43Z | [
"python",
"redirect",
"process"
] |
What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python? | 1,193,583 | <p>The code below is outdated in Python 3.0 by being replaced by <code>subprocess.getstatusoutput()</code>. </p>
<pre><code>import commands
(ret, out) = commands.getstatusoutput('some command')
print ret
print out
</code></pre>
<p>The real question is what's the multiplatform alternative to this command from Python because the above code does fail ugly under Windows because getstatusoutput is supported only under Unix and Python does not tell you this, instead you get something like:</p>
<pre><code>>test.py
1
'{' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
| 7 | 2009-07-28T11:47:02Z | 1,198,935 | <p>This would be the multiplatform implementation for getstatusoutput(): </p>
<pre><code>def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
"""This new implementation should work on all platforms."""
import subprocess
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = "".join(pipe.stdout.readlines())
sts = pipe.returncode
if sts is None: sts = 0
return sts, output
</code></pre>
| 6 | 2009-07-29T09:05:20Z | [
"python",
"redirect",
"process"
] |
Is there a standard pythonic way to treat physical units / quantities in python? | 1,193,890 | <p>Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code.</p>
| 17 | 2009-07-28T12:51:20Z | 1,193,902 | <p>The best solution is the <a href="http://home.scarlet.be/be052320/Unum.html">Unum</a> package. a de-facto standard, imho.</p>
| 9 | 2009-07-28T12:53:28Z | [
"python",
"physics",
"units-of-measurement"
] |
Is there a standard pythonic way to treat physical units / quantities in python? | 1,193,890 | <p>Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code.</p>
| 17 | 2009-07-28T12:51:20Z | 1,203,778 | <p>I've been looking at the <a href="http://code.enthought.com/projects/files/ETS31%5FAPI/enthought.units.html" rel="nofollow">Enthought Units module</a></p>
| 2 | 2009-07-30T00:14:02Z | [
"python",
"physics",
"units-of-measurement"
] |
Is there a standard pythonic way to treat physical units / quantities in python? | 1,193,890 | <p>Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code.</p>
| 17 | 2009-07-28T12:51:20Z | 1,204,146 | <p><a href="https://launchpad.net/python-quantities">quantities</a> seems to be gaining a lot of traction lately.</p>
| 9 | 2009-07-30T02:27:36Z | [
"python",
"physics",
"units-of-measurement"
] |
Is there a standard pythonic way to treat physical units / quantities in python? | 1,193,890 | <p>Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code.</p>
| 17 | 2009-07-28T12:51:20Z | 27,903,335 | <p>There is also <a href="http://pint.readthedocs.org/en/0.6/" rel="nofollow" title="pint">pint</a> which in his documentation has a list of other projects in their <a href="http://pint.readthedocs.org/en/0.6/faq.html" rel="nofollow">faq's</a>.</p>
| 0 | 2015-01-12T13:40:49Z | [
"python",
"physics",
"units-of-measurement"
] |
How to wait for a child that respawns itself with os.execv() on win32? | 1,194,078 | <p>I have some code that uses <a href="http://pypi.python.org/pypi/pip" rel="nofollow">pip</a> to bootstrap a Python envionment for out build process: this is a lovely way of ensuring we get proper isolation of the build requirements from the rest of the host system, and helping us get more consistent build results overall.</p>
<p>Anyway, the code I have that drives <code>pip.py</code> appears to have some problems on windows. The problem is that I'm spawning the <code>pip</code> process from my bootstrapping scripts using <code>subprocess.Popen()</code> and then waiting for the process to complete but this is happening too early due to the fact that <code>pip</code> uses <a href="http://docs.python.org/library/os.html#os.execv" rel="nofollow">execv</a> to relaunch itself under the new <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> it creates. When this happens my parent is seeing that the child has exited with an exitcode of 0 and it carries on on it's merry way.</p>
<p>So the question is simple: how can I cope with an <code>os.execv()</code> call from a child process on win32 in manner where i can ascertain the return code of the newly executed child process?</p>
| 0 | 2009-07-28T13:24:02Z | 1,429,702 | <p>I can't think of any smooth way to handle this. This may sound dirty, but perhaps you could work with dropping flag files onto the filesystem while your script is running, and wait for those files to be cleaned up?</p>
| 0 | 2009-09-15T21:25:21Z | [
"python",
"windows",
"pip",
"execv"
] |
Python memory footprint vs. heap size | 1,194,416 | <p>I'm having some memory issues while using a python script to issue a large <strong>solr</strong> query. I'm using the <strong>solrpy</strong> library to interface with the solr server. The query returns approximately 80,000 records. Immediately after issuing the query the python memory footprint as viewed through top balloons to ~190MB.</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 193m 189m 3272 S 0.0 11.2 0:11.31 python
...
</code></pre>
<p>At this point, the heap profile as viewed through heapy looks like this:</p>
<pre><code>Partition of a set of 163934 objects. Total size = 14157888 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 80472 49 7401384 52 7401384 52 unicode
1 44923 27 3315928 23 10717312 76 str
...
</code></pre>
<p>The unicode objects represent the unique identifiers of the records from the query. One thing to note is that the total heap size is only 14MB while python is occupying 190MB of physical memory. Once the variable storing the query results falls out of scope, the heap profile correctly reflects the garbage collection:</p>
<pre><code>Partition of a set of 83586 objects. Total size = 6437744 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 44928 54 3316108 52 3316108 52 str
</code></pre>
<p>However, the memory footprint remains unchanged:</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 195m 192m 3432 S 0.0 11.3 0:13.46 python
...
</code></pre>
<p>Why is there such a large disparity between python's physical memory footprint and the size of the python heap?</p>
| 9 | 2009-07-28T14:19:10Z | 1,194,548 | <p>Python allocates Unicode objects from the C heap. So when you allocate many of them (along with other malloc blocks), then release most of them except for the very last one, C malloc will not return any memory to the operating system, as the C heap will only shrink on the end (not in the middle). Releasing the last Unicode object will release the block at the end of the C heap, which then allows malloc to return it all to the system.</p>
<p>On top of these problems, Python also maintains a pool of freed unicode objects, for faster allocation. So when the last Unicode object is freed, it isn't returned to malloc right away, making all the other pages stuck.</p>
| 5 | 2009-07-28T14:36:47Z | [
"python",
"memory-leaks",
"solr"
] |
Python memory footprint vs. heap size | 1,194,416 | <p>I'm having some memory issues while using a python script to issue a large <strong>solr</strong> query. I'm using the <strong>solrpy</strong> library to interface with the solr server. The query returns approximately 80,000 records. Immediately after issuing the query the python memory footprint as viewed through top balloons to ~190MB.</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 193m 189m 3272 S 0.0 11.2 0:11.31 python
...
</code></pre>
<p>At this point, the heap profile as viewed through heapy looks like this:</p>
<pre><code>Partition of a set of 163934 objects. Total size = 14157888 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 80472 49 7401384 52 7401384 52 unicode
1 44923 27 3315928 23 10717312 76 str
...
</code></pre>
<p>The unicode objects represent the unique identifiers of the records from the query. One thing to note is that the total heap size is only 14MB while python is occupying 190MB of physical memory. Once the variable storing the query results falls out of scope, the heap profile correctly reflects the garbage collection:</p>
<pre><code>Partition of a set of 83586 objects. Total size = 6437744 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 44928 54 3316108 52 3316108 52 str
</code></pre>
<p>However, the memory footprint remains unchanged:</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 195m 192m 3432 S 0.0 11.3 0:13.46 python
...
</code></pre>
<p>Why is there such a large disparity between python's physical memory footprint and the size of the python heap?</p>
| 9 | 2009-07-28T14:19:10Z | 1,194,575 | <p>What version of python are you using?<br />
I am asking because <a href="http://evanjones.ca/python-memory.html" rel="nofollow">older version of CPython did not release the memory</a> and this was fixed in Python 2.5.</p>
| 1 | 2009-07-28T14:41:07Z | [
"python",
"memory-leaks",
"solr"
] |
Python memory footprint vs. heap size | 1,194,416 | <p>I'm having some memory issues while using a python script to issue a large <strong>solr</strong> query. I'm using the <strong>solrpy</strong> library to interface with the solr server. The query returns approximately 80,000 records. Immediately after issuing the query the python memory footprint as viewed through top balloons to ~190MB.</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 193m 189m 3272 S 0.0 11.2 0:11.31 python
...
</code></pre>
<p>At this point, the heap profile as viewed through heapy looks like this:</p>
<pre><code>Partition of a set of 163934 objects. Total size = 14157888 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 80472 49 7401384 52 7401384 52 unicode
1 44923 27 3315928 23 10717312 76 str
...
</code></pre>
<p>The unicode objects represent the unique identifiers of the records from the query. One thing to note is that the total heap size is only 14MB while python is occupying 190MB of physical memory. Once the variable storing the query results falls out of scope, the heap profile correctly reflects the garbage collection:</p>
<pre><code>Partition of a set of 83586 objects. Total size = 6437744 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 44928 54 3316108 52 3316108 52 str
</code></pre>
<p>However, the memory footprint remains unchanged:</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 195m 192m 3432 S 0.0 11.3 0:13.46 python
...
</code></pre>
<p>Why is there such a large disparity between python's physical memory footprint and the size of the python heap?</p>
| 9 | 2009-07-28T14:19:10Z | 1,195,441 | <p>CPython implementation only exceptionally free's allocated memory. This is a widely known bug, but it isn't receiving much attention by CPython developers. The recommended workaround is to "fork and die" the process that consumes lots RAM.</p>
| 2 | 2009-07-28T17:06:03Z | [
"python",
"memory-leaks",
"solr"
] |
Python memory footprint vs. heap size | 1,194,416 | <p>I'm having some memory issues while using a python script to issue a large <strong>solr</strong> query. I'm using the <strong>solrpy</strong> library to interface with the solr server. The query returns approximately 80,000 records. Immediately after issuing the query the python memory footprint as viewed through top balloons to ~190MB.</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 193m 189m 3272 S 0.0 11.2 0:11.31 python
...
</code></pre>
<p>At this point, the heap profile as viewed through heapy looks like this:</p>
<pre><code>Partition of a set of 163934 objects. Total size = 14157888 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 80472 49 7401384 52 7401384 52 unicode
1 44923 27 3315928 23 10717312 76 str
...
</code></pre>
<p>The unicode objects represent the unique identifiers of the records from the query. One thing to note is that the total heap size is only 14MB while python is occupying 190MB of physical memory. Once the variable storing the query results falls out of scope, the heap profile correctly reflects the garbage collection:</p>
<pre><code>Partition of a set of 83586 objects. Total size = 6437744 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 44928 54 3316108 52 3316108 52 str
</code></pre>
<p>However, the memory footprint remains unchanged:</p>
<pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8225 root 16 0 195m 192m 3432 S 0.0 11.3 0:13.46 python
...
</code></pre>
<p>Why is there such a large disparity between python's physical memory footprint and the size of the python heap?</p>
| 9 | 2009-07-28T14:19:10Z | 1,196,291 | <p>I've implemented hruske's advice of "fork and die". I'm using os.fork() to execute the memory intensive section of code in a child process, then I let the child process exit. The parent process executes an os.waitpid() on the child so that only one thread is executing at a given time.</p>
<p>If anyone sees any pitfalls with this solution, please chime in.</p>
| 0 | 2009-07-28T19:35:36Z | [
"python",
"memory-leaks",
"solr"
] |
What's wrong with this bit of python code using lambda? | 1,194,543 | <p>Some python code that keeps throwing up an invalid syntax error:</p>
<pre><code>stat.sort(lambda x1, y1: 1 if x1.created_at < y1.created_at else -1)
</code></pre>
| 1 | 2009-07-28T14:35:24Z | 1,194,590 | <p>Try the <a href="http://www.diveintopython.org/power%5Fof%5Fintrospection/and%5For.html" rel="nofollow">and-or trick</a>:</p>
<pre><code>lambda x1, y1: x1.created_at < y1.created_at and 1 or -1
</code></pre>
| 1 | 2009-07-28T14:42:57Z | [
"python"
] |
What's wrong with this bit of python code using lambda? | 1,194,543 | <p>Some python code that keeps throwing up an invalid syntax error:</p>
<pre><code>stat.sort(lambda x1, y1: 1 if x1.created_at < y1.created_at else -1)
</code></pre>
| 1 | 2009-07-28T14:35:24Z | 1,194,766 | <p>This is a better solution:</p>
<pre><code>stat.sort(key=lambda x: x.created_at, reverse=True)
</code></pre>
<p>Or, to avoid the lambda altogether:</p>
<pre><code>from operator import attrgetter
stat.sort(key=attrgetter('created_at'), reverse=True)
</code></pre>
| 8 | 2009-07-28T15:06:01Z | [
"python"
] |
Forward declaration - no admin page in django? | 1,194,723 | <p>This is probably a db design issue, but I couldn't figure out any better. Among several others, I have these models:</p>
<pre><code>class User(models.Model):
name = models.CharField( max_length=40 )
# some fields omitted
bands = models.ManyToManyField( Band )
</code></pre>
<p>and</p>
<pre><code>class Band(models.Model):
creator = models.ForeignKey( User )
# some fields omitted
name = models.CharField( max_length=40 )
</code></pre>
<p>So basically, I've got a user entity, which has many to many relation with a band entity. The twist is that I want a special user, who "created" the band on the site to have special editing capabilities. So I went forward, and added a ForeignKey called creator. The code could not run, because Band came after User in the source. So I forward declared <code>class Band(models.Model): pass</code>. Sadly, this does not seem to be exatly a good idea, because now Band is the only model that doesn't show up any interface elements in the django admin (Bands model is there, it just can't be edited).</p>
<p>My question is that what change should I make in the models to get this work properly? (if any)</p>
| 3 | 2009-07-28T15:00:56Z | 1,194,800 | <p>See: <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey">http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey</a>, which says:</p>
<blockquote>
<p>If you need to create a relationship on a model that has not
yet been defined, you can use the name of the model, rather
than the model object itself:</p>
</blockquote>
<pre><code> class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
</code></pre>
| 12 | 2009-07-28T15:11:35Z | [
"python",
"django",
"database-design",
"circular-dependency",
"forward-declaration"
] |
How to update manytomany field in Django? | 1,194,737 | <p>Here's an example:</p>
<p>If I have these classes</p>
<pre><code>class Author(models.Model):
name = models.CharField(max_length=45)
class Book(models.Model):
name = models.CharField(max_length=45)
authors = models.ManyToManyField(Author)
</code></pre>
<p>In the database I have one Author with the name "George" and another one with the name "Georfe". The last one is a mistake. So what I want is in every Book that have "Georfe" as one of his Author replace it by the Author "George".</p>
<p>In SQL is really easy to do. If id of "George" = 3 and id of "Georfe" = 7 and the relation table name is "author_book":</p>
<pre><code>UPDATE author_book SET id=3 WHERE id=7;
</code></pre>
<p>Is it possible to do that with the Django ORM?</p>
<p>I found a way to do it: I loop trough all the related Books of the mistyped author and do:</p>
<pre><code>book.authors.add(Author.objects.get(id=3))
book.authors.remove(Author.objects.get(id=7))
</code></pre>
<p>But I don't find this solution really elegant and efficient. Is there a solution without the loop?</p>
| 10 | 2009-07-28T15:02:37Z | 1,195,759 | <p>With the auto-generated through table, you can do a two-step insert and delete, which is nice for readability.</p>
<pre><code>george = Author.objects.get(name='George')
georfe = Author.objects.get(name='Georfe')
book.authors.add(george)
book.authors.remove(georfe)
assert george in book.authors
</code></pre>
<p>If you have an explicitly defined through table (authors = models.ManyToManyField(Author, through=BookAuthors) then you can change the relationship explicitly on BookAuthor. A little known fact is that this Model already exists, it is generated by django automatically. Usually you should only create an explicit through model if you have extra data you wish to store (for instance the chapters a particular author wrote, in a multi-author book).</p>
<pre><code># This line is only needed without a custom through model.
BookAuthor = Book.authors.through
book_author = BookAuthor.objects.get(author=georfe, book=great_american_novel)
book_author.author = george
book_author.save()
assert george in book.authors
</code></pre>
| 8 | 2009-07-28T18:10:14Z | [
"python",
"django"
] |
How to update manytomany field in Django? | 1,194,737 | <p>Here's an example:</p>
<p>If I have these classes</p>
<pre><code>class Author(models.Model):
name = models.CharField(max_length=45)
class Book(models.Model):
name = models.CharField(max_length=45)
authors = models.ManyToManyField(Author)
</code></pre>
<p>In the database I have one Author with the name "George" and another one with the name "Georfe". The last one is a mistake. So what I want is in every Book that have "Georfe" as one of his Author replace it by the Author "George".</p>
<p>In SQL is really easy to do. If id of "George" = 3 and id of "Georfe" = 7 and the relation table name is "author_book":</p>
<pre><code>UPDATE author_book SET id=3 WHERE id=7;
</code></pre>
<p>Is it possible to do that with the Django ORM?</p>
<p>I found a way to do it: I loop trough all the related Books of the mistyped author and do:</p>
<pre><code>book.authors.add(Author.objects.get(id=3))
book.authors.remove(Author.objects.get(id=7))
</code></pre>
<p>But I don't find this solution really elegant and efficient. Is there a solution without the loop?</p>
| 10 | 2009-07-28T15:02:37Z | 1,195,768 | <p><strong>Note:</strong> This code will <em>delete</em> the bad 'georfe' author, as well as updating the books to point to the correct author. If you don't want to do that, then use <code>.remove()</code> as @jcdyer's answer mentions.</p>
<p>Can you do something like this?</p>
<pre><code>george_author = Author.objects.get(name="George")
for book in Book.objects.filter(authors__name="Georfe"):
book.authors.add(george_author.id)
book.authors.filter(name="Georfe").delete()
</code></pre>
<p>I suspect that this would be easier if you had an explicit table joining the two models (with the "through" keyword arg) -- in that case, you would have access to the relationship table directly, and could just do a <code>.update(id=george_author.id)</code> on it.</p>
| 10 | 2009-07-28T18:11:54Z | [
"python",
"django"
] |
How do I change the directory of InMemoryUploadedFile? | 1,194,963 | <p>It seems that if I do not create a ModelForm from a model, and create a new object and save it, it will not respect the field's upload directory.</p>
<p>How do I change the directory of a InMemoryUploadedFile so I can manually implement the upload dir? Because the InMemoryUploadedFile obj is just the filename, and I would like to add the upload dir parameters. Thank you!</p>
<pre><code>def add_image(self, image):
pi = ProductImages()
pi.image = image
pi.save()
self.o_gallery_images.add(pi)
return True
</code></pre>
<p>(Code that does not respect the upload dir of ProductImages "image" field)</p>
| 0 | 2009-07-28T15:38:46Z | 1,197,046 | <p>How did you define the attribute of image in your ProductImages model? Did you have upload_to argument in your FileField? </p>
<pre><code>class ProductImages(models.Model):
image = models.FileField(upload_to="images/")
</code></pre>
| 1 | 2009-07-28T22:13:02Z | [
"python",
"django"
] |
Installing Django with mod_wsgi | 1,195,260 | <p>I wrote an application using Django 1.0. It works fine with the django test server. But when I tried to get it into a more likely production enviroment the Apache server fails to run the app.
The server I use is <a href="http://www.wampserver.com" rel="nofollow" title="WAMPServer's WebSite">WAMP2.0</a>. I've been a PHP programmer for years now and I've been using WAMPServer since long ago.
I installed the mod_wsgi.so and seems to work just fine (no services error) but I can't configure the httpd.conf to look at my python scripts located outside the server root.</p>
<p>For now, I'm cool with overriding the document root and serve the django app from the document root instead so the httpd.conf line should look like this:</p>
<pre>
WSGIScriptAlias / C:/Users/Marcos/Documents/mysite/apache/django.wsgi
</pre>
<p>but the server's response is a 403 Forbidden</p>
| 3 | 2009-07-28T16:33:46Z | 1,195,457 | <p>Have you seen <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango">http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango</a> ?</p>
<p>You need more than one line to assure that Apache will play nicely.</p>
<pre><code>Alias /media/ /usr/local/django/mysite/media/
<Directory /usr/local/django/mysite/media>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /usr/local/django/mysite/apache/django.wsgi
<Directory /usr/local/django/mysite/apache>
Order deny,allow
Allow from all
</Directory>
</code></pre>
<p>The <code><Directory></code>, as well as appropriate file system ownership and permissions are essential.</p>
<p>The <code>usr/local/django/mysite/apache</code> directory has your Python/Django app and the all-important <code>django.wsgi</code> file. You must provide permissions on this directory.</p>
| 6 | 2009-07-28T17:09:08Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Installing Django with mod_wsgi | 1,195,260 | <p>I wrote an application using Django 1.0. It works fine with the django test server. But when I tried to get it into a more likely production enviroment the Apache server fails to run the app.
The server I use is <a href="http://www.wampserver.com" rel="nofollow" title="WAMPServer's WebSite">WAMP2.0</a>. I've been a PHP programmer for years now and I've been using WAMPServer since long ago.
I installed the mod_wsgi.so and seems to work just fine (no services error) but I can't configure the httpd.conf to look at my python scripts located outside the server root.</p>
<p>For now, I'm cool with overriding the document root and serve the django app from the document root instead so the httpd.conf line should look like this:</p>
<pre>
WSGIScriptAlias / C:/Users/Marcos/Documents/mysite/apache/django.wsgi
</pre>
<p>but the server's response is a 403 Forbidden</p>
| 3 | 2009-07-28T16:33:46Z | 1,195,520 | <p>mod_wsgi's documentation is very good. Try using their quick configuration guide and go from there:
<a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide" rel="nofollow">http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide</a></p>
| 1 | 2009-07-28T17:21:28Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
Installing Django with mod_wsgi | 1,195,260 | <p>I wrote an application using Django 1.0. It works fine with the django test server. But when I tried to get it into a more likely production enviroment the Apache server fails to run the app.
The server I use is <a href="http://www.wampserver.com" rel="nofollow" title="WAMPServer's WebSite">WAMP2.0</a>. I've been a PHP programmer for years now and I've been using WAMPServer since long ago.
I installed the mod_wsgi.so and seems to work just fine (no services error) but I can't configure the httpd.conf to look at my python scripts located outside the server root.</p>
<p>For now, I'm cool with overriding the document root and serve the django app from the document root instead so the httpd.conf line should look like this:</p>
<pre>
WSGIScriptAlias / C:/Users/Marcos/Documents/mysite/apache/django.wsgi
</pre>
<p>but the server's response is a 403 Forbidden</p>
| 3 | 2009-07-28T16:33:46Z | 1,197,411 | <p>You have:</p>
<pre><code>WSGIScriptAlias / /C:/Users/Marcos/Documents/mysite/apache/django.wsgi
</code></pre>
<p>That is wrong as RHS is not a valid Windows pathname. Use:</p>
<pre><code>WSGIScriptAlias / C:/Users/Marcos/Documents/mysite/apache/django.wsgi
</code></pre>
<p>That is, no leading slash before the Windows drive specifier.</p>
<p>Other than that, follow the mod_wsgi documentation others have pointed out.</p>
<p><hr /></p>
<p>Poster edited question to change what now would appear to be a typo in the post and not a problem with his configuration.</p>
<p>If that is the case, next causes for a 403 are as follows.</p>
<p>First is that you need to also have:</p>
<pre><code><Directory C:/Users/Marcos/Documents/mysite/apache>
Order deny,allow
Allow from all
</Directory>
</code></pre>
<p>If you don't have that then Apache isn't being granted rights to serve a script from that directory and so will return FORBIDDEN (403).</p>
<p>Second is that you do have that, but don't acknowledge that you do, and that that directory or the WSGI script file is not readable by the user that the Apache service runs as under Windows.</p>
| 7 | 2009-07-29T00:04:32Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
django @login_required decorator error | 1,195,432 | <p>I'm running django 1.1rc. All of my code works correctly using django's built in development server; however, when I move it into production using Apache's mod_python, I get the following error on all of my views:</p>
<pre><code> Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin
</code></pre>
<p>What might I look for that's causing this error?</p>
<p><strong>Update:</strong>
What's strange is that I can access the views account/login and also the admin site just fine. I tried removing the @login_required decorator on all of my views and it generates the same type of exception.</p>
<p><strong>Update2:</strong>
So it seems like there is a problem with any view in my custom package: booster. The django.contrib works fine. I'm serving the app at <a href="http://server_name/booster" rel="nofollow">http://server_name/booster</a>. However, the built-in auth login view redirects to <a href="http://server_name/accounts/login" rel="nofollow">http://server_name/accounts/login</a>. Does this give a clue to what may be wrong?</p>
<p><strong>Traceback:</strong></p>
<pre><code>Environment:
Request Method: GET
Request URL: http://lghbb/booster/hospitalists/
Django Version: 1.1 rc 1
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'booster.core',
'booster.hospitalists']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Template error:
In template c:\booster\templates\hospitalists\my_patients.html, error at line 23
Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
13 : <th scope="col">Name</th>
14 : <th scope="col">DOB</th>
15 : <th scope="col">IC</th>
16 : <th scope="col">Type</th>
17 : <th scope="col">LOS</th>
18 : <th scope="col">PCP</th>
19 : <th scope="col">Service</th>
20 : </tr>
21 : </thead>
22 : <tbody>
23 : {% for patient in patients %}
24 : <tr class="{{ patient.gender }} select">
25 : <td>{{ patient.bed }}</td>
26 : <td>{{ patient.mr }}</td>
27 : <td>{{ patient.acct }}</td>
28 : <td><a href="{% url hospitalists.views.patient patient.id %}">{{ patient }}</a></td>
29 : <td>{{ patient.dob }}</td>
30 : <td class="{% if patient.infections.count %}infection{% endif %}">
31 : {% for infection in patient.infections.all %}
32 : {{ infection.short_name }} &nbsp;
33 : {% endfor %}
Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python25\Lib\site-packages\django\contrib\auth\decorators.py" in __call__
78. return self.view_func(request, *args, **kwargs)
File "c:/booster\hospitalists\views.py" in index
50. return render_to_response('hospitalists/my_patients.html', RequestContext(request, {'patients': patients, 'user' : request.user}))
File "C:\Python25\Lib\site-packages\django\shortcuts\__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Python25\Lib\site-packages\django\template\loader.py" in render_to_string
108. return t.render(context_instance)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
178. return self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
71. result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\loader_tags.py" in render
97. return compiled_parent.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
178. return self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
71. result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\loader_tags.py" in render
24. result = self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
Exception Type: TemplateSyntaxError at /hospitalists/
Exception Value: Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
Original Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\django\template\debug.py", line 71, in render_node
result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\defaulttags.py", line 155, in render
nodelist.append(node.render(context))
File "C:\Python25\Lib\site-packages\django\template\defaulttags.py", line 382, in render
raise e
NoReverseMatch: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
</code></pre>
<p>Thanks for your help,
Pete</p>
| 3 | 2009-07-28T17:03:33Z | 1,195,486 | <p>Having googled on this a bit, it sounds like you may need to delete any .pyc files on the server and let it recompile them the first time they're accessed.</p>
| 0 | 2009-07-28T17:15:34Z | [
"python",
"django"
] |
django @login_required decorator error | 1,195,432 | <p>I'm running django 1.1rc. All of my code works correctly using django's built in development server; however, when I move it into production using Apache's mod_python, I get the following error on all of my views:</p>
<pre><code> Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin
</code></pre>
<p>What might I look for that's causing this error?</p>
<p><strong>Update:</strong>
What's strange is that I can access the views account/login and also the admin site just fine. I tried removing the @login_required decorator on all of my views and it generates the same type of exception.</p>
<p><strong>Update2:</strong>
So it seems like there is a problem with any view in my custom package: booster. The django.contrib works fine. I'm serving the app at <a href="http://server_name/booster" rel="nofollow">http://server_name/booster</a>. However, the built-in auth login view redirects to <a href="http://server_name/accounts/login" rel="nofollow">http://server_name/accounts/login</a>. Does this give a clue to what may be wrong?</p>
<p><strong>Traceback:</strong></p>
<pre><code>Environment:
Request Method: GET
Request URL: http://lghbb/booster/hospitalists/
Django Version: 1.1 rc 1
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'booster.core',
'booster.hospitalists']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Template error:
In template c:\booster\templates\hospitalists\my_patients.html, error at line 23
Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
13 : <th scope="col">Name</th>
14 : <th scope="col">DOB</th>
15 : <th scope="col">IC</th>
16 : <th scope="col">Type</th>
17 : <th scope="col">LOS</th>
18 : <th scope="col">PCP</th>
19 : <th scope="col">Service</th>
20 : </tr>
21 : </thead>
22 : <tbody>
23 : {% for patient in patients %}
24 : <tr class="{{ patient.gender }} select">
25 : <td>{{ patient.bed }}</td>
26 : <td>{{ patient.mr }}</td>
27 : <td>{{ patient.acct }}</td>
28 : <td><a href="{% url hospitalists.views.patient patient.id %}">{{ patient }}</a></td>
29 : <td>{{ patient.dob }}</td>
30 : <td class="{% if patient.infections.count %}infection{% endif %}">
31 : {% for infection in patient.infections.all %}
32 : {{ infection.short_name }} &nbsp;
33 : {% endfor %}
Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python25\Lib\site-packages\django\contrib\auth\decorators.py" in __call__
78. return self.view_func(request, *args, **kwargs)
File "c:/booster\hospitalists\views.py" in index
50. return render_to_response('hospitalists/my_patients.html', RequestContext(request, {'patients': patients, 'user' : request.user}))
File "C:\Python25\Lib\site-packages\django\shortcuts\__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Python25\Lib\site-packages\django\template\loader.py" in render_to_string
108. return t.render(context_instance)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
178. return self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
71. result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\loader_tags.py" in render
97. return compiled_parent.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
178. return self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
71. result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\loader_tags.py" in render
24. result = self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
Exception Type: TemplateSyntaxError at /hospitalists/
Exception Value: Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
Original Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\django\template\debug.py", line 71, in render_node
result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\defaulttags.py", line 155, in render
nodelist.append(node.render(context))
File "C:\Python25\Lib\site-packages\django\template\defaulttags.py", line 382, in render
raise e
NoReverseMatch: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
</code></pre>
<p>Thanks for your help,
Pete</p>
| 3 | 2009-07-28T17:03:33Z | 1,196,998 | <p>I had a problem with my apache configuration:</p>
<p>I changed this:</p>
<p>SetEnv DJANGO_SETTINGS_MODULE settings</p>
<p>to this:</p>
<p>SetEnv DJANGO_SETTINGS_MODULE booster.settings</p>
<p>To solve the defualt auth login problem, I added the setting settings.LOGIN_URL.</p>
| 1 | 2009-07-28T22:00:19Z | [
"python",
"django"
] |
django @login_required decorator error | 1,195,432 | <p>I'm running django 1.1rc. All of my code works correctly using django's built in development server; however, when I move it into production using Apache's mod_python, I get the following error on all of my views:</p>
<pre><code> Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin
</code></pre>
<p>What might I look for that's causing this error?</p>
<p><strong>Update:</strong>
What's strange is that I can access the views account/login and also the admin site just fine. I tried removing the @login_required decorator on all of my views and it generates the same type of exception.</p>
<p><strong>Update2:</strong>
So it seems like there is a problem with any view in my custom package: booster. The django.contrib works fine. I'm serving the app at <a href="http://server_name/booster" rel="nofollow">http://server_name/booster</a>. However, the built-in auth login view redirects to <a href="http://server_name/accounts/login" rel="nofollow">http://server_name/accounts/login</a>. Does this give a clue to what may be wrong?</p>
<p><strong>Traceback:</strong></p>
<pre><code>Environment:
Request Method: GET
Request URL: http://lghbb/booster/hospitalists/
Django Version: 1.1 rc 1
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'booster.core',
'booster.hospitalists']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Template error:
In template c:\booster\templates\hospitalists\my_patients.html, error at line 23
Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
13 : <th scope="col">Name</th>
14 : <th scope="col">DOB</th>
15 : <th scope="col">IC</th>
16 : <th scope="col">Type</th>
17 : <th scope="col">LOS</th>
18 : <th scope="col">PCP</th>
19 : <th scope="col">Service</th>
20 : </tr>
21 : </thead>
22 : <tbody>
23 : {% for patient in patients %}
24 : <tr class="{{ patient.gender }} select">
25 : <td>{{ patient.bed }}</td>
26 : <td>{{ patient.mr }}</td>
27 : <td>{{ patient.acct }}</td>
28 : <td><a href="{% url hospitalists.views.patient patient.id %}">{{ patient }}</a></td>
29 : <td>{{ patient.dob }}</td>
30 : <td class="{% if patient.infections.count %}infection{% endif %}">
31 : {% for infection in patient.infections.all %}
32 : {{ infection.short_name }} &nbsp;
33 : {% endfor %}
Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python25\Lib\site-packages\django\contrib\auth\decorators.py" in __call__
78. return self.view_func(request, *args, **kwargs)
File "c:/booster\hospitalists\views.py" in index
50. return render_to_response('hospitalists/my_patients.html', RequestContext(request, {'patients': patients, 'user' : request.user}))
File "C:\Python25\Lib\site-packages\django\shortcuts\__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Python25\Lib\site-packages\django\template\loader.py" in render_to_string
108. return t.render(context_instance)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
178. return self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
71. result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\loader_tags.py" in render
97. return compiled_parent.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
178. return self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
71. result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\loader_tags.py" in render
24. result = self.nodelist.render(context)
File "C:\Python25\Lib\site-packages\django\template\__init__.py" in render
779. bits.append(self.render_node(node, context))
File "C:\Python25\Lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
Exception Type: TemplateSyntaxError at /hospitalists/
Exception Value: Caught an exception while rendering: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
Original Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\django\template\debug.py", line 71, in render_node
result = node.render(context)
File "C:\Python25\Lib\site-packages\django\template\defaulttags.py", line 155, in render
nodelist.append(node.render(context))
File "C:\Python25\Lib\site-packages\django\template\defaulttags.py", line 382, in render
raise e
NoReverseMatch: Reverse for '<django.contrib.auth.decorators._CheckLogin object at 0x05016DD0>' with arguments '(7L,)' and keyword arguments '{}' not found.
</code></pre>
<p>Thanks for your help,
Pete</p>
| 3 | 2009-07-28T17:03:33Z | 1,647,161 | <p>This is a pretty common 'phantom error' in Django. In other words, there's a bug in your code, but the debug page is spitting back a misleading exception. Usually when I see this error, it's because I've screwed something up in a url tag in one of my templates - most commonly a misspelled url or a url for a view that I haven't written yet. A lot of the times, the Django debug page will even highlight the url that the error is coming from. </p>
| 0 | 2009-10-29T23:24:05Z | [
"python",
"django"
] |
Python scoping problem | 1,195,577 | <p>I have a trivial example:</p>
<pre><code>
def func1():
local_var = None
def func(args):
print args,
print "local_var:", local_var
local_var = "local"
func("first")
func("second")
func1()
</code></pre>
I expect the output to be:
<pre>
first local_var: None
second local_var: local
</pre>
<p>However, my actual output is:</p>
<pre>
first local_var:
Traceback (most recent call last):
File "test.py", line 13, in
func1()
File "test.py", line 10, in func1
func("first")
File "test.py", line 6, in func
print "local_var:", local_var
UnboundLocalError: local variable 'local_var' referenced before assignment
</pre>
<p>My understanding of python scoping rules dictate that this should work as expected. I have other code where this works as expected, but reducing one non-working code fragment to it's trivial case above also doesn't work. So I'm stumped.</p>
| 3 | 2009-07-28T17:38:30Z | 1,195,635 | <p>Before Python 3.0, functions couldn't write to non-global variables in outer scopes. Python3 has introduced the <code>nonlocal</code> keyword that lets this work. You'd add <code>nonlocal local_var</code> at the top of <code>func()</code>'s definition to get the output you expected. See <a href="http://www.python.org/dev/peps/pep-3104/" rel="nofollow" title="Access to Names in Outer Scopes">PEP 3104</a>.</p>
<p>If you're not working in Python 3 you'll have to make the variable global, or pass it into the function somehow.</p>
| 1 | 2009-07-28T17:47:24Z | [
"python",
"scoping"
] |
Python scoping problem | 1,195,577 | <p>I have a trivial example:</p>
<pre><code>
def func1():
local_var = None
def func(args):
print args,
print "local_var:", local_var
local_var = "local"
func("first")
func("second")
func1()
</code></pre>
I expect the output to be:
<pre>
first local_var: None
second local_var: local
</pre>
<p>However, my actual output is:</p>
<pre>
first local_var:
Traceback (most recent call last):
File "test.py", line 13, in
func1()
File "test.py", line 10, in func1
func("first")
File "test.py", line 6, in func
print "local_var:", local_var
UnboundLocalError: local variable 'local_var' referenced before assignment
</pre>
<p>My understanding of python scoping rules dictate that this should work as expected. I have other code where this works as expected, but reducing one non-working code fragment to it's trivial case above also doesn't work. So I'm stumped.</p>
| 3 | 2009-07-28T17:38:30Z | 1,195,680 | <p>The standard way to solve this problem pre-3.0 would be</p>
<pre><code>def func1():
local_var = [None]
def func(args):
print args,
print "local_var:", local_var[0]
local_var[0] = "local"
func("first")
func("second")
func1()
</code></pre>
| 1 | 2009-07-28T17:56:25Z | [
"python",
"scoping"
] |
Python scoping problem | 1,195,577 | <p>I have a trivial example:</p>
<pre><code>
def func1():
local_var = None
def func(args):
print args,
print "local_var:", local_var
local_var = "local"
func("first")
func("second")
func1()
</code></pre>
I expect the output to be:
<pre>
first local_var: None
second local_var: local
</pre>
<p>However, my actual output is:</p>
<pre>
first local_var:
Traceback (most recent call last):
File "test.py", line 13, in
func1()
File "test.py", line 10, in func1
func("first")
File "test.py", line 6, in func
print "local_var:", local_var
UnboundLocalError: local variable 'local_var' referenced before assignment
</pre>
<p>My understanding of python scoping rules dictate that this should work as expected. I have other code where this works as expected, but reducing one non-working code fragment to it's trivial case above also doesn't work. So I'm stumped.</p>
| 3 | 2009-07-28T17:38:30Z | 1,195,692 | <p>Python's scoping rules are discussed and explained in this related question:</p>
<p><a href="http://stackoverflow.com/questions/1188944/reason-for-unintuitive-unboundlocalerror-behaviour">http://stackoverflow.com/questions/1188944/reason-for-unintuitive-unboundlocalerror-behaviour</a></p>
| 1 | 2009-07-28T17:58:16Z | [
"python",
"scoping"
] |
Python scoping problem | 1,195,577 | <p>I have a trivial example:</p>
<pre><code>
def func1():
local_var = None
def func(args):
print args,
print "local_var:", local_var
local_var = "local"
func("first")
func("second")
func1()
</code></pre>
I expect the output to be:
<pre>
first local_var: None
second local_var: local
</pre>
<p>However, my actual output is:</p>
<pre>
first local_var:
Traceback (most recent call last):
File "test.py", line 13, in
func1()
File "test.py", line 10, in func1
func("first")
File "test.py", line 6, in func
print "local_var:", local_var
UnboundLocalError: local variable 'local_var' referenced before assignment
</pre>
<p>My understanding of python scoping rules dictate that this should work as expected. I have other code where this works as expected, but reducing one non-working code fragment to it's trivial case above also doesn't work. So I'm stumped.</p>
| 3 | 2009-07-28T17:38:30Z | 1,195,696 | <p>The assignment to <code>local_var</code> in <code>func</code> makes it local <strong>to <code>func</code></strong> -- so the <code>print</code> statement references that "very very local" variable before it's ever assigned to, as the exception says. As jtb says, in Python 3 you can solve this with <code>nonlocal</code>, but it's clear from your code, using <code>print</code> statements, that you're working in Python 2. The traditional solution in Python 2 is to make sure that the assignment is not to a barename and thus does not make the variable more local than you wish, e.g.:</p>
<pre><code>def func1():
local_var = [None]
def func(args):
print args,
print "local_var:", local_var[0]
local_var[0] = "local"
func("first")
func("second")
func1()
</code></pre>
<p>the assignment to the indexing is not to a barename and therefore doesn't affect locality, and since Python 2.2 it's perfectly acceptable for nested inner functions to <em>refer</em> to variables that are locals in outer containing functions, which is all this version does (<em>assigning</em> to barenames is a different issue than <em>referring</em> to variables).</p>
| 9 | 2009-07-28T17:58:36Z | [
"python",
"scoping"
] |
Load non-uniform data from a txt file into a msql database | 1,195,753 | <p>I have text files with a lot of uniform rows that I'd like to load into a mysql database, but the files are not completely uniform. There are several rows at the beginning for some miscellaneous information, and there are timestamps about every 6 lines.</p>
<p>"LOAD DATA INFILE" doesn't seem like the answer here because of my file format. It doesn't seem flexible enough.</p>
<p>Note: The header of the file takes up a pre-determined number of lines. The timestamp is predicatable, but there are some other random notes that can pop up that need to be ignored. They always start with several keywords that I can check for though.</p>
<p>A sample of my file in the middle:</p>
<pre><code> 103.3 .00035
103.4 .00035
103.5 .00035
103.6 .00035
103.7 .00035
103.8 .00035
103.9 .00035
Time: 07-15-2009 13:37
104.0 .00035
104.1 .00035
104.2 .00035
104.3 .00035
104.4 .00035
104.5 .00035
104.6 .00035
104.7 .00035
104.8 .00035
104.9 .00035
Time: 07-15-2009 13:38
105.0 .00035
105.1 .00035
105.2 .00035
</code></pre>
<p>From this I need to load information into three fields. The first field needs to be the filename, and the other are present in the example. I could add the filename to be in front of each data line, but this may not be necessary if I use a script to load the data.</p>
<p>If required, I can change the file format, but I don't want to lose the timestamps and header information.</p>
<p>SQLAlchemy seems like a possible good choice for python, which I'm fairly familiar with.</p>
<p>I have thousands of lines of data, so loading all my files that I already have may be slow at first, but afterwards, I just want to load in the <em>new</em> lines of the file. So, I'll need to be selective about what I load in because I don't want duplicate information.</p>
<p>Any suggestions on a selective data loading method from a text file to a mysql database?
And beyond that, what do you suggest for only loading in lines of the file that are not already in the database?</p>
<p>Thanks all. Meanwhile, I'll look into SQLAlchemy a bit more and see if I get somewhere with that.</p>
| 0 | 2009-07-28T18:08:59Z | 1,195,784 | <p>LOAD DATA INFILE has an IGNORE LINES option which you can use to skip the header. According to <a href="http://dev.mysql.com/doc/refman/5.0/en/load-data.html" rel="nofollow">the docs</a>, it also has a " LINES STARTING BY 'prefix_string'" option which you could use since all of your data lines seem to start with two blanks, while your timestamps start at the beginning of the line.</p>
| 2 | 2009-07-28T18:15:11Z | [
"python",
"mysql",
"file-io",
"sqlalchemy",
"load-data-infile"
] |
Load non-uniform data from a txt file into a msql database | 1,195,753 | <p>I have text files with a lot of uniform rows that I'd like to load into a mysql database, but the files are not completely uniform. There are several rows at the beginning for some miscellaneous information, and there are timestamps about every 6 lines.</p>
<p>"LOAD DATA INFILE" doesn't seem like the answer here because of my file format. It doesn't seem flexible enough.</p>
<p>Note: The header of the file takes up a pre-determined number of lines. The timestamp is predicatable, but there are some other random notes that can pop up that need to be ignored. They always start with several keywords that I can check for though.</p>
<p>A sample of my file in the middle:</p>
<pre><code> 103.3 .00035
103.4 .00035
103.5 .00035
103.6 .00035
103.7 .00035
103.8 .00035
103.9 .00035
Time: 07-15-2009 13:37
104.0 .00035
104.1 .00035
104.2 .00035
104.3 .00035
104.4 .00035
104.5 .00035
104.6 .00035
104.7 .00035
104.8 .00035
104.9 .00035
Time: 07-15-2009 13:38
105.0 .00035
105.1 .00035
105.2 .00035
</code></pre>
<p>From this I need to load information into three fields. The first field needs to be the filename, and the other are present in the example. I could add the filename to be in front of each data line, but this may not be necessary if I use a script to load the data.</p>
<p>If required, I can change the file format, but I don't want to lose the timestamps and header information.</p>
<p>SQLAlchemy seems like a possible good choice for python, which I'm fairly familiar with.</p>
<p>I have thousands of lines of data, so loading all my files that I already have may be slow at first, but afterwards, I just want to load in the <em>new</em> lines of the file. So, I'll need to be selective about what I load in because I don't want duplicate information.</p>
<p>Any suggestions on a selective data loading method from a text file to a mysql database?
And beyond that, what do you suggest for only loading in lines of the file that are not already in the database?</p>
<p>Thanks all. Meanwhile, I'll look into SQLAlchemy a bit more and see if I get somewhere with that.</p>
| 0 | 2009-07-28T18:08:59Z | 1,195,978 | <p>Another way to do this is to just have Python transform the files for you. You could have it filter the input file to an output file based on the criteria that you specify pretty easily. This code assumes you have some function is_data(line) that checks line for the criteria you specify and returns true if it is data.</p>
<pre><code>with file("output", "w") as out:
for line in file("input"):
if is_data(line):
out.write(line)
</code></pre>
<p>Additionally, if you files just continue to concat you could have it store and read the last recorded offset (this code may not be 100% right, I haven't test it. But you get the idea):</p>
<pre><code>if os.path.exists("filter_settings.txt"):
start=long(file("filter_settings.txt").read())
else:
start=0
with file("output", "w") as out:
input = file("input")
input.seek(start)
for line in input:
if is_data(line):
out.write(line)
file("filter_settings.txt", "w").write(input.tell())
</code></pre>
| 2 | 2009-07-28T18:42:22Z | [
"python",
"mysql",
"file-io",
"sqlalchemy",
"load-data-infile"
] |
Web Services with Google App Engine | 1,195,893 | <p>I see that Google App Engine can host web applications that will return html, etc. But what about web services that communicate over http and accept / return xml?</p>
<p>Does anyone know how this is being done in Goggle App Engine with Python or for that matter in Java (JAS-WX is not supported)? Any links o samples or articles is greatly appreciated.</p>
<p>Thanks // :)</p>
| 6 | 2009-07-28T18:31:01Z | 1,195,949 | <p>Google App Engine allows you to write web services that return any type of HTTP response content. This includes xml, json, text, etc.</p>
<p>For instance, take a look at the <a href="http://code.google.com/appengine/docs/java/gettingstarted/">guestbook sample project</a> offered by Google which shows the HTTP response coming back as text/plain:</p>
<pre><code> public class GuestbookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user != null) {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, " + user.getNickname());
} else {
resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
}
}
}
</code></pre>
<p>Additionally, the <a href="http://groups.google.com/group/google-appengine">app engine google group</a> is a great place to learn more, ask questions, and see sample code.</p>
| 9 | 2009-07-28T18:38:23Z | [
"java",
"python",
"web-services",
"google-app-engine"
] |
Web Services with Google App Engine | 1,195,893 | <p>I see that Google App Engine can host web applications that will return html, etc. But what about web services that communicate over http and accept / return xml?</p>
<p>Does anyone know how this is being done in Goggle App Engine with Python or for that matter in Java (JAS-WX is not supported)? Any links o samples or articles is greatly appreciated.</p>
<p>Thanks // :)</p>
| 6 | 2009-07-28T18:31:01Z | 1,196,729 | <p>Most python apps just write a handler that outputs the shaped xml directly... this example serves any GET requests submitted to the root url ("/"): </p>
<pre><code>import wsgiref.handlers
from google.appengine.ext import webapp
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('<myXml><node id=1 /></myXml>')
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
</code></pre>
| 3 | 2009-07-28T21:05:22Z | [
"java",
"python",
"web-services",
"google-app-engine"
] |
Web Services with Google App Engine | 1,195,893 | <p>I see that Google App Engine can host web applications that will return html, etc. But what about web services that communicate over http and accept / return xml?</p>
<p>Does anyone know how this is being done in Goggle App Engine with Python or for that matter in Java (JAS-WX is not supported)? Any links o samples or articles is greatly appreciated.</p>
<p>Thanks // :)</p>
| 6 | 2009-07-28T18:31:01Z | 1,197,991 | <p>It's definitely possible (and not too hard) to use GAE to host "web services that communicate over http and accept / return xml".</p>
<p>To parse XML requests (presumably coming in as the body of HTTP POST or PUT requests), you have several options, e.g. pyexpat or minidom on top of it, see <a href="http://groups.google.com/group/google-appengine/browse%5Fthread/thread/85b7d03ff0d4ff2b/9fdfec112a4c051a?pli=1" rel="nofollow">this thread</a> for example (especially the last post on it).</p>
<p>If you wish, you could also use minidom to construct the XML response and <a href="http://docs.python.org/library/xml.dom.minidom.html#xml.dom.minidom.Node.writexml" rel="nofollow">write</a> it back (e.g. using a <code>StringIO</code> instance to hold the formatted response and its <code>write</code> method as the argument to your minidom instance's <code>writexml</code> method, then turning around and using the <code>getvalue</code> of that instance to get the needed result as a string). Even though you're limited to pure Python and a few "whiteslisted" C-coded extensions such as pyexpat, that doesn't really limit your choices all that much, nor make your life substantially harder.</p>
<p>Just do remember to set your response's content type header to <code>text/xml</code> (or some media type that's even more specific and appropriate, if any, of course!) -- and, I recommend, use UTF-8 (the standard text encoding that lets you express all of Unicode while being plain ASCII if your data do happen to be plain ASCII!-), not weird "code pages" or regionally limited codes such as the ISO-8859 family.</p>
| 2 | 2009-07-29T04:05:34Z | [
"java",
"python",
"web-services",
"google-app-engine"
] |
How to manage many to one relationship in Django | 1,195,911 | <p>I am trying to make a many to one relationship and want to be able to control it (add -remove etc) via the admin panel. So this is my model.py:</p>
<pre><code>from django.db import models
class Office(models.Model):
name = models.CharField(max_length=30)
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
office = models.ForeignKey(Office)
</code></pre>
<p>I want my model allow a province to have several Office.</p>
<p>So inside my admin.py:</p>
<pre><code>class ProvinceCreator(admin.ModelAdmin):
list_filter = ['numberPlate']
list_display = ['name', 'numberPlate','office']
class OfficeCreator(admin.ModelAdmin):
list_display = ['name']
</code></pre>
<p>This seems correct to me, however when I try to add a new province with the admin panel, I get this:</p>
<pre><code>TemplateSyntaxError at /admin/haritaapp/province/
Caught an exception while rendering: no such column: haritaapp_province.office_id
</code></pre>
<p>Thanks</p>
| 5 | 2009-07-28T18:34:21Z | 1,196,107 | <p>Have you looked at the docs for doing Inlines?</p>
<p>In your admin.py</p>
<pre><code>class Office(admin.TabularInline):
model = Office
class ProvinceAdmin(admin.ModelAdmin):
inlines = [
Office,
]
</code></pre>
| 1 | 2009-07-28T19:01:55Z | [
"python",
"django",
"django-models",
"django-admin"
] |
How to manage many to one relationship in Django | 1,195,911 | <p>I am trying to make a many to one relationship and want to be able to control it (add -remove etc) via the admin panel. So this is my model.py:</p>
<pre><code>from django.db import models
class Office(models.Model):
name = models.CharField(max_length=30)
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
office = models.ForeignKey(Office)
</code></pre>
<p>I want my model allow a province to have several Office.</p>
<p>So inside my admin.py:</p>
<pre><code>class ProvinceCreator(admin.ModelAdmin):
list_filter = ['numberPlate']
list_display = ['name', 'numberPlate','office']
class OfficeCreator(admin.ModelAdmin):
list_display = ['name']
</code></pre>
<p>This seems correct to me, however when I try to add a new province with the admin panel, I get this:</p>
<pre><code>TemplateSyntaxError at /admin/haritaapp/province/
Caught an exception while rendering: no such column: haritaapp_province.office_id
</code></pre>
<p>Thanks</p>
| 5 | 2009-07-28T18:34:21Z | 1,196,142 | <p>It seams that you have your models setup <em>backwards</em>. If you want province to have many offices, then province should be a foreign key in the Office model.</p>
<pre><code>from django.db import models
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
class Office(models.Model):
name = models.CharField(max_length=30)
province = models.ForeignKey(Province)
</code></pre>
<p>This would be straightforward and very intuitive way to implement one-to-many relationsship</p>
<p>As for the error that you are getting "no such column: haritaapp_province.office_id", when you add a new attribute (in your case office) to the model, you should either manually add column to the table. Or drop the table and re-run the syncdb:</p>
<pre><code> python manage.py syncdb
</code></pre>
<p>Django will <b>not</b> automatically add new columns to the table when you add new fields to the model.</p>
| 6 | 2009-07-28T19:08:47Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Sources of PyS60's standard functions (particularly appuifw.query) | 1,196,050 | <p>I need to give user ability to enter a time in form hh:mm:ss (with appropriate validation of course). And standard function <code>appuifw.query(u'Label', 'time')</code> works almost fine except that it allows to enter only hours and minutes (hh:mm). So I want to look though its source and write my own that enhances it in the stated manner.</p>
<p>I've found file <code>epoc32\winscw\c\resource\appuifw.py</code> that comes with PyS60 SDK extension but it only contains constructor implementation (<code>__init__</code>).</p>
<p>So the question is where to find sources of platform's standard functions (particularly <code>appuifw.query</code>).</p>
| 0 | 2009-07-28T18:52:23Z | 1,203,088 | <p>Are the <a href="https://garage.maemo.org/frs/?group%5Fid=854" rel="nofollow">*_src.zip files</a> on garage.maemo.org any useful? (I don't currently have the tools to verify what's in there.)</p>
| 1 | 2009-07-29T21:14:29Z | [
"python",
"mobile",
"pys60"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.