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 |
|---|---|---|---|---|---|---|---|---|---|
How to start a background process in Python? | 1,196,074 | <p>I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>
| 135 | 2009-07-28T18:56:50Z | 1,196,112 | <p>You probably want the answer to <a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395">"How to call an external command in Python"</a>.</p>
<p>The simplest approach is to use the <code>os.system</code> function, e.g.:</p>
<pre><code>import os
os.system("some_command &")
</code></pre>
<p>Basically, whatever you pass to the <code>system</code> function will be executed the same as if you'd passed it to the shell in a script.</p>
| 24 | 2009-07-28T19:02:59Z | [
"python",
"process",
"daemon"
] |
How to start a background process in Python? | 1,196,074 | <p>I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>
| 135 | 2009-07-28T18:56:50Z | 1,196,122 | <p><strong>Note</strong>: This answer is less current than it was when posted in 2009. Using the <code>subprocess</code> module shown in other answers is now recommended <a href="https://docs.python.org/2/library/os.html?highlight=os#os.spawnl">in the docs</a></p>
<blockquote>
<p>(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)</p>
</blockquote>
<hr>
<p>If you want your process to start in the background you can either use <code>system()</code> and call it in the same way your shell script did, or you can <code>spawn</code> it:</p>
<pre><code>import os
os.spawnl(os.P_DETACH, 'some_long_running_command')
</code></pre>
<p>(or, alternatively, you may try the less portable <code>os.P_NOWAIT</code> flag).</p>
<p>See the <a href="https://docs.python.org/2/library/os.html#os.spawnl">documentation here</a>. </p>
| 46 | 2009-07-28T19:05:23Z | [
"python",
"process",
"daemon"
] |
How to start a background process in Python? | 1,196,074 | <p>I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>
| 135 | 2009-07-28T18:56:50Z | 1,196,162 | <p>You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):</p>
<pre><code>try:
pid = os.fork()
except OSError, e:
## some debug output
sys.exit(1)
if pid == 0:
## eventually use os.putenv(..) to set environment variables
## os.execv strips of args[0] for the arguments
os.execv(args[0], args)
</code></pre>
| 8 | 2009-07-28T19:12:06Z | [
"python",
"process",
"daemon"
] |
How to start a background process in Python? | 1,196,074 | <p>I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>
| 135 | 2009-07-28T18:56:50Z | 7,224,186 | <p>While <a href="http://stackoverflow.com/questions/1196074/starting-a-background-process-in-python/1196122#1196122">jkp</a>'s solution works, the newer way of doing things (and the way the documentation recommends) is to use the <code>subprocess</code> module. For simple commands its equivalent, but it offers more options if you want to do something complicated.</p>
<p>Example for your case:</p>
<pre><code>import subprocess
subprocess.Popen(["rm","-r","some.file"])
</code></pre>
<p>This should run <code>rm -r somefile</code> in the background. <strong>But be wary: <code>subprocess.Popen()</code> only runs a process in the background if nothing in the python script depends on the output of the command being run:</strong></p>
<p>For example, the following command will <em>not</em> run in the background:</p>
<pre><code>import subprocess
ls_output=subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
</code></pre>
<p>See the documentation <a href="http://docs.python.org/library/subprocess.html#module-subprocess">here</a>.</p>
<p>Also, a point of clarification: "Background" purely a shell concept: what you probably want is to spawn a new process. I've used "background" here to refer to shell-background-like behavior, but don't mistake this for the process actually being in the background.</p>
| 198 | 2011-08-28T21:47:04Z | [
"python",
"process",
"daemon"
] |
How to start a background process in Python? | 1,196,074 | <p>I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>
| 135 | 2009-07-28T18:56:50Z | 13,593,257 | <p>I found this <a href="http://stackoverflow.com/questions/89228/calling-an-external-command-in-python#2251026">here</a>:</p>
<p>On windows (win xp), the parent process will not finish until the <code>longtask.py</code> has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.</p>
<p>The solution is to pass <code>DETACHED_PROCESS</code> flag to the underlying <code>CreateProcess</code> function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:</p>
<pre><code>DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
</code></pre>
| 10 | 2012-11-27T21:19:09Z | [
"python",
"process",
"daemon"
] |
How to start a background process in Python? | 1,196,074 | <p>I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.</p>
| 135 | 2009-07-28T18:56:50Z | 34,459,371 | <p><a href="https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f" rel="nofollow">https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f</a></p>
<pre>
import os, time, sys, subprocess
if len(sys.argv) == 2:
time.sleep(5)
print 'track end'
if sys.platform == 'darwin':
subprocess.Popen(['say', 'hello'])
else:
print 'main begin'
subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
print 'main end'
</pre>
| 1 | 2015-12-25T01:47:55Z | [
"python",
"process",
"daemon"
] |
How to import python module in a shared folder? | 1,196,708 | <p>I have some python modules in a shared folder on a Windows machine. </p>
<p>The file is \mtl12366150\test\mymodule.py</p>
<p>os.path.exists tells me this path is valid.</p>
<p>I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).</p>
<p>When I try to import mymodule I get an error saying the module doesn't exist.</p>
<p>Is there a way to import module that are located in shared path?</p>
| 0 | 2009-07-28T21:01:47Z | 1,196,757 | <p>To import a python item there needs to be a <code>__init__.py</code> file in each of the folder above it to show that it is a valid python package.</p>
<p>The <code>__init__.py</code> files can be empty, they are there just to show structure.</p>
<pre><code>\mtl12366150
__init__.py
\test
__init__.py
\mymodule.py
</code></pre>
| 0 | 2009-07-28T21:10:12Z | [
"python",
"import",
"folder",
"shared"
] |
How to import python module in a shared folder? | 1,196,708 | <p>I have some python modules in a shared folder on a Windows machine. </p>
<p>The file is \mtl12366150\test\mymodule.py</p>
<p>os.path.exists tells me this path is valid.</p>
<p>I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).</p>
<p>When I try to import mymodule I get an error saying the module doesn't exist.</p>
<p>Is there a way to import module that are located in shared path?</p>
| 0 | 2009-07-28T21:01:47Z | 1,196,801 | <p>Did you forget to use a raw string, or escape the backslashes, in your additional sys.path component? Remember that "\t" is a tab, whereas r"\t" or "\t" are a backslash followed by a tab.</p>
<p>In most applications you are actually better off using forward slashes rather than backslashes even for Windows paths, and most Windows APIs will accept them just fine. Otherwise, be careful to use raw strings!</p>
<p>[There is no need to add __init__.py files in the directories above a simple Python module]</p>
| 1 | 2009-07-28T21:19:49Z | [
"python",
"import",
"folder",
"shared"
] |
How to import python module in a shared folder? | 1,196,708 | <p>I have some python modules in a shared folder on a Windows machine. </p>
<p>The file is \mtl12366150\test\mymodule.py</p>
<p>os.path.exists tells me this path is valid.</p>
<p>I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).</p>
<p>When I try to import mymodule I get an error saying the module doesn't exist.</p>
<p>Is there a way to import module that are located in shared path?</p>
| 0 | 2009-07-28T21:01:47Z | 1,196,815 | <p>"I appended to sys.path ..."</p>
<p>Please don't.</p>
<p>Set the <code>PYTHONPATH</code> environment variable from outside your application.</p>
| -2 | 2009-07-28T21:22:31Z | [
"python",
"import",
"folder",
"shared"
] |
How to import python module in a shared folder? | 1,196,708 | <p>I have some python modules in a shared folder on a Windows machine. </p>
<p>The file is \mtl12366150\test\mymodule.py</p>
<p>os.path.exists tells me this path is valid.</p>
<p>I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).</p>
<p>When I try to import mymodule I get an error saying the module doesn't exist.</p>
<p>Is there a way to import module that are located in shared path?</p>
| 0 | 2009-07-28T21:01:47Z | 1,196,830 | <p>You say os.path.exists() says the path is there, but are you absolutely sure you escaped the \? Try this:</p>
<pre><code>sys.path.append('\\mtl12366150\\tes')
</code></pre>
| 1 | 2009-07-28T21:25:17Z | [
"python",
"import",
"folder",
"shared"
] |
How to import python module in a shared folder? | 1,196,708 | <p>I have some python modules in a shared folder on a Windows machine. </p>
<p>The file is \mtl12366150\test\mymodule.py</p>
<p>os.path.exists tells me this path is valid.</p>
<p>I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).</p>
<p>When I try to import mymodule I get an error saying the module doesn't exist.</p>
<p>Is there a way to import module that are located in shared path?</p>
| 0 | 2009-07-28T21:01:47Z | 1,196,898 | <p>As S.Lott said, the best approach is to set the PYTHONPATH environment variable. I don't have a windows box handy, but it would look something like this from your command prompt:</p>
<pre><code>c:> SET PYTHONPATH=c:\mtl12366150\test
c:> python
>>> import mymodule
>>>
</code></pre>
| -1 | 2009-07-28T21:38:26Z | [
"python",
"import",
"folder",
"shared"
] |
How to import python module in a shared folder? | 1,196,708 | <p>I have some python modules in a shared folder on a Windows machine. </p>
<p>The file is \mtl12366150\test\mymodule.py</p>
<p>os.path.exists tells me this path is valid.</p>
<p>I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).</p>
<p>When I try to import mymodule I get an error saying the module doesn't exist.</p>
<p>Is there a way to import module that are located in shared path?</p>
| 0 | 2009-07-28T21:01:47Z | 1,200,216 | <p>I think I found the answer. I was using Python 2.6.1 and with Python 2.6.2 it now works. I had the same faulty behavior with python 2.5.4.</p>
| 0 | 2009-07-29T13:21:13Z | [
"python",
"import",
"folder",
"shared"
] |
Passing a Django model attribute name to a function | 1,197,042 | <p>I'd like to build a function in Django that iterates over a set of objects in a queryset and does something based on the value of an arbitrary attribute. The type of the objects is fixed; let's say they're guaranteed to be from the Comment model, which looks like this:</p>
<pre><code>class Comment(models.Model):
name = models.CharField(max_length=255)
text = models.TextField()
email = models.EmailField()
</code></pre>
<p>Sometimes I'll want to do run the function over the <code>name</code>s, but other times the <code>email</code>s. I'd like to know how to write and call a function that looks like this:</p>
<pre><code>def do_something(attribute, objects):
for object in objects:
# do something with the object based on object.attribute
return results
</code></pre>
| 1 | 2009-07-28T22:12:15Z | 1,197,061 | <p>You don't make clear what you want to return from your function, so substitute a suitable <code>return</code> statement. I assume <code>attribute</code> will be set to one of "name", "text" or "email".</p>
<pre><code>def do_something(attribute, objects):
for o in objects:
print getattr(o, attribute)
return something
</code></pre>
<p><strong>Update:</strong> OK, you've updated the question. Cide's answer makes the most sense now.</p>
| 1 | 2009-07-28T22:16:43Z | [
"python",
"django"
] |
Passing a Django model attribute name to a function | 1,197,042 | <p>I'd like to build a function in Django that iterates over a set of objects in a queryset and does something based on the value of an arbitrary attribute. The type of the objects is fixed; let's say they're guaranteed to be from the Comment model, which looks like this:</p>
<pre><code>class Comment(models.Model):
name = models.CharField(max_length=255)
text = models.TextField()
email = models.EmailField()
</code></pre>
<p>Sometimes I'll want to do run the function over the <code>name</code>s, but other times the <code>email</code>s. I'd like to know how to write and call a function that looks like this:</p>
<pre><code>def do_something(attribute, objects):
for object in objects:
# do something with the object based on object.attribute
return results
</code></pre>
| 1 | 2009-07-28T22:12:15Z | 1,197,086 | <pre><code>def do_something(attribute, objects):
results = []
for object in objects:
if hasattr(object, attribute):
results.append(getattr(object, attribute))
return results
</code></pre>
<p>Or, more succinctly,</p>
<pre><code>def do_something(attribute, objects):
return [getattr(o, attribute) for o in objects if hasattr(o, attribute)]
</code></pre>
| 4 | 2009-07-28T22:22:19Z | [
"python",
"django"
] |
Passing a Django model attribute name to a function | 1,197,042 | <p>I'd like to build a function in Django that iterates over a set of objects in a queryset and does something based on the value of an arbitrary attribute. The type of the objects is fixed; let's say they're guaranteed to be from the Comment model, which looks like this:</p>
<pre><code>class Comment(models.Model):
name = models.CharField(max_length=255)
text = models.TextField()
email = models.EmailField()
</code></pre>
<p>Sometimes I'll want to do run the function over the <code>name</code>s, but other times the <code>email</code>s. I'd like to know how to write and call a function that looks like this:</p>
<pre><code>def do_something(attribute, objects):
for object in objects:
# do something with the object based on object.attribute
return results
</code></pre>
| 1 | 2009-07-28T22:12:15Z | 1,197,088 | <p>If you're only doing stuff with a single attribute, you can use .values_list(), which is more performant since you're not instantiating whole objects, and you're only pulling the specific value you're using from the database.</p>
<pre><code>>>> def do_something(values):
... for value in values:
... print value
... return something
...
>>> emails = Comment.objects.values_list('email', flat=True)
>>> names = Comment.objects.values_list('name', flat=True)
>>> do_something(emails) # Prints all email addresses
>>> do_something(names) # Prints all names
</code></pre>
| 4 | 2009-07-28T22:22:29Z | [
"python",
"django"
] |
How can I take a screenshot/image of a website using Python? | 1,197,172 | <p>What I want to achieve is to get a website screenshot from any website in python.</p>
<p>Env: Linux</p>
| 26 | 2009-07-28T22:48:13Z | 1,197,292 | <p>You don't mention what environment you're running in, which makes a big difference because there isn't a pure Python web browser that's capable of rendering HTML.</p>
<p>But if you're using a Mac, I've used <a href="http://www.paulhammond.org/webkit2png/" rel="nofollow">webkit2png</a> with great success. If not, as others have pointed out there are plenty of options.</p>
| 0 | 2009-07-28T23:28:08Z | [
"python",
"screenshot",
"webpage",
"backend"
] |
How can I take a screenshot/image of a website using Python? | 1,197,172 | <p>What I want to achieve is to get a website screenshot from any website in python.</p>
<p>Env: Linux</p>
| 26 | 2009-07-28T22:48:13Z | 1,197,604 | <p>On the Mac, there's <a href="http://www.paulhammond.org/webkit2png/">webkit2png</a> and on Linux+KDE, you can use <a href="http://khtml2png.sourceforge.net/">khtml2png</a>. I've tried the former and it works quite well, and heard of the latter being put to use. </p>
<p>I recently came across <a href="http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/">QtWebKit</a> which claims to be cross platform (Qt rolled WebKit into their library, I guess). But I've never tried it, so I can't tell you much more.</p>
<p>The QtWebKit links shows how to access from Python. You should be able to at least use subprocess to do the same with the others.</p>
| 7 | 2009-07-29T01:12:48Z | [
"python",
"screenshot",
"webpage",
"backend"
] |
How can I take a screenshot/image of a website using Python? | 1,197,172 | <p>What I want to achieve is to get a website screenshot from any website in python.</p>
<p>Env: Linux</p>
| 26 | 2009-07-28T22:48:13Z | 1,198,024 | <p>I can't comment on ars's answer, but I actually got <a href="http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/" rel="nofollow">Roland Tapken's code</a> running using QtWebkit and it works quite well. </p>
<p>Just wanted to confirm that what Roland posts on his blog works great on Ubuntu. Our production version ended up not using any of what he wrote but we are using the PyQt/QtWebKit bindings with much success.</p>
| 5 | 2009-07-29T04:19:46Z | [
"python",
"screenshot",
"webpage",
"backend"
] |
How can I take a screenshot/image of a website using Python? | 1,197,172 | <p>What I want to achieve is to get a website screenshot from any website in python.</p>
<p>Env: Linux</p>
| 26 | 2009-07-28T22:48:13Z | 12,031,316 | <p>Here is a simple solution using webkit:
<a href="http://webscraping.com/blog/Webpage-screenshots-with-webkit/">http://webscraping.com/blog/Webpage-screenshots-with-webkit/</a></p>
<pre><code>import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class Screenshot(QWebView):
def __init__(self):
self.app = QApplication(sys.argv)
QWebView.__init__(self)
self._loaded = False
self.loadFinished.connect(self._loadFinished)
def capture(self, url, output_file):
self.load(QUrl(url))
self.wait_load()
# set to webpage size
frame = self.page().mainFrame()
self.page().setViewportSize(frame.contentsSize())
# render image
image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
frame.render(painter)
painter.end()
print 'saving', output_file
image.save(output_file)
def wait_load(self, delay=0):
# process app events until page loaded
while not self._loaded:
self.app.processEvents()
time.sleep(delay)
self._loaded = False
def _loadFinished(self, result):
self._loaded = True
s = Screenshot()
s.capture('http://webscraping.com', 'website.png')
s.capture('http://webscraping.com/blog', 'blog.png')
</code></pre>
| 29 | 2012-08-20T01:21:49Z | [
"python",
"screenshot",
"webpage",
"backend"
] |
How can I take a screenshot/image of a website using Python? | 1,197,172 | <p>What I want to achieve is to get a website screenshot from any website in python.</p>
<p>Env: Linux</p>
| 26 | 2009-07-28T22:48:13Z | 18,068,097 | <p>Here is my solution by grabbing help from various sources. It takes full web page screen capture and it crops it (optional) and generates thumbnail from the cropped image also. Following are the requirements:</p>
<p>Requirements:</p>
<ol>
<li>Install NodeJS</li>
<li>Using Node's package manager install phantomjs: <code>npm -g install phantomjs</code></li>
<li>Install selenium (in your virtualenv, if you are using that)</li>
<li>Install imageMagick</li>
<li>Add phantomjs to system path (on windows)</li>
</ol>
<hr>
<pre><code>import os
from subprocess import Popen, PIPE
from selenium import webdriver
abspath = lambda *p: os.path.abspath(os.path.join(*p))
ROOT = abspath(os.path.dirname(__file__))
def execute_command(command):
result = Popen(command, shell=True, stdout=PIPE).stdout.read()
if len(result) > 0 and not result.isspace():
raise Exception(result)
def do_screen_capturing(url, screen_path, width, height):
print "Capturing screen.."
driver = webdriver.PhantomJS()
# it save service log file in same directory
# if you want to have log file stored else where
# initialize the webdriver.PhantomJS() as
# driver = webdriver.PhantomJS(service_log_path='/var/log/phantomjs/ghostdriver.log')
driver.set_script_timeout(30)
if width and height:
driver.set_window_size(width, height)
driver.get(url)
driver.save_screenshot(screen_path)
def do_crop(params):
print "Croping captured image.."
command = [
'convert',
params['screen_path'],
'-crop', '%sx%s+0+0' % (params['width'], params['height']),
params['crop_path']
]
execute_command(' '.join(command))
def do_thumbnail(params):
print "Generating thumbnail from croped captured image.."
command = [
'convert',
params['crop_path'],
'-filter', 'Lanczos',
'-thumbnail', '%sx%s' % (params['width'], params['height']),
params['thumbnail_path']
]
execute_command(' '.join(command))
def get_screen_shot(**kwargs):
url = kwargs['url']
width = int(kwargs.get('width', 1024)) # screen width to capture
height = int(kwargs.get('height', 768)) # screen height to capture
filename = kwargs.get('filename', 'screen.png') # file name e.g. screen.png
path = kwargs.get('path', ROOT) # directory path to store screen
crop = kwargs.get('crop', False) # crop the captured screen
crop_width = int(kwargs.get('crop_width', width)) # the width of crop screen
crop_height = int(kwargs.get('crop_height', height)) # the height of crop screen
crop_replace = kwargs.get('crop_replace', False) # does crop image replace original screen capture?
thumbnail = kwargs.get('thumbnail', False) # generate thumbnail from screen, requires crop=True
thumbnail_width = int(kwargs.get('thumbnail_width', width)) # the width of thumbnail
thumbnail_height = int(kwargs.get('thumbnail_height', height)) # the height of thumbnail
thumbnail_replace = kwargs.get('thumbnail_replace', False) # does thumbnail image replace crop image?
screen_path = abspath(path, filename)
crop_path = thumbnail_path = screen_path
if thumbnail and not crop:
raise Exception, 'Thumnail generation requires crop image, set crop=True'
do_screen_capturing(url, screen_path, width, height)
if crop:
if not crop_replace:
crop_path = abspath(path, 'crop_'+filename)
params = {
'width': crop_width, 'height': crop_height,
'crop_path': crop_path, 'screen_path': screen_path}
do_crop(params)
if thumbnail:
if not thumbnail_replace:
thumbnail_path = abspath(path, 'thumbnail_'+filename)
params = {
'width': thumbnail_width, 'height': thumbnail_height,
'thumbnail_path': thumbnail_path, 'crop_path': crop_path}
do_thumbnail(params)
return screen_path, crop_path, thumbnail_path
if __name__ == '__main__':
'''
Requirements:
Install NodeJS
Using Node's package manager install phantomjs: npm -g install phantomjs
install selenium (in your virtualenv, if you are using that)
install imageMagick
add phantomjs to system path (on windows)
'''
url = 'http://stackoverflow.com/questions/1197172/how-can-i-take-a-screenshot-image-of-a-website-using-python'
screen_path, crop_path, thumbnail_path = get_screen_shot(
url=url, filename='sof.png',
crop=True, crop_replace=False,
thumbnail=True, thumbnail_replace=False,
thumbnail_width=200, thumbnail_height=150,
)
</code></pre>
<p>These are the generated images:</p>
<ul>
<li><a href="http://i.imgur.com/A54lvMG.png?1">Full web page screen</a></li>
<li><a href="http://i.imgur.com/GtoVRU2.png?1">Cropped image from captured screen</a></li>
<li><a href="http://i.imgur.com/yRQqLM3.png?1">Thumbnail of a cropped image</a></li>
</ul>
| 24 | 2013-08-05T21:30:57Z | [
"python",
"screenshot",
"webpage",
"backend"
] |
How can I take a screenshot/image of a website using Python? | 1,197,172 | <p>What I want to achieve is to get a website screenshot from any website in python.</p>
<p>Env: Linux</p>
| 26 | 2009-07-28T22:48:13Z | 20,045,102 | <p>Try this.. </p>
<pre><code>#!/usr/bin/env python
import gtk.gdk
import time
import random
while 1 :
# generate a random time between 120 and 300 sec
random_time = random.randrange(120,300)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
print "Next picture in: %.2f minutes" % (float(random_time) / 60)
time.sleep(random_time)
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
ts = time.time()
filename = "screenshot"
filename += str(ts)
filename += ".png"
if (pb != None):
pb.save(filename,"png")
print "Screenshot saved to "+filename
else:
print "Unable to get the screenshot."
</code></pre>
| -1 | 2013-11-18T10:09:39Z | [
"python",
"screenshot",
"webpage",
"backend"
] |
Matching blank lines with regular expressions | 1,197,600 | <p>I've got a string that I'm trying to split into chunks based on blank lines.</p>
<p>Given a string <code>s</code>, I thought I could do this:</p>
<pre><code>re.split('(?m)^\s*$', s)
</code></pre>
<p>This works in some cases:</p>
<pre><code>>>> s = 'foo\nbar\n \nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n', '\nbaz']
</code></pre>
<p>But it doesn't work if the line is completely empty:</p>
<pre><code>>>> s = 'foo\nbar\n\nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n\nbaz']
</code></pre>
<p>What am I doing wrong?</p>
<p>[python 2.5; no difference if I compile <code>'^\s*$'</code> with <code>re.MULTILINE</code> and use the compiled expression instead]</p>
| 5 | 2009-07-29T01:12:14Z | 1,197,638 | <p>What you're doing wrong is using regular expressions. What is wrong with ('Some\ntext.').split('\n')?</p>
| -1 | 2009-07-29T01:29:14Z | [
"python",
"regex"
] |
Matching blank lines with regular expressions | 1,197,600 | <p>I've got a string that I'm trying to split into chunks based on blank lines.</p>
<p>Given a string <code>s</code>, I thought I could do this:</p>
<pre><code>re.split('(?m)^\s*$', s)
</code></pre>
<p>This works in some cases:</p>
<pre><code>>>> s = 'foo\nbar\n \nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n', '\nbaz']
</code></pre>
<p>But it doesn't work if the line is completely empty:</p>
<pre><code>>>> s = 'foo\nbar\n\nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n\nbaz']
</code></pre>
<p>What am I doing wrong?</p>
<p>[python 2.5; no difference if I compile <code>'^\s*$'</code> with <code>re.MULTILINE</code> and use the compiled expression instead]</p>
| 5 | 2009-07-29T01:12:14Z | 1,197,642 | <p>Try this instead:</p>
<pre><code>re.split('\n\s*\n', s)
</code></pre>
<p>The problem is that "$ *^" actually only matches "spaces (if any) that are alone on a line"--not the newlines themselves. This leaves the delimiter empty when there's nothing on the line, which doesn't make sense.</p>
<p>This version also gets rid of the delimiting newlines themselves, which is probably what you want. Otherwise, you'll have the newlines stuck to the beginning and end of each split part.</p>
<p>Treating multiple consecutive blank lines as defining an empty block ("abc\n\n\ndef" -> ["abc", "", "def"]) is trickier...</p>
| 16 | 2009-07-29T01:29:46Z | [
"python",
"regex"
] |
Matching blank lines with regular expressions | 1,197,600 | <p>I've got a string that I'm trying to split into chunks based on blank lines.</p>
<p>Given a string <code>s</code>, I thought I could do this:</p>
<pre><code>re.split('(?m)^\s*$', s)
</code></pre>
<p>This works in some cases:</p>
<pre><code>>>> s = 'foo\nbar\n \nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n', '\nbaz']
</code></pre>
<p>But it doesn't work if the line is completely empty:</p>
<pre><code>>>> s = 'foo\nbar\n\nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n\nbaz']
</code></pre>
<p>What am I doing wrong?</p>
<p>[python 2.5; no difference if I compile <code>'^\s*$'</code> with <code>re.MULTILINE</code> and use the compiled expression instead]</p>
| 5 | 2009-07-29T01:12:14Z | 1,197,644 | <p>Is this what you want?</p>
<pre><code>>>> s = 'foo\nbar\n\nbaz'
>>> re.split('\n\s*\n',s)
['foo\nbar', 'baz']
>>> s = 'foo\nbar\n \nbaz'
>>> re.split('\n\s*\n',s)
['foo\nbar', 'baz']
>>> s = 'foo\nbar\n\t\nbaz'
>>> re.split('\n\s*\n',s)
['foo\nbar', 'baz']
</code></pre>
| 0 | 2009-07-29T01:31:11Z | [
"python",
"regex"
] |
Matching blank lines with regular expressions | 1,197,600 | <p>I've got a string that I'm trying to split into chunks based on blank lines.</p>
<p>Given a string <code>s</code>, I thought I could do this:</p>
<pre><code>re.split('(?m)^\s*$', s)
</code></pre>
<p>This works in some cases:</p>
<pre><code>>>> s = 'foo\nbar\n \nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n', '\nbaz']
</code></pre>
<p>But it doesn't work if the line is completely empty:</p>
<pre><code>>>> s = 'foo\nbar\n\nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n\nbaz']
</code></pre>
<p>What am I doing wrong?</p>
<p>[python 2.5; no difference if I compile <code>'^\s*$'</code> with <code>re.MULTILINE</code> and use the compiled expression instead]</p>
| 5 | 2009-07-29T01:12:14Z | 15,831,927 | <p>The re library can split on one or more empty lines ! An empty line is a string that consists of zero or more whitespaces, starts at the start of the line and ends at the end of a line. Special character '$' matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline (excerpt from <a href="http://docs.python.org/2/library/re.html" rel="nofollow">docs</a>). That's why we need to add a special character '\s*' for the line break. Everything is possible :-)</p>
<pre><code>>>> import re
>>> text = "foo\n \n \n \nbar\n"
>>> re.split("(?m)^\s*$\s*", text)
['foo\n', 'bar\n']
</code></pre>
<p>The same regex works with windows style line breaks.</p>
<pre><code>>>> import re
>>> text = "foo\r\n \r\n \r\n \r\nbar\r\n"
>>> re.split("(?m)^\s*$\s*", text)
['foo\r\n', 'bar\r\n']
</code></pre>
| 1 | 2013-04-05T10:46:27Z | [
"python",
"regex"
] |
Matching blank lines with regular expressions | 1,197,600 | <p>I've got a string that I'm trying to split into chunks based on blank lines.</p>
<p>Given a string <code>s</code>, I thought I could do this:</p>
<pre><code>re.split('(?m)^\s*$', s)
</code></pre>
<p>This works in some cases:</p>
<pre><code>>>> s = 'foo\nbar\n \nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n', '\nbaz']
</code></pre>
<p>But it doesn't work if the line is completely empty:</p>
<pre><code>>>> s = 'foo\nbar\n\nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n\nbaz']
</code></pre>
<p>What am I doing wrong?</p>
<p>[python 2.5; no difference if I compile <code>'^\s*$'</code> with <code>re.MULTILINE</code> and use the compiled expression instead]</p>
| 5 | 2009-07-29T01:12:14Z | 33,071,992 | <p><strong>Try this:</strong></p>
<pre><code>blank=''
with open('fu.txt') as txt:
txt=txt.read().split('\n')
for line in txt:
if line is blank: print('blank')
else: print(line)
</code></pre>
| 0 | 2015-10-12T01:34:08Z | [
"python",
"regex"
] |
CopyBlock tag for Django | 1,197,650 | <p>How can I write a tag "copyblock" for Django templates?</p>
<p>For such a function:</p>
<pre><code><title> {% block title %} some title... {% endblock %} </title>
<h1>{% copyblock title %}</h1>
</code></pre>
| 0 | 2009-07-29T01:32:34Z | 1,197,694 | <p>Take a look at the solutions mentioned in this question:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/511067/how-to-repeat-a-block-in-a-django-template">http://stackoverflow.com/questions/511067/how-to-repeat-a-block-in-a-django-template</a></li>
</ul>
| 1 | 2009-07-29T01:48:15Z | [
"python",
"django",
"templates",
"django-templates"
] |
CopyBlock tag for Django | 1,197,650 | <p>How can I write a tag "copyblock" for Django templates?</p>
<p>For such a function:</p>
<pre><code><title> {% block title %} some title... {% endblock %} </title>
<h1>{% copyblock title %}</h1>
</code></pre>
| 0 | 2009-07-29T01:32:34Z | 1,197,722 | <p>Django's template parser doesn't expose blocks by name. Instead, they are organized into a tree structure in the Django <code>Template</code>'s <code>nodelist</code>, with rendering <code>push</code>ing and <code>pop</code>ping on the stack of template nodes. You'll have a nearly impossible time accessing them in the way your example indicates.</p>
<p>The SO link that ars references provides suggestions on the best solutions. Of those solutions, defining a variable in the context (ie: <code>{{ title }}</code> in the spirit of your example) that can be reused is probably the most straightforward and maintainable approach. If the piece you want to duplicate goes beyond a simple variable, a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags" rel="nofollow">custom template tag</a> is probably the most appealing option.</p>
| 1 | 2009-07-29T02:02:50Z | [
"python",
"django",
"templates",
"django-templates"
] |
Actions triggered by field change in Django | 1,197,674 | <p>How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:</p>
<pre><code>class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
</code></pre>
<p>and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.</p>
<p>I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.</p>
<p><strong>Update:</strong> I've added the following to my Game class:</p>
<pre><code> def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
</code></pre>
| 19 | 2009-07-29T01:42:07Z | 1,197,708 | <p>Django has a nifty feature called <a href="http://docs.djangoproject.com/en/dev/topics/signals/">signals</a>, which are effectively triggers that are set off at specific times:</p>
<ul>
<li>Before/after a model's save method is called</li>
<li>Before/after a model's delete method is called</li>
<li>Before/after an HTTP request is made</li>
</ul>
<p>Read the docs for full info, but all you need to do is create a receiver function and register it as a signal. This is usually done in models.py.</p>
<pre><code>from django.core.signals import request_finished
def my_callback(sender, **kwargs):
print "Request finished!"
request_finished.connect(my_callback)
</code></pre>
<p>Simple, eh?</p>
| 11 | 2009-07-29T01:56:36Z | [
"python",
"django",
"django-models"
] |
Actions triggered by field change in Django | 1,197,674 | <p>How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:</p>
<pre><code>class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
</code></pre>
<p>and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.</p>
<p>I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.</p>
<p><strong>Update:</strong> I've added the following to my Game class:</p>
<pre><code> def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
</code></pre>
| 19 | 2009-07-29T01:42:07Z | 1,197,738 | <p>Basically, you need to override the <code>save</code> method, check if the <code>state</code> field was changed, set <code>started</code> if needed and then let the model base class finish persisting to the database.</p>
<p>The tricky part is figuring out if the field was changed. Check out the mixins and other solutions in this question to help you out with this:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/110803/dirty-fields-in-django">http://stackoverflow.com/questions/110803/dirty-fields-in-django</a></li>
</ul>
| 8 | 2009-07-29T02:07:19Z | [
"python",
"django",
"django-models"
] |
Actions triggered by field change in Django | 1,197,674 | <p>How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:</p>
<pre><code>class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
</code></pre>
<p>and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.</p>
<p>I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.</p>
<p><strong>Update:</strong> I've added the following to my Game class:</p>
<pre><code> def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
</code></pre>
| 19 | 2009-07-29T01:42:07Z | 1,198,061 | <p>One way is to add a setter for the state. It's just a normal method, nothing special.</p>
<pre><code>class Game(models.Model):
# ... other code
def set_state(self, newstate):
if self.state != newstate:
oldstate = self.state
self.state = newstate
if oldstate == 'S' and newstate == 'A':
self.started = datetime.now()
# create units, etc.
</code></pre>
<p><strong>Update:</strong> If you want this to be triggered <em>whenever</em> a change is made to a model instance, you can (<em>instead</em> of <code>set_state</code> above) use a <code>__setattr__</code> method in <code>Game</code> which is something like this:</p>
<pre><code>def __setattr__(self, name, value):
if name != "state":
object.__setattr__(self, name, value)
else:
if self.state != value:
oldstate = self.state
object.__setattr__(self, name, value) # use base class setter
if oldstate == 'S' and value == 'A':
self.started = datetime.now()
# create units, etc.
</code></pre>
<p>Note that you wouldn't especially find this in the Django docs, as it (<code>__setattr__</code>) is a standard Python feature, documented <a href="http://docs.python.org/reference/datamodel.html?highlight=__setattr__#object.__setattr__" rel="nofollow">here</a>, and is not Django-specific.</p>
<p>note: Don't know about versions of django older than 1.2, but this code using <code>__setattr__</code> won't work, it'll fail just after the second <code>if</code>, when trying to access <code>self.state</code>.</p>
<p>I tried something similar, and I tried to fix this problem by forcing the initialization of <code>state</code> (first in <code>__init__</code> then ) in <code>__new__</code> but this will lead to nasty unexpected behaviour.</p>
<p>I'm editing instead of commenting for obvious reasons, also: I'm not deleting this piece of code since maybe it could work with older (or future?) versions of django, and there may be another workaround to the <code>self.state</code> problem that i'm unaware of</p>
| 5 | 2009-07-29T04:35:04Z | [
"python",
"django",
"django-models"
] |
Actions triggered by field change in Django | 1,197,674 | <p>How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:</p>
<pre><code>class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
</code></pre>
<p>and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.</p>
<p>I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.</p>
<p><strong>Update:</strong> I've added the following to my Game class:</p>
<pre><code> def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
</code></pre>
| 19 | 2009-07-29T01:42:07Z | 14,226,105 | <p>@dcramer came up with a more elegant solution (in my opinion) for this issue.</p>
<p><a href="https://gist.github.com/730765" rel="nofollow">https://gist.github.com/730765</a></p>
<pre class="lang-py prettyprint-override"><code>from django.db.models.signals import post_init
def track_data(*fields):
"""
Tracks property changes on a model instance.
The changed list of properties is refreshed on model initialization
and save.
>>> @track_data('name')
>>> class Post(models.Model):
>>> name = models.CharField(...)
>>>
>>> @classmethod
>>> def post_save(cls, sender, instance, created, **kwargs):
>>> if instance.has_changed('name'):
>>> print "Hooray!"
"""
UNSAVED = dict()
def _store(self):
"Updates a local copy of attributes values"
if self.id:
self.__data = dict((f, getattr(self, f)) for f in fields)
else:
self.__data = UNSAVED
def inner(cls):
# contains a local copy of the previous values of attributes
cls.__data = {}
def has_changed(self, field):
"Returns ``True`` if ``field`` has changed since initialization."
if self.__data is UNSAVED:
return False
return self.__data.get(field) != getattr(self, field)
cls.has_changed = has_changed
def old_value(self, field):
"Returns the previous value of ``field``"
return self.__data.get(field)
cls.old_value = old_value
def whats_changed(self):
"Returns a list of changed attributes."
changed = {}
if self.__data is UNSAVED:
return changed
for k, v in self.__data.iteritems():
if v != getattr(self, k):
changed[k] = v
return changed
cls.whats_changed = whats_changed
# Ensure we are updating local attributes on model init
def _post_init(sender, instance, **kwargs):
_store(instance)
post_init.connect(_post_init, sender=cls, weak=False)
# Ensure we are updating local attributes on model save
def save(self, *args, **kwargs):
save._original(self, *args, **kwargs)
_store(self)
save._original = cls.save
cls.save = save
return cls
return inner
</code></pre>
| 3 | 2013-01-08T23:51:43Z | [
"python",
"django",
"django-models"
] |
Actions triggered by field change in Django | 1,197,674 | <p>How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:</p>
<pre><code>class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
</code></pre>
<p>and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.</p>
<p>I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.</p>
<p><strong>Update:</strong> I've added the following to my Game class:</p>
<pre><code> def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
</code></pre>
| 19 | 2009-07-29T01:42:07Z | 25,503,326 | <p>It has been answered, but here's an example of using signals, post_init and post_save.</p>
<pre><code>class MyModel(models.Model):
state = models.IntegerField()
previous_state = None
@staticmethod
def post_save(sender, **kwargs):
instance = kwargs.get('instance')
created = kwargs.get('created')
if instance.previous_state != instance.state or created:
do_something_with_state_change()
@staticmethod
def remember_state(sender, **kwargs):
instance = kwargs.get('instance')
instance.previous_state = instance.state
post_save.connect(MyModel.post_save, sender=MyModel)
post_init.connect(MyModel.remember_state, sender=MyModel)
</code></pre>
| 6 | 2014-08-26T10:15:19Z | [
"python",
"django",
"django-models"
] |
Convert html entities to ascii in Python | 1,197,981 | <p>I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. </p>
<p>Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.</p>
<p>Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.</p>
| 4 | 2009-07-29T04:00:35Z | 1,198,002 | <p>ASCII is the American Standard Code for Information Interchange and does <strong>not</strong> include any accented letters. Your best bet is to get Unicode (as you say you can) and encode it as UTF-8 (maybe ISO-8859-1 or some weird codepage if you're dealing with seriously badly coded user-agents/clients, sigh) -- the content type header of that part together with text/plain can express what encoding you've chosen to use (I do recommend trying UTF-8 unless you have positively demonstrated it cannot work -- it's <em>almost</em> universally supported these days and MUCH more flexible than any ISO-8859 or "codepage" hack!).</p>
| 2 | 2009-07-29T04:10:44Z | [
"python",
"ascii"
] |
Convert html entities to ascii in Python | 1,197,981 | <p>I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. </p>
<p>Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.</p>
<p>Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.</p>
| 4 | 2009-07-29T04:00:35Z | 1,198,004 | <p>You can use the <a href="http://docs.python.org/library/htmllib.html#module-htmlentitydefs" rel="nofollow">htmlentitydefs</a> package:</p>
<pre><code>import htmlentitydefs
print htmlentitydefs.entitydefs['aacute']
</code></pre>
<p>Basically, <code>entitydefs</code> is just a dictionary, and you can see this by printing it at the python prompt:</p>
<pre><code>from pprint import pprint
pprint htmlentitydefs.entitydefs
</code></pre>
| 1 | 2009-07-29T04:10:45Z | [
"python",
"ascii"
] |
Convert html entities to ascii in Python | 1,197,981 | <p>I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. </p>
<p>Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.</p>
<p>Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.</p>
| 4 | 2009-07-29T04:00:35Z | 1,582,036 | <p>Here is a complete implementation that also handles unicode html entities. You might find it useful.</p>
<p>It returns a unicode string that is not ascii, but if you want plain ascii, you can modify the replace operations so that it replaces the entities to empty string.</p>
<pre><code>def convert_html_entities(s):
matches = re.findall("&#\d+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
name = hit[2:-1]
try:
entnum = int(name)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&#[xX][0-9a-fA-F]+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
hex = hit[3:-1]
try:
entnum = int(hex, 16)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&\w+;", s)
hits = set(matches)
amp = "&amp;"
if amp in hits:
hits.remove(amp)
for hit in hits:
name = hit[1:-1]
if htmlentitydefs.name2codepoint.has_key(name):
s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
s = s.replace(amp, "&")
return s
</code></pre>
<p>Edit: added matching for hexcodes. I've been using this for a while now, and ran into my first situation with ' which is a single quote/apostrophe.</p>
| 8 | 2009-10-17T11:53:40Z | [
"python",
"ascii"
] |
Convert html entities to ascii in Python | 1,197,981 | <p>I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. </p>
<p>Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII.</p>
<p>Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.</p>
| 4 | 2009-07-29T04:00:35Z | 3,429,309 | <p>We put up a little module with agazso's function:</p>
<p><a href="http://github.com/ARTFL/util/blob/master/ents.py" rel="nofollow">http://github.com/ARTFL/util/blob/master/ents.py</a></p>
<p>We find agazso's function to faster than the alternatives for ent conversion. Thanks for posting it.</p>
| 0 | 2010-08-07T05:56:44Z | [
"python",
"ascii"
] |
Why is wxGridSizer much slower to initialize on a wxDialog then on a wxFrame? | 1,198,067 | <p>It seems that this is specific to windows, here is an example that reproduces the effect:</p>
<pre><code>import wx
def makegrid(window):
grid = wx.GridSizer(24, 10, 1, 1)
window.SetSizer(grid)
for i in xrange(240):
cell = wx.Panel(window)
cell.SetBackgroundColour(wx.Color(i, i, i))
grid.Add(cell, flag=wx.EXPAND)
class TestFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
makegrid(self)
class TestDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent)
makegrid(self)
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
btn1 = wx.Button(self, label="Show Frame")
btn2 = wx.Button(self, label="Show Dialog")
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
sizer.Add(btn1, flag=wx.EXPAND)
sizer.Add(btn2, flag=wx.EXPAND)
btn1.Bind(wx.EVT_BUTTON, self.OnShowFrame)
btn2.Bind(wx.EVT_BUTTON, self.OnShowDialog)
def OnShowFrame(self, event):
TestFrame(self).Show()
def OnShowDialog(self, event):
TestDialog(self).ShowModal()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
</code></pre>
<p>I have tried this on the following configurations:</p>
<ul>
<li>Windows 7 with Python 2.5.4 and wxPython 2.8.10.1</li>
<li>Windows XP with Python 2.5.2 and wxPython 2.8.7.1</li>
<li>Windows XP with Python 2.6.0 and wxPython 2.8.9.1</li>
<li>Ubuntu 9.04 with Python 2.6.2 and wxPython 2.8.9.1</li>
</ul>
<p>The wxDialog wasn't slow only on Ubuntu.</p>
| 2 | 2009-07-29T04:36:47Z | 1,204,886 | <p>I got a reply on the <a href="http://groups.google.com/group/wxPython-users/browse_thread/thread/66762899a9f3b697#" rel="nofollow">wxPython-users mailing list</a>, the problem can be fixed by calling <code>Layout</code> explicitly before the dialog is shown.</p>
<blockquote>
<p>This is really weird...</p>
<p>My guess is that this is due to
Windows and wxWidgets not dealing very
well with overlapping siblings, and so
when the sizer is doing the initial
layout and moving all the panels from
(0,0) to where they need to be that
something about the dialog is causing
all of them to be refreshed and
repainted at each move. If you
instead do the initial layout before
the dialog is shown then it is just as
fast as the frame.</p>
<p>You can do this by adding a call to window.Layout() at the end of
makegrid.</p>
<p>-- Robin Dunn</p>
</blockquote>
| 2 | 2009-07-30T06:58:31Z | [
"python",
"windows",
"wxpython"
] |
Python: How to get rid of circular dependency involving decorator? | 1,198,188 | <p>I had got a following case of circular import (here severly simplified):</p>
<p><code>array2image.py</code> conversion module:</p>
<pre><code>import tuti
@tuti.log_exec_time # can't do that, evaluated at definition time
def convert(arr):
'''Convert array to image.'''
return image.fromarray(arr)
</code></pre>
<p><code>tuti.py</code> test utils module:</p>
<pre><code>import array2image
def log_exec_time(f):
'''A small decorator not using array2image'''
def debug_image(arr):
image = array2image.convert(arr)
image = write('somewhere')
</code></pre>
<p>It failed with NameError. This didn't look right to me, as there was really no circular dependency there. I was looking for a <em>neat</em> way to avoid that or an explanation... and half way through writing this question I found it.</p>
<p>Moving the <code>import</code> below the decorator in <code>tuti.py</code> resolves NameError:</p>
<pre><code>def log_exec_time(f):
'''A small decorator not using array2image'''
import array2image
def debug_image(arr):
image = array2image.convert(arr)
image = write('somewhere')
</code></pre>
| 1 | 2009-07-29T05:31:20Z | 1,198,225 | <p>The answer you came up with is a valid solution. </p>
<p>However, if you were that worried about circular dependencies, I would say that log_exec_time would belong in its own file since its not dependent on anything else in tuti.py.</p>
| 4 | 2009-07-29T05:45:20Z | [
"python",
"import",
"decorator",
"circular"
] |
Tkinter locks python when Icon loaded and tk.mainloop in a thread | 1,198,262 | <p>Here's the test case...</p>
<pre>
import Tkinter as tk
import thread
from time import sleep
if __name__ == '__main__':
t = tk.Tk()
thread.start_new_thread(t.mainloop, ())
# t.iconbitmap('icon.ico')
b = tk.Button(text='test', command=exit)
b.grid(row=0)
while 1:
sleep(1)
</pre>
<p>This code works. Uncomment the t.iconbitmap line and it locks. Re-arrange it any way you like, it will lock.</p>
<p>Does anyone know how to prevent tk.mainloop locking the GIL when there is an icon present?</p>
<p>Target is win32, py2.6.2.</p>
| 5 | 2009-07-29T05:57:59Z | 1,198,288 | <p>I believe you should not execute the main loop on a different thread. AFAIK, the main loop should be executed on the same thread that created the widget. </p>
<p>The GUI toolkits that I am familiar with (Tkinter, .NET Windows Forms) are that way: You can manipulate the GUI from one thread only.</p>
<p>On Linux, your code raises an exception:</p>
<pre>
self.tk.mainloop(n)
RuntimeError: Calling Tcl from different appartment
</pre>
<p>One of the following will work (no extra threads):</p>
<pre><code>if __name__ == '__main__':
t = tk.Tk()
t.iconbitmap('icon.ico')
b = tk.Button(text='test', command=exit)
b.grid(row=0)
t.mainloop()
</code></pre>
<p>With extra thread:</p>
<pre><code>def threadmain():
t = tk.Tk()
t.iconbitmap('icon.ico')
b = tk.Button(text='test', command=exit)
b.grid(row=0)
t.mainloop()
if __name__ == '__main__':
thread.start_new_thread(threadmain, ())
while 1:
sleep(1)
</code></pre>
<hr>
<p>If you need to do communicate with tkinter from outside the tkinter thread, I suggest you set up a timer that checks a queue for work.</p>
<p>Here is an example:</p>
<pre><code>import Tkinter as tk
import thread
from time import sleep
import Queue
request_queue = Queue.Queue()
result_queue = Queue.Queue()
def submit_to_tkinter(callable, *args, **kwargs):
request_queue.put((callable, args, kwargs))
return result_queue.get()
t = None
def threadmain():
global t
def timertick():
try:
callable, args, kwargs = request_queue.get_nowait()
except Queue.Empty:
pass
else:
print "something in queue"
retval = callable(*args, **kwargs)
result_queue.put(retval)
t.after(500, timertick)
t = tk.Tk()
t.configure(width=640, height=480)
b = tk.Button(text='test', name='button', command=exit)
b.place(x=0, y=0)
timertick()
t.mainloop()
def foo():
t.title("Hello world")
def bar(button_text):
t.children["button"].configure(text=button_text)
def get_button_text():
return t.children["button"]["text"]
if __name__ == '__main__':
thread.start_new_thread(threadmain, ())
trigger = 0
while 1:
trigger += 1
if trigger == 3:
submit_to_tkinter(foo)
if trigger == 5:
submit_to_tkinter(bar, "changed")
if trigger == 7:
print submit_to_tkinter(get_button_text)
sleep(1)
</code></pre>
| 15 | 2009-07-29T06:09:46Z | [
"python",
"winapi",
"tkinter",
"green-threads"
] |
How to set the encoding for the tables' char columns in django? | 1,198,486 | <p>I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run</p>
<pre><code>manage.py syncdb
</code></pre>
<p>all respective columns are created with cp1252 character set (where did it get that -- I have no idea) and I have to manually update every column...</p>
<p>Is there a way to tell Django to create all those columns with UTF-8 encoding in the first place?</p>
<p>BTW, I use MySQL.</p>
| 10 | 2009-07-29T07:07:51Z | 1,198,655 | <p>Djangoâs database backends automatically handles Unicode strings into the appropriate encoding and talk to the database. You donât need to tell Django what encoding your database uses. It handles it well, by using you database's encoding.</p>
<p>I don't see any way you can tell django to create a column, using some specific encoding.
As it appears to me, there is absolutely some previous MySQL configuration affecting you.
And despite of doing it manually for all column, use these.</p>
<pre><code>CREATE DATABASE db_name
[[DEFAULT] CHARACTER SET charset_name]
[[DEFAULT] COLLATE collation_name]
ALTER DATABASE db_name
[[DEFAULT] CHARACTER SET charset_name]
[[DEFAULT] COLLATE collation_name]
</code></pre>
| 4 | 2009-07-29T07:54:10Z | [
"python",
"mysql",
"django"
] |
How to set the encoding for the tables' char columns in django? | 1,198,486 | <p>I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run</p>
<pre><code>manage.py syncdb
</code></pre>
<p>all respective columns are created with cp1252 character set (where did it get that -- I have no idea) and I have to manually update every column...</p>
<p>Is there a way to tell Django to create all those columns with UTF-8 encoding in the first place?</p>
<p>BTW, I use MySQL.</p>
| 10 | 2009-07-29T07:07:51Z | 1,198,663 | <p>What is your MySQL encoding set to?</p>
<p>For example, try the following from the command line:</p>
<pre><code> mysqld --verbose --help | grep character-set
</code></pre>
<p>If it doesn't output utf8, then you'll need to set the output in my.cnf:</p>
<pre><code>[mysqld]
character-set-server=utf8
default-collation=utf8_unicode_ci
[client]
default-character-set=utf8
</code></pre>
<p>This page has some more information: </p>
<ul>
<li><a href="http://www.zulutown.com/blog/tag/character-set/" rel="nofollow">http://www.zulutown.com/blog/tag/character-set/</a></li>
</ul>
| 2 | 2009-07-29T07:55:56Z | [
"python",
"mysql",
"django"
] |
How to set the encoding for the tables' char columns in django? | 1,198,486 | <p>I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run</p>
<pre><code>manage.py syncdb
</code></pre>
<p>all respective columns are created with cp1252 character set (where did it get that -- I have no idea) and I have to manually update every column...</p>
<p>Is there a way to tell Django to create all those columns with UTF-8 encoding in the first place?</p>
<p>BTW, I use MySQL.</p>
| 10 | 2009-07-29T07:07:51Z | 1,198,675 | <p>Django does not specify charset and collation in <code>CREATE TABLE</code> statements. Everything is determined by database charset. Doing <code>ALTER DATABASE ... CHARACTER SET utf8 COLLATE utf8_general_ci</code> before running <code>syncdb</code> should help.</p>
<p>For connection, Django issues <code>SET NAMES utf8</code> automatically, so you don't need to worry about default connection charset settings.</p>
| 15 | 2009-07-29T07:59:37Z | [
"python",
"mysql",
"django"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,552 | <p>I would be interested in seeing a more Pythonic way of doing this also. But this is a crappy solution. You would need to add checking for an empry index list.</p>
<p>Something along the lines of:</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
output = []
prev = 0
for index in indexes:
output.append(list[prev:index])
prev = index
output.append(list[indexes[-1]:])
print output
</code></pre>
<p>produces</p>
<pre><code>[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19]]
</code></pre>
| 5 | 2009-07-29T07:28:04Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,575 | <p>This is all that I could think of</p>
<pre><code>def partition(list_, indexes):
if indexes[0] != 0:
indexes = [0] + indexes
if indexes[-1] != len(list_):
indexes = indexes + [len(list_)]
return [ list_[a:b] for (a,b) in zip(indexes[:-1], indexes[1:])]
</code></pre>
| 0 | 2009-07-29T07:32:07Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,585 | <p>My solution is similar to Il-Bhima's.</p>
<pre><code>>>> def parts(list_, indices):
... indices = [0]+indices+[len(list_)]
... return [list_[v:indices[k+1]] for k, v in enumerate(indices[:-1])]
</code></pre>
<h2>Alternative approach</h2>
<p>If you're willing to slightly change the way you input indices, from absolute indices to relative (that is, from <code>[5, 12, 17]</code> to <code>[5, 7, 5]</code>, the below will also give you the desired output, while it doesn't create intermediary lists.</p>
<pre><code>>>> from itertools import islice
>>> def parts(list_, indices):
... i = iter(list_)
... return [list(islice(i, n)) for n in chain(indices, [None])]
</code></pre>
| 6 | 2009-07-29T07:35:18Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,615 | <p>The plural of index is indices. Going for simplicity/readability.</p>
<pre><code>indices = [5, 12, 17]
input = range(20)
output = []
for i in reversed(indices):
output.append(input[i:])
input[i:] = []
output.append(input)
while len(output):
print output.pop()
</code></pre>
| -1 | 2009-07-29T07:43:52Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,739 | <p>Cide's makes three copies of the array: [0]+indices copies, ([0]+indices)+[] copies again, and indices[:-1] will copy a third time. Il-Bhima makes five copies. (I'm not counting the return value, of course.)</p>
<p>Those could be reduced (izip, islice), but here's a zero-copy version:</p>
<pre><code>def iterate_pairs(lst, indexes):
prev = 0
for i in indexes:
yield prev, i
prev = i
yield prev, len(lst)
def partition(lst, indexes):
for first, last in iterate_pairs(lst, indexes):
yield lst[first:last]
indexes = [5, 12, 17]
lst = range(20)
print [l for l in partition(lst, indexes)]
</code></pre>
<p>Of course, array copies are fairly cheap (native code) compared to interpreted Python, but this has another advantage: it's easy to reuse, to mutate the data directly:</p>
<pre><code>for first, last in iterate_pairs(lst, indexes):
for i in range(first, last):
lst[i] = first
print lst
# [0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 12, 12, 12, 12, 12, 17, 17, 17]
</code></pre>
<p>(That's why I passed indexes to iterate_pairs. If you don't care about that, you can remove that parameter and just have the final line be "yield prev, None", which is all partition() needs.)</p>
| 0 | 2009-07-29T08:20:00Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,757 | <pre><code>indices = [5, 12, 17]
input = range(20)
output = []
reduce(lambda x, y: output.append(input[x:y]) or y, indices + [len(input)], 0)
print output
</code></pre>
| 1 | 2009-07-29T08:24:49Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,198,876 | <p>This is the simplest and most pythonic solution I can think of:</p>
<pre><code>def partition(alist, indices):
return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]
</code></pre>
<p>if the inputs are very large, then the iterators solution should be more convenient:</p>
<pre><code>from itertools import izip, chain
def partition(alist, indices):
pairs = izip(chain([0], indices), chain(indices, [None]))
return (alist[i:j] for i, j in pairs)
</code></pre>
<p>and of course, the very, very lazy guy solution (if you don't mind to get arrays instead of lists, but anyway you can always revert them to lists):</p>
<pre><code>import numpy
partition = numpy.split
</code></pre>
| 36 | 2009-07-29T08:55:27Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,201,494 | <p>Here's yet another answer.</p>
<pre><code>def partition(l, indexes):
result, indexes = [], indexes+[len(l)]
reduce(lambda x, y: result.append(l[x:y]) or y, indexes, 0)
return result
</code></pre>
<p>It supports negative indexes and such.</p>
<pre><code>>>> partition([1,2,3,4,5], [1, -1])
[[1], [2, 3, 4], [5]]
>>>
</code></pre>
| 0 | 2009-07-29T16:31:57Z | [
"python",
"list"
] |
Split a list into parts based on a set of indexes in Python | 1,198,512 | <p>What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below</p>
<pre><code>indexes = [5, 12, 17]
list = range(20)
</code></pre>
<p>return something like this</p>
<pre><code>part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
</code></pre>
<p>If there are no indexes it should return the entire list.</p>
| 33 | 2009-07-29T07:16:24Z | 1,204,323 | <pre><code>>>> def burst_seq(seq, indices):
... startpos = 0
... for index in indices:
... yield seq[startpos:index]
... startpos = index
... yield seq[startpos:]
...
>>> list(burst_seq(range(20), [5, 12, 17]))
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19]]
>>> list(burst_seq(range(20), []))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]
>>> list(burst_seq(range(0), [5, 12, 17]))
[[], [], [], []]
>>>
</code></pre>
<p>Maxima mea culpa: it uses a <code>for</code> statement, and it's not using whizzbang stuff like itertools, zip(), None as a sentinel, list comprehensions, ... </p>
<p>;-)</p>
| 2 | 2009-07-30T03:32:12Z | [
"python",
"list"
] |
django one to many issue at the admin panel | 1,198,589 | <p>Greetings, I have these 2 models:</p>
<pre><code>from django.db import models
class Office(models.Model):
name = models.CharField(max_length=30)
person = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
fax = models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ForeignKey(Office)
def __unicode__(self):
return self.name
</code></pre>
<p>I want to be able to select several Offices for Provinces, which is a one to many model. Here is my admin.py:</p>
<pre><code>from harita.haritaapp.models import Province, Office
from django.contrib import admin
class ProvinceCreator(admin.ModelAdmin):
list_display = ['name', 'numberPlate','content','office']
class OfficeCreator(admin.ModelAdmin):
list_display = ['name','person','phone','fax','address']
admin.site.register(Province, ProvinceCreator)
admin.site.register(Office, OfficeCreator)
</code></pre>
<p>Right now, I am able to select one Office per Province at the admin panel while creating a new Province but I want to be able to select more than one. How can I achieve this?</p>
<p>Regards</p>
| -2 | 2009-07-29T07:35:41Z | 1,198,603 | <p>I'm not sure if I'm misunderstanding you, but your models currently say "an office can be associated with many provinces, but each province may only have one office". This contradicts what you want. Use a ManyToMany field instead:</p>
<pre><code>class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ManyToManyField(Office)
def __unicode__(self):
return self.name
</code></pre>
| 2 | 2009-07-29T07:40:54Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Double Iteration in List Comprehension | 1,198,777 | <p>In Python you can have multiple iterators in a list comprehension, like</p>
<pre><code>[(x,y) for x in a for y in b]
</code></pre>
<p>for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.</p>
<p>My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:</p>
<pre><code>[x for x in a for a in b]
</code></pre>
<p>where the current value of the outer loop is the iterator of the inner?</p>
<p>As an example, if I have a nested list:</p>
<pre><code>a=[[1,2],[3,4]]
</code></pre>
<p>what would the list comprehension expression be to achieve this result:</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>?? (Please only list comprehension answers, since this is what I want to find out).</p>
| 75 | 2009-07-29T08:30:49Z | 1,198,788 | <p>Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:</p>
<pre><code>[x for b in a for x in b]
</code></pre>
<p>to get the desired result, and yes, one current value can be the iterator for the next loop :-). Sorry for the noise.</p>
| 44 | 2009-07-29T08:34:28Z | [
"python",
"list-comprehension"
] |
Double Iteration in List Comprehension | 1,198,777 | <p>In Python you can have multiple iterators in a list comprehension, like</p>
<pre><code>[(x,y) for x in a for y in b]
</code></pre>
<p>for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.</p>
<p>My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:</p>
<pre><code>[x for x in a for a in b]
</code></pre>
<p>where the current value of the outer loop is the iterator of the inner?</p>
<p>As an example, if I have a nested list:</p>
<pre><code>a=[[1,2],[3,4]]
</code></pre>
<p>what would the list comprehension expression be to achieve this result:</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>?? (Please only list comprehension answers, since this is what I want to find out).</p>
| 75 | 2009-07-29T08:30:49Z | 1,198,794 | <p>To answer your question with your own suggestion:</p>
<pre><code>>>> [x for b in a for x in b] # Works fine
</code></pre>
<p>While you asked for list comprehension answers, let me also point out the excellent itertools.chain():</p>
<pre><code>>>> from itertools import chain
>>> list(chain.from_iterable(a))
>>> list(chain(*a)) # If you're using python < 2.6
</code></pre>
| 74 | 2009-07-29T08:36:21Z | [
"python",
"list-comprehension"
] |
Double Iteration in List Comprehension | 1,198,777 | <p>In Python you can have multiple iterators in a list comprehension, like</p>
<pre><code>[(x,y) for x in a for y in b]
</code></pre>
<p>for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.</p>
<p>My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:</p>
<pre><code>[x for x in a for a in b]
</code></pre>
<p>where the current value of the outer loop is the iterator of the inner?</p>
<p>As an example, if I have a nested list:</p>
<pre><code>a=[[1,2],[3,4]]
</code></pre>
<p>what would the list comprehension expression be to achieve this result:</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>?? (Please only list comprehension answers, since this is what I want to find out).</p>
| 75 | 2009-07-29T08:30:49Z | 26,480,506 | <p>ThomasH has already added a good answer, but I want to show what happens:</p>
<pre><code>>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]
</code></pre>
<p>I guess Python parses the list comprehension from left to right. This means, the first <code>for</code> loop that occurs will be executed first.</p>
<p>The second "problem" of this is that <code>b</code> gets "leaked" out of the list comprehension. After the first successful list comprehension <code>b == [3, 4]</code>.</p>
| 10 | 2014-10-21T06:47:04Z | [
"python",
"list-comprehension"
] |
Double Iteration in List Comprehension | 1,198,777 | <p>In Python you can have multiple iterators in a list comprehension, like</p>
<pre><code>[(x,y) for x in a for y in b]
</code></pre>
<p>for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.</p>
<p>My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:</p>
<pre><code>[x for x in a for a in b]
</code></pre>
<p>where the current value of the outer loop is the iterator of the inner?</p>
<p>As an example, if I have a nested list:</p>
<pre><code>a=[[1,2],[3,4]]
</code></pre>
<p>what would the list comprehension expression be to achieve this result:</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>?? (Please only list comprehension answers, since this is what I want to find out).</p>
| 75 | 2009-07-29T08:30:49Z | 28,941,994 | <p>I feel this is easier to understand</p>
<pre><code>[row[i] for row in a for i in range(len(a))]
result: [1, 2, 3, 4]
</code></pre>
| 1 | 2015-03-09T12:27:20Z | [
"python",
"list-comprehension"
] |
Double Iteration in List Comprehension | 1,198,777 | <p>In Python you can have multiple iterators in a list comprehension, like</p>
<pre><code>[(x,y) for x in a for y in b]
</code></pre>
<p>for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.</p>
<p>My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:</p>
<pre><code>[x for x in a for a in b]
</code></pre>
<p>where the current value of the outer loop is the iterator of the inner?</p>
<p>As an example, if I have a nested list:</p>
<pre><code>a=[[1,2],[3,4]]
</code></pre>
<p>what would the list comprehension expression be to achieve this result:</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>?? (Please only list comprehension answers, since this is what I want to find out).</p>
| 75 | 2009-07-29T08:30:49Z | 36,734,643 | <p>I hope this helps someone else since <code>a,b,x,y</code> don't have much meaning to me! Suppose you have a text full of sentences and you want an array of words.</p>
<pre><code># Without list comprehension
list_of_words = []
for sentence in text:
for word in sentence:
list_of_words.append(word)
return list_of_words
</code></pre>
<p>I like to think of list comprehension as stretching code horizontally.</p>
<p>Try breaking it up into:</p>
<pre><code># List Comprehension
[word for sentence in text for word in sentence]
</code></pre>
| 3 | 2016-04-20T05:34:36Z | [
"python",
"list-comprehension"
] |
Double Iteration in List Comprehension | 1,198,777 | <p>In Python you can have multiple iterators in a list comprehension, like</p>
<pre><code>[(x,y) for x in a for y in b]
</code></pre>
<p>for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.</p>
<p>My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:</p>
<pre><code>[x for x in a for a in b]
</code></pre>
<p>where the current value of the outer loop is the iterator of the inner?</p>
<p>As an example, if I have a nested list:</p>
<pre><code>a=[[1,2],[3,4]]
</code></pre>
<p>what would the list comprehension expression be to achieve this result:</p>
<pre><code>[1,2,3,4]
</code></pre>
<p>?? (Please only list comprehension answers, since this is what I want to find out).</p>
| 75 | 2009-07-29T08:30:49Z | 39,870,492 | <p>Order of iterators may seem counter-intuitive.</p>
<p>Take for example: <code>[str(x) for i in range(3) for x in foo(i)]</code></p>
<p>Let's decompose it:</p>
<pre><code>def foo(i):
return i, i + 0.5
[str(x)
for i in range(3)
for x in foo(i)
]
# if same as
for i in range(3):
for x in foo(i):
yield str(x)
</code></pre>
| 1 | 2016-10-05T09:39:42Z | [
"python",
"list-comprehension"
] |
Python: Mapping from intervals to values | 1,199,053 | <p>I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:</p>
<pre><code>if p <= 100:
return 0
elif p > 100 and p <= 300:
return 1
elif p > 300 and p <= 500:
return 2
elif p > 500 and p <= 800:
return 3
elif p > 800 and p <= 1000:
return 4
elif p > 1000:
return 5
</code></pre>
<p>Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded.
Any use of any data structure is of course possible.</p>
| 9 | 2009-07-29T09:33:42Z | 1,199,093 | <p>Try something along the lines of:</p>
<pre><code>d = {(None,100): 0,
(100,200): 1,
...
(1000, None): 5}
value = 300 # example value
for k,v in d.items():
if (k[0] is None or value > k[0]) and (k[1] is None or value <= k[1]):
return v
</code></pre>
| 0 | 2009-07-29T09:42:34Z | [
"python",
"range",
"intervals"
] |
Python: Mapping from intervals to values | 1,199,053 | <p>I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:</p>
<pre><code>if p <= 100:
return 0
elif p > 100 and p <= 300:
return 1
elif p > 300 and p <= 500:
return 2
elif p > 500 and p <= 800:
return 3
elif p > 800 and p <= 1000:
return 4
elif p > 1000:
return 5
</code></pre>
<p>Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded.
Any use of any data structure is of course possible.</p>
| 9 | 2009-07-29T09:33:42Z | 1,199,097 | <p>You could try a take on this:</p>
<pre><code>def check_mapping(p):
mapping = [(100, 0), (300, 1), (500, 2)] # Add all your values and returns here
for check, value in mapping:
if p <= check:
return value
print check_mapping(12)
print check_mapping(101)
print check_mapping(303)
</code></pre>
<p>produces:</p>
<pre><code>0
1
2
</code></pre>
<p>As always in Python, there will be any better ways to do it.</p>
| 3 | 2009-07-29T09:43:35Z | [
"python",
"range",
"intervals"
] |
Python: Mapping from intervals to values | 1,199,053 | <p>I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:</p>
<pre><code>if p <= 100:
return 0
elif p > 100 and p <= 300:
return 1
elif p > 300 and p <= 500:
return 2
elif p > 500 and p <= 800:
return 3
elif p > 800 and p <= 1000:
return 4
elif p > 1000:
return 5
</code></pre>
<p>Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded.
Any use of any data structure is of course possible.</p>
| 9 | 2009-07-29T09:33:42Z | 1,199,112 | <pre><code>def which_interval(endpoints, number):
for n, endpoint in enumerate(endpoints):
if number <= endpoint:
return n
previous = endpoint
return n + 1
</code></pre>
<p>Pass your endpoints as a list in <code>endpoints</code>, like this:</p>
<pre><code>which_interval([100, 300, 500, 800, 1000], 5)
</code></pre>
<p>Edit:</p>
<p>The above is a linear search. Glenn Maynard's answer will have better performance, since it uses a bisection algorithm.</p>
| 0 | 2009-07-29T09:47:46Z | [
"python",
"range",
"intervals"
] |
Python: Mapping from intervals to values | 1,199,053 | <p>I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:</p>
<pre><code>if p <= 100:
return 0
elif p > 100 and p <= 300:
return 1
elif p > 300 and p <= 500:
return 2
elif p > 500 and p <= 800:
return 3
elif p > 800 and p <= 1000:
return 4
elif p > 1000:
return 5
</code></pre>
<p>Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded.
Any use of any data structure is of course possible.</p>
| 9 | 2009-07-29T09:33:42Z | 1,199,113 | <pre><code>import bisect
bisect.bisect_left([100,300,500,800,1000], p)
</code></pre>
| 29 | 2009-07-29T09:47:54Z | [
"python",
"range",
"intervals"
] |
Python: Mapping from intervals to values | 1,199,053 | <p>I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:</p>
<pre><code>if p <= 100:
return 0
elif p > 100 and p <= 300:
return 1
elif p > 300 and p <= 500:
return 2
elif p > 500 and p <= 800:
return 3
elif p > 800 and p <= 1000:
return 4
elif p > 1000:
return 5
</code></pre>
<p>Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded.
Any use of any data structure is of course possible.</p>
| 9 | 2009-07-29T09:33:42Z | 1,199,299 | <p>Another way ...</p>
<pre><code>def which(lst, p):
return len([1 for el in lst if p > el])
lst = [100, 300, 500, 800, 1000]
which(lst, 2)
which(lst, 101)
which(lst, 1001)
</code></pre>
| 0 | 2009-07-29T10:34:49Z | [
"python",
"range",
"intervals"
] |
Python: Mapping from intervals to values | 1,199,053 | <p>I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:</p>
<pre><code>if p <= 100:
return 0
elif p > 100 and p <= 300:
return 1
elif p > 300 and p <= 500:
return 2
elif p > 500 and p <= 800:
return 3
elif p > 800 and p <= 1000:
return 4
elif p > 1000:
return 5
</code></pre>
<p>Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded.
Any use of any data structure is of course possible.</p>
| 9 | 2009-07-29T09:33:42Z | 1,200,012 | <p>It is indeed quite horrible. Without a requirement to have no hardcoding, it should have been written like this:</p>
<pre><code>if p <= 100:
return 0
elif p <= 300:
return 1
elif p <= 500:
return 2
elif p <= 800:
return 3
elif p <= 1000:
return 4
else:
return 5
</code></pre>
<p>Here are examples of creating a lookup function, both linear and using binary search, with the no-hardcodings requirement fulfilled, and a couple of sanity checks on the two tables:</p>
<pre><code>def make_linear_lookup(keys, values):
assert sorted(keys) == keys
assert len(values) == len(keys) + 1
def f(query):
return values[sum(1 for key in keys if query > key)]
return f
import bisect
def make_bisect_lookup(keys, values):
assert sorted(keys) == keys
assert len(values) == len(keys) + 1
def f(query):
return values[bisect.bisect_left(keys, query)]
return f
</code></pre>
| 3 | 2009-07-29T12:48:31Z | [
"python",
"range",
"intervals"
] |
installed module on python editor | 1,199,249 | <p>how can i import modules/packages at python3.0 editor IDLE.
and can we see all the modules contain/included by it.</p>
| 0 | 2009-07-29T10:23:27Z | 1,199,259 | <pre><code>>>> import idle
>>> dir(idle)
</code></pre>
| 1 | 2009-07-29T10:26:43Z | [
"python",
"editor"
] |
Whats the best way of putting tabular data into python? | 1,199,350 | <p>I have a CSV file which I am processing and putting the processed data into a text file.
The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file?</p>
<p>For eg. Assume there is a column called 'col'.
I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.)</p>
<p>Hope I am not too vague...</p>
| 2 | 2009-07-29T10:44:31Z | 1,199,371 | <p>Probably either a <code>dict</code> of <code>list</code> or a <code>list</code> of <code>dict</code>. Personally, I'd go with the former. So, parse the heading row of the CSV to get a <code>dict</code> from column heading to column index. Then when you're reading through each row, work out what index you're at, grab the column heading, and then append to the end of the list for that column heading.</p>
| 0 | 2009-07-29T10:48:21Z | [
"python",
"file",
"csv"
] |
Whats the best way of putting tabular data into python? | 1,199,350 | <p>I have a CSV file which I am processing and putting the processed data into a text file.
The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file?</p>
<p>For eg. Assume there is a column called 'col'.
I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.)</p>
<p>Hope I am not too vague...</p>
| 2 | 2009-07-29T10:44:31Z | 1,199,385 | <p>Python's CSV library has a <a href="http://docs.python.org/library/csv.html#csv.DictReader" rel="nofollow">function named DictReader</a> that allow you to view and manipulate the data as a Python dictionary, which allows you to use normal iterative tools.</p>
| 1 | 2009-07-29T10:51:08Z | [
"python",
"file",
"csv"
] |
Whats the best way of putting tabular data into python? | 1,199,350 | <p>I have a CSV file which I am processing and putting the processed data into a text file.
The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file?</p>
<p>For eg. Assume there is a column called 'col'.
I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.)</p>
<p>Hope I am not too vague...</p>
| 2 | 2009-07-29T10:44:31Z | 1,199,396 | <p>Go with a list of lists. That is:</p>
<pre><code>[[col1, col2, col3, col4], # Row 1
[col1, col2, col3, col4], # Row 2
[col1, col2, col3, col4], # Row 3
[col1, col2, col3, col4]] # Row 4
</code></pre>
<p>To modify a specific column, you can transform this into a list of columns with a single statement:</p>
<pre><code>>>> cols = zip(*rows)
>>> cols
[[row1, row2, row3, row4], # Col 1
[row1, row2, row3, row4], # Col 2
[row1, row2, row3, row4], # Col 3
[row1, row2, row3, row4]] # Col 4
</code></pre>
| 2 | 2009-07-29T10:52:56Z | [
"python",
"file",
"csv"
] |
Whats the best way of putting tabular data into python? | 1,199,350 | <p>I have a CSV file which I am processing and putting the processed data into a text file.
The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file?</p>
<p>For eg. Assume there is a column called 'col'.
I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.)</p>
<p>Hope I am not too vague...</p>
| 2 | 2009-07-29T10:44:31Z | 1,199,409 | <p>Is SQLite an option for you? I know that you have CSV input and output. However, you can import all the data into the SQLite database. Then do all the necessary processing with the power of SQL. Then you can export the results as CSV. </p>
| 1 | 2009-07-29T10:54:41Z | [
"python",
"file",
"csv"
] |
Whats the best way of putting tabular data into python? | 1,199,350 | <p>I have a CSV file which I am processing and putting the processed data into a text file.
The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file?</p>
<p>For eg. Assume there is a column called 'col'.
I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.)</p>
<p>Hope I am not too vague...</p>
| 2 | 2009-07-29T10:44:31Z | 1,199,830 | <p>Good question, I have this problem very frequently.</p>
<p>In general, to handle csv files like that, I prefer to use R which is a data.frame object specifically designed for this.</p>
<p>In python, you can have a look at this library called datamatrix:</p>
<ul>
<li><a href="http://github.com/cswegger/datamatrix/tree/master" rel="nofollow">http://github.com/cswegger/datamatrix/tree/master</a></li>
</ul>
<p>Or maybe at numpy/scipy's matrixes.</p>
<p>Named tuples are another alternative which has been tought for parsing csv files, but they are not pbased on the concept of a matrix:</p>
<ul>
<li><a href="http://ttp://code.activestate.com/recipes/500261/" rel="nofollow">http://code.activestate.com/recipes/500261/</a></li>
</ul>
| 0 | 2009-07-29T12:13:12Z | [
"python",
"file",
"csv"
] |
Whats the best way of putting tabular data into python? | 1,199,350 | <p>I have a CSV file which I am processing and putting the processed data into a text file.
The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file?</p>
<p>For eg. Assume there is a column called 'col'.
I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.)</p>
<p>Hope I am not too vague...</p>
| 2 | 2009-07-29T10:44:31Z | 1,200,623 | <p>Your situation is kind of vague, but I'll try to answer your question, "How do I remember the column into which a piece of data goes in the text file?"</p>
<p>One way is to store a list of rows as dictionaries. </p>
<p><em>Note: I usually use tab-delimited text files, so forgive me if I'm forgetting something about csv formatting.</em></p>
<pre><code>input_file = open('input.csv', 'r')
# ['col1', 'col2', 'col3']
headers = input_file.readline().strip().split(',')
stored_rows = []
for line in input_file:
row_data = line.strip().split(',')
stored_rows.append(dict(zip(headers, row_data)))
</code></pre>
<p>Now each row has a value for each column, which you can then process and output in whatever order you need.</p>
<pre><code>output_headers = ['col3', 'col1', 'col2']
output_file = open('ouput.csv', 'w')
output_file.write(','.join(output_headers) + '\n')
for row in stored_rows:
# do any processing you need here
row['col1'] = row['col1'].strip().lower() #for example
# write the data to your output file in the order you want it
output_file.write(','.join(map(row.get, output_headers)) + '\n')
</code></pre>
| 0 | 2009-07-29T14:22:31Z | [
"python",
"file",
"csv"
] |
Using Storm: ImportError: No module named local | 1,199,415 | <p>As stated in the Storm documentation, I am doing the following to import the necessary symbols for using Storm:</p>
<pre><code>from storm.locals import *
</code></pre>
<p>I'm using it alongside with Pylons, and storm is indeed installed as an egg in the virtual Python environment which Pylon setup for me, and it also searches the correct paths.</p>
<p>However, when the import code above is evaluated, the following exception is being thrown:</p>
<blockquote>
<p>ImportError: No module named local</p>
</blockquote>
<p>But I'm not explicitly including anything from a module named 'local', but 'locals'.</p>
<p><strong>Update (traceback)</strong></p>
<pre><code>URL: http://localhost:5000/characters/index
File '/home/andy/pylon-env/lib/python2.6/site-packages/WebError-0.10.1-py2.6.egg/weberror/evalexception.py', line 431 in respond
app_iter = self.application(environ, detect_start_response)
File '/home/andy/pylon-env/lib/python2.6/site-packages/Beaker-1.3.1-py2.6.egg/beaker/middleware.py', line 70 in __call__
return self.app(environ, start_response)
File '/home/andy/pylon-env/lib/python2.6/site-packages/Beaker-1.3.1-py2.6.egg/beaker/middleware.py', line 149 in __call__
return self.wrap_app(environ, session_start_response)
File '/home/andy/pylon-env/lib/python2.6/site-packages/Routes-1.10.3-py2.6.egg/routes/middleware.py', line 130 in __call__
response = self.app(environ, start_response)
File '/home/andy/pylon-env/lib/python2.6/site-packages/Pylons-0.9.7-py2.6.egg/pylons/wsgiapp.py', line 124 in __call__
controller = self.resolve(environ, start_response)
File '/home/andy/pylon-env/lib/python2.6/site-packages/Pylons-0.9.7-py2.6.egg/pylons/wsgiapp.py', line 263 in resolve
return self.find_controller(controller)
File '/home/andy/pylon-env/lib/python2.6/site-packages/Pylons-0.9.7-py2.6.egg/pylons/wsgiapp.py', line 284 in find_controller
__import__(full_module_name)
File '/home/andy/projects/evecharacters/evecharacters/controllers/characters.py', line 9 in <module>
from storm.local import *
ImportError: No module named local
</code></pre>
| 0 | 2009-07-29T10:56:19Z | 1,200,522 | <p>Here's the code that's failing.</p>
<pre><code>File '/home/andy/projects/evecharacters/evecharacters/controllers/characters.py', line 9 in <module>
from storm.local import *
ImportError: No module named local
</code></pre>
<p>You claim your snippet is</p>
<pre><code>from storm.locals import *
</code></pre>
<p>But the error traceback says</p>
<pre><code>from storm.local import *
</code></pre>
<p>I'm betting the traceback is right and the file</p>
<p>/home/andy/projects/evecharacters/evecharacters/controllers/characters.py', line 9</p>
<p>has the incorrect code <code>from storm.local import *</code>. Not the code you wish that it had.</p>
| 1 | 2009-07-29T14:08:22Z | [
"python",
"storm-orm"
] |
combine javascript files at deployment in python | 1,199,470 | <p>I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?</p>
| 13 | 2009-07-29T11:06:42Z | 1,199,481 | <p>Here's a Python script I made that I use with all my heavy JavaScript projects. I'm using YUICompressor, but you can change the code to use another compressor.</p>
<pre><code>import os, os.path, shutil
YUI_COMPRESSOR = 'yuicompressor-2.4.2.jar'
def compress(in_files, out_file, in_type='js', verbose=False,
temp_file='.temp'):
temp = open(temp_file, 'w')
for f in in_files:
fh = open(f)
data = fh.read() + '\n'
fh.close()
temp.write(data)
print ' + %s' % f
temp.close()
options = ['-o "%s"' % out_file,
'--type %s' % in_type]
if verbose:
options.append('-v')
os.system('java -jar "%s" %s "%s"' % (YUI_COMPRESSOR,
' '.join(options),
temp_file))
org_size = os.path.getsize(temp_file)
new_size = os.path.getsize(out_file)
print '=> %s' % out_file
print 'Original: %.2f kB' % (org_size / 1024.0)
print 'Compressed: %.2f kB' % (new_size / 1024.0)
print 'Reduction: %.1f%%' % (float(org_size - new_size) / org_size * 100)
print ''
#os.remove(temp_file)
</code></pre>
<p>I use it like this (the below is just a code snippet, and assumes that the <code>compress</code> function exists in the current namespace):</p>
<pre><code>SCRIPTS = [
'app/js/libs/EventSource.js',
'app/js/libs/Hash.js',
'app/js/libs/JSON.js',
'app/js/libs/ServiceClient.js',
'app/js/libs/jquery.hash.js',
'app/js/libs/Application.js',
'app/js/intro.js',
'app/js/jquery-extras.js',
'app/js/settings.js',
'app/js/api.js',
'app/js/game.js',
'app/js/user.js',
'app/js/pages.intro.js',
'app/js/pages.home.js',
'app/js/pages.log-in.js',
'app/js/pages.log-out.js',
'app/js/pages.new-command.js',
'app/js/pages.new-frame.js',
'app/js/pages.not-found.js',
'app/js/pages.register.js',
'app/js/pages.outro.js',
'app/js/outro.js',
]
SCRIPTS_OUT_DEBUG = 'app/js/multifarce.js'
SCRIPTS_OUT = 'app/js/multifarce.min.js'
STYLESHEETS = [
'app/media/style.css',
]
STYLESHEETS_OUT = 'app/media/style.min.css'
def main():
print 'Compressing JavaScript...'
compress(SCRIPTS, SCRIPTS_OUT, 'js', False, SCRIPTS_OUT_DEBUG)
print 'Compressing CSS...'
compress(STYLESHEETS, STYLESHEETS_OUT, 'css')
if __name__ == '__main__':
main()
</code></pre>
| 21 | 2009-07-29T11:09:46Z | [
"javascript",
"python",
"deployment",
"buildout",
"jscompress"
] |
combine javascript files at deployment in python | 1,199,470 | <p>I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?</p>
| 13 | 2009-07-29T11:06:42Z | 1,201,475 | <p>The <a href="http://qooxdoo.org" rel="nofollow">qooxdoo</a> project comes with a Javascript compressor written in Python. Although it's tightly integrated with the framework, you should be able to utilize the compressor component. If you get the latest SDK there is a <em>tool/bin/compile.py</em> command line tool you can use to compress JS files, with various options (use the -h command line switch for help). I'm sure builtout can call this through a shell.</p>
<p>If you want to roll your own you can draw the compressor into your own Python code, by using the Python modules that come with the qooxdoo SDK (under <em>tool/pylib/</em>). It's not documented but you can look at the <em>compile.py</em> script how to achieve that.</p>
| 1 | 2009-07-29T16:29:12Z | [
"javascript",
"python",
"deployment",
"buildout",
"jscompress"
] |
combine javascript files at deployment in python | 1,199,470 | <p>I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?</p>
| 13 | 2009-07-29T11:06:42Z | 1,905,612 | <p>Combining Blixt's solution with JS Min. Here is the code:</p>
<p>Just call the <code>compress(in_files, out_file)</code> method</p>
<pre><code>import os, os.path, shutil
# This code is original from jsmin by Douglas Crockford, it was translated to
# Python by Baruch Even. The original code had the following copyright and
# license.
#
# /* jsmin.c
# 2007-05-22
#
# Copyright (c) 2002 Douglas Crockford (www.crockford.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# The Software shall be used for Good, not Evil.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# */
from StringIO import StringIO
def jsmin(js):
ins = StringIO(js)
outs = StringIO()
JavascriptMinify().minify(ins, outs)
str = outs.getvalue()
if len(str) > 0 and str[0] == '\n':
str = str[1:]
return str
def isAlphanum(c):
"""return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
"""
return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
(c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126));
class UnterminatedComment(Exception):
pass
class UnterminatedStringLiteral(Exception):
pass
class UnterminatedRegularExpression(Exception):
pass
class JavascriptMinify(object):
def _outA(self):
self.outstream.write(self.theA)
def _outB(self):
self.outstream.write(self.theB)
def _get(self):
"""return the next character from stdin. Watch out for lookahead. If
the character is a control character, translate it to a space or
linefeed.
"""
c = self.theLookahead
self.theLookahead = None
if c == None:
c = self.instream.read(1)
if c >= ' ' or c == '\n':
return c
if c == '': # EOF
return '\000'
if c == '\r':
return '\n'
return ' '
def _peek(self):
self.theLookahead = self._get()
return self.theLookahead
def _next(self):
"""get the next character, excluding comments. peek() is used to see
if an unescaped '/' is followed by a '/' or '*'.
"""
c = self._get()
if c == '/' and self.theA != '\\':
p = self._peek()
if p == '/':
c = self._get()
while c > '\n':
c = self._get()
return c
if p == '*':
c = self._get()
while 1:
c = self._get()
if c == '*':
if self._peek() == '/':
self._get()
return ' '
if c == '\000':
raise UnterminatedComment()
return c
def _action(self, action):
"""do something! What you do is determined by the argument:
1 Output A. Copy B to A. Get the next B.
2 Copy B to A. Get the next B. (Delete A).
3 Get the next B. (Delete B).
action treats a string as a single character. Wow!
action recognizes a regular expression if it is preceded by ( or , or =.
"""
if action <= 1:
self._outA()
if action <= 2:
self.theA = self.theB
if self.theA == "'" or self.theA == '"':
while 1:
self._outA()
self.theA = self._get()
if self.theA == self.theB:
break
if self.theA <= '\n':
raise UnterminatedStringLiteral()
if self.theA == '\\':
self._outA()
self.theA = self._get()
if action <= 3:
self.theB = self._next()
if self.theB == '/' and (self.theA == '(' or self.theA == ',' or
self.theA == '=' or self.theA == ':' or
self.theA == '[' or self.theA == '?' or
self.theA == '!' or self.theA == '&' or
self.theA == '|' or self.theA == ';' or
self.theA == '{' or self.theA == '}' or
self.theA == '\n'):
self._outA()
self._outB()
while 1:
self.theA = self._get()
if self.theA == '/':
break
elif self.theA == '\\':
self._outA()
self.theA = self._get()
elif self.theA <= '\n':
raise UnterminatedRegularExpression()
self._outA()
self.theB = self._next()
def _jsmin(self):
"""Copy the input to the output, deleting the characters which are
insignificant to JavaScript. Comments will be removed. Tabs will be
replaced with spaces. Carriage returns will be replaced with linefeeds.
Most spaces and linefeeds will be removed.
"""
self.theA = '\n'
self._action(3)
while self.theA != '\000':
if self.theA == ' ':
if isAlphanum(self.theB):
self._action(1)
else:
self._action(2)
elif self.theA == '\n':
if self.theB in ['{', '[', '(', '+', '-']:
self._action(1)
elif self.theB == ' ':
self._action(3)
else:
if isAlphanum(self.theB):
self._action(1)
else:
self._action(2)
else:
if self.theB == ' ':
if isAlphanum(self.theA):
self._action(1)
else:
self._action(3)
elif self.theB == '\n':
if self.theA in ['}', ']', ')', '+', '-', '"', '\'']:
self._action(1)
else:
if isAlphanum(self.theA):
self._action(1)
else:
self._action(3)
else:
self._action(1)
def minify(self, instream, outstream):
self.instream = instream
self.outstream = outstream
self.theA = '\n'
self.theB = None
self.theLookahead = None
self._jsmin()
self.instream.close()
def compress(in_files, out_file, in_type='js', verbose=False,
temp_file='.temp'):
temp = open(temp_file, 'w')
for f in in_files:
fh = open(f)
data = fh.read() + '\n'
fh.close()
temp.write(data)
print ' + %s' % f
temp.close()
out = open(out_file, 'w')
jsm = JavascriptMinify()
jsm.minify(open(temp_file,'r'), out)
out.close()
org_size = os.path.getsize(temp_file)
new_size = os.path.getsize(out_file)
print '=> %s' % out_file
print 'Original: %.2f kB' % (org_size / 1024.0)
print 'Compressed: %.2f kB' % (new_size / 1024.0)
print 'Reduction: %.1f%%' % (float(org_size - new_size) / org_size * 100)
print ''
os.remove(temp_file)
</code></pre>
| 6 | 2009-12-15T06:46:24Z | [
"javascript",
"python",
"deployment",
"buildout",
"jscompress"
] |
combine javascript files at deployment in python | 1,199,470 | <p>I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?</p>
| 13 | 2009-07-29T11:06:42Z | 5,109,788 | <p>A slightly different take on the solution proposed by Rushabh. Rather than a file based compress function, this is string based and somewhat simpler:</p>
<pre><code>def jsmerge(file_names, debug=False):
"""combines several js files together, with optional minification"""
js = ""
for file_name in file_names:
js += open(file_name).read()
# if debug is enabled, we skip the minification
if debug:
return js
else:
return jsmin(js)
</code></pre>
| 0 | 2011-02-24T20:01:11Z | [
"javascript",
"python",
"deployment",
"buildout",
"jscompress"
] |
combine javascript files at deployment in python | 1,199,470 | <p>I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?</p>
| 13 | 2009-07-29T11:06:42Z | 19,655,315 | <p>If you're using WSGI middleware you could also use <a href="http://www.fanstatic.org/en/1.0a3/index.html" rel="nofollow">Fanstatic</a>. It's probably some more work to integrate it into your stack than "simply" changing something in Buildout. The things you get with Fanstatic on the other hand are pretty good. It allows you to only send exactly the scripts you need for every page. It also does concatting (bundling) and minification of "resources" (JavaScript and CSS).</p>
| 1 | 2013-10-29T10:17:26Z | [
"javascript",
"python",
"deployment",
"buildout",
"jscompress"
] |
How to distribute and execute platform-specific unit tests? | 1,199,493 | <p>We have a python project that we want to start testing using buildbot. Its unit tests include tests that should only work on some platforms. So, we've got tests that should pass on all platforms, tests that should only run on 1 specific platform, tests that should pass on platforms A, B, C and tests that pass on B and D.</p>
<p>What is the best way of doing this? Simple suites would be a hassle, since, as described, each test can have a different list of target platforms. I thought about adding "@run_on" and "@ignore_on" decorators that would match platforms to test methods. Is there anything better?</p>
| 5 | 2009-07-29T11:13:10Z | 1,199,671 | <p>Sounds like a handy place for a test loader.</p>
<p>Check out <a href="http://docs.python.org/library/unittest.html#unittest.TestLoader.loadTestsFromName" rel="nofollow">http://docs.python.org/library/unittest.html#unittest.TestLoader.loadTestsFromName</a></p>
<p>If you provide some suitable naming conventions you can probably create suites based on your test naming conventions.</p>
<p>If I've got test A that executes on AIX, Linux (all) and 32 bit Windows, test B that runs on Windows 64, Linux 64 and Solaris, and test C that runs on everything but HPUX and test D that runs on everything... What possible naming-convention is there for this?</p>
<pre><code>class TestA_AIX_Linux2_Win32( unittest.TestCase ):
class TestB_Win64_Linux64_Solaris( unittest.TestCase ):
class TestC_AIX_Linux2_Win32_Win64_Linux64_Solaris( unittest.TestCase ):
class TestD_All( unittest.TestCase ):
</code></pre>
<p>The hard part is the "not HP/UX". Avoiding negative logic makes your life simpler. In this case, you simply list all OS's that are not HP/UX. The list is fairly short and grows slowly.</p>
<p>The "All" tests are simply a separate text search that's merged in with the current platform's list of tests to create a complete suite.</p>
<p>You could try something like</p>
<pre><code>class TextC_XHPUX( unittest.TestCase ):
</code></pre>
<p>Your text matching rule is normally <code>"_someOSName"</code>; your exceptions would be a weird text filter to mess around with the the <code>"_X"</code> name.</p>
<p>"We can't have a positive list of OS's. What if we add a new OS? Do we have to rename every test to explicitly include it?" Yes. The new operating system market is slow to evolve, it's not that painful to manage.</p>
<p>The alternative is to include information within each class (i.e., a class-level function) or a decorator and use a customized class loader that evaluates the class-level function.</p>
| 0 | 2009-07-29T11:44:31Z | [
"python",
"unit-testing",
"buildbot"
] |
How to distribute and execute platform-specific unit tests? | 1,199,493 | <p>We have a python project that we want to start testing using buildbot. Its unit tests include tests that should only work on some platforms. So, we've got tests that should pass on all platforms, tests that should only run on 1 specific platform, tests that should pass on platforms A, B, C and tests that pass on B and D.</p>
<p>What is the best way of doing this? Simple suites would be a hassle, since, as described, each test can have a different list of target platforms. I thought about adding "@run_on" and "@ignore_on" decorators that would match platforms to test methods. Is there anything better?</p>
| 5 | 2009-07-29T11:13:10Z | 1,199,767 | <p>On a couple of occasions I have used this very simple approach in test modules:</p>
<pre><code>import sys
import unittest
if 'win' in sys.platform:
class TestIt(unittest.TestCase):
...
if 'linux' in sys.platform:
class TestIt(unittest.TestCase):
...
</code></pre>
| 2 | 2009-07-29T12:01:48Z | [
"python",
"unit-testing",
"buildbot"
] |
How to distribute and execute platform-specific unit tests? | 1,199,493 | <p>We have a python project that we want to start testing using buildbot. Its unit tests include tests that should only work on some platforms. So, we've got tests that should pass on all platforms, tests that should only run on 1 specific platform, tests that should pass on platforms A, B, C and tests that pass on B and D.</p>
<p>What is the best way of doing this? Simple suites would be a hassle, since, as described, each test can have a different list of target platforms. I thought about adding "@run_on" and "@ignore_on" decorators that would match platforms to test methods. Is there anything better?</p>
| 5 | 2009-07-29T11:13:10Z | 1,371,766 | <p>We've decided to go with decorators that, using platform module and others, check whether the tests should be executed, and if not simply let it pass (though, we saw that python2.7 already has in its trunk a SkipTest exception that could be raised in such cases, to ignore the test).</p>
| 0 | 2009-09-03T06:50:32Z | [
"python",
"unit-testing",
"buildbot"
] |
How do I use Python serverside with shared hosting? | 1,199,703 | <p>I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.</p>
| 3 | 2009-07-29T11:49:50Z | 1,199,738 | <p>There are many ways you could do this: assuming the server architecture supports the <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">WSGI</a> standard, then you could do something as simple as plugging in your own handler to generate the HTML (this could just build a string manually if you want to be really straightforward, or else use a template engine like <a href="http://www.makotemplates.org/docs/" rel="nofollow">Mako</a>.</p>
<p>An example of a WSGI handler might look like this:</p>
<pre><code>class HelloWorldHandler(object):
def __call__(self, environ, start_response):
"""
Processes a request for a webpage
"""
start_response('200 OK', [('Content-Type', 'text/html')])
return "<p>Hello world!</p>"
</code></pre>
<p>Obviously it is up to you what you return or how you generate it: as I say, for more complex pages a templating engine might be useful.</p>
<p>The more involved way would be to leverage a more complete framework, such as <a href="http://pythonpaste.org/" rel="nofollow">paste</a> or <a href="http://turbogears.org/" rel="nofollow">turbogears</a> but if you only want to output a static page or two this could be overkill.</p>
| 2 | 2009-07-29T11:57:11Z | [
"python",
"server-side"
] |
How do I use Python serverside with shared hosting? | 1,199,703 | <p>I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.</p>
| 3 | 2009-07-29T11:49:50Z | 1,199,744 | <p>If your server is running Apache HTTP server, then you need something like <strong>mod_wsgi</strong> or <strong>mod_python</strong> installed and running as a module (your server signature may tell you this).</p>
<p>Once running, you may need to add a <strong>handler</strong> to your apache config, or a default may be setup.</p>
<p>After that, look at the documentation for the <strong>middleware</strong> of the module you are running, then maybe go on and use something like Django.</p>
| 2 | 2009-07-29T11:58:08Z | [
"python",
"server-side"
] |
How do I use Python serverside with shared hosting? | 1,199,703 | <p>I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.</p>
| 3 | 2009-07-29T11:49:50Z | 1,199,863 | <p>You can't use it "the same way" as PHP. There are however tons of ways of doing it like Python.</p>
<p>Look into the likes of Turbogears or Django. Or BFG of you want something minimalistic, or WSGI (via mod_wsgi) if you want to go directly to the basics.</p>
<p><a href="http://www.djangoproject.com/" rel="nofollow">http://www.djangoproject.com/</a></p>
<p><a href="http://bfg.repoze.org/" rel="nofollow">http://bfg.repoze.org/</a></p>
<p><a href="http://turbogears.org/" rel="nofollow">http://turbogears.org/</a></p>
<p><a href="http://www.wsgi.org/wsgi/" rel="nofollow">http://www.wsgi.org/wsgi/</a></p>
| 1 | 2009-07-29T12:22:48Z | [
"python",
"server-side"
] |
How do I use Python serverside with shared hosting? | 1,199,703 | <p>I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.</p>
| 3 | 2009-07-29T11:49:50Z | 1,199,872 | <p>When I used shared hosting I found that if I renamed the file to .py and prefixed it with a shebang line then it would be executed as Python.</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>Was probably pretty bad practice, but it did work. Don't expect to be able to spit out any extensive web apps with it though.</p>
| 3 | 2009-07-29T12:24:50Z | [
"python",
"server-side"
] |
Google app engine - structuring model layout with regards to parents? | 1,199,713 | <p>How does one go about structuring his db.Models effectively?</p>
<p>For instance, lets say I have a model for Countries, with properties like "name, northern_hemisphere(boolean), population, states (list of states), capital(boolean).</p>
<p>And another model called State or county or something with properties "name, population, cities(list of cities).</p>
<p>And another model called Cities, with properties "name, capital(boolean), distance_from_capital, population.</p>
<p>I just made that up so bare with me. Obviously I need the Cities to store data related to certain States, and thus States needs data related to the specific Country. In my States model I would have California, Colorado etc, and each of those has to have a specific list of Cities.</p>
<p>How does one structure his models so they are related somehow? I am very new to MVC so am struggling conceptually. Is it possible to use the class(parent) constructor?</p>
| 1 | 2009-07-29T11:52:42Z | 1,199,742 | <p>If you want to store relational data in the datastore of Google App Engine, this is a great article to start out with: <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">Modeling Entity Relationships</a>.</p>
<p>You use <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty" rel="nofollow"><code>ReferenceProperty</code></a> to specify a relationship between two models:</p>
<pre><code>class Country(db.Model):
name = db.StringProperty(required=True)
class State(db.Model):
country = db.ReferenceProperty(Country, collection_name='states')
name = db.StringProperty(required=True)
class City(db.Model):
state = db.ReferenceProperty(State, collection_name='cities')
name = db.StringProperty(required=True)
</code></pre>
<p>Instances of your <code>Country</code> model will automatically get a new property called <code>states</code> which will be a query to get all related <code>State</code> entities. Same thing with the <code>State</code> model for cities. Its automatically created <code>cities</code> property will be a query to get all related <code>City</code> entities.</p>
<p>How to use:</p>
<pre><code># Create a new country:
us = Country(name='USA')
us.put()
# Create a new state
ca = State(name='California', country=us)
ca.put()
# Create a new city
la = City(name='Los Angeles', state=ca)
la.put()
# And another
sf = City(name='San Francisco', state=ca)
sf.put()
# Print states
for state in us.states:
print state.name
# Print cities
for city in state.cities:
print ' ' + city.name
</code></pre>
<p>Should output:</p>
<pre><code>California
Los Angeles
San Francisco
</code></pre>
| 4 | 2009-07-29T11:57:51Z | [
"python",
"google-app-engine",
"django-models"
] |
importing modules with submodules from deep in a library | 1,199,743 | <p>here at office we have a library named after the company name and inside of it sublibraries, per project more or less, and in each sublibrary there might be more modules or libraries. we are using Django and this makes our hierarchy a couple of steps deeper...</p>
<p>I am a bit perplex about the differences among the following import instructions:</p>
<p>1:<pre>
import company.productline.specific.models, company.productline.base.models
specific, base = company.productline.specific, company.productline.base
</pre>
2:</p>
<pre>
import company.productline.specific.models, company.productline.base.models
from company.productline import specific, base
</pre>
<p>3:</p>
<pre>
from company.productline import specific, base
import company.productline.specific.models, company.productline.base.models
</pre>
<p>the first style imports only the <code>models</code>? what are then the names <code>specific</code> and <code>base</code> made available in the current namespace?</p>
<p>what happens in the initialization of modules if one imports first submodules and only afterwards the containing libraries?</p>
<p>maybe the neatest style is the last one, where it is clear (at least to me) that I first import the two modules and putting their names directly in the current namespace and that the second import adds the <code>model</code> submodule to both modules just imported.</p>
<p>on the other hand, (1) allows me to import only the inner modules and to refer to them in a compact though clear way (<code>specific.models</code> and <code>base.models</code>)</p>
<p>not so sure whether this is question, but I'm curious to read comments.</p>
| 0 | 2009-07-29T11:58:04Z | 1,199,846 | <p>The three examples above are all equivalent in practice. All of them are weird, though. There is no reason to do </p>
<pre><code>from company.productline import specific
</code></pre>
<p>and</p>
<pre><code>import company.productline.specific.models
</code></pre>
<p>You can (most of the time) just access models by <code>specific.models</code> after the first import.</p>
<p>It seems reasonable to in this case do</p>
<pre><code>from company.productline import base
from company.productline import specific
</code></pre>
<p>And then access these like <code>base.models</code>, <code>specific.whatever</code>, etc. If "specific" is a you also need to do a <code>import model</code> in <code>__init__.py</code> to be able to access specific.module.</p>
| 0 | 2009-07-29T12:16:55Z | [
"python",
"coding-style"
] |
importing modules with submodules from deep in a library | 1,199,743 | <p>here at office we have a library named after the company name and inside of it sublibraries, per project more or less, and in each sublibrary there might be more modules or libraries. we are using Django and this makes our hierarchy a couple of steps deeper...</p>
<p>I am a bit perplex about the differences among the following import instructions:</p>
<p>1:<pre>
import company.productline.specific.models, company.productline.base.models
specific, base = company.productline.specific, company.productline.base
</pre>
2:</p>
<pre>
import company.productline.specific.models, company.productline.base.models
from company.productline import specific, base
</pre>
<p>3:</p>
<pre>
from company.productline import specific, base
import company.productline.specific.models, company.productline.base.models
</pre>
<p>the first style imports only the <code>models</code>? what are then the names <code>specific</code> and <code>base</code> made available in the current namespace?</p>
<p>what happens in the initialization of modules if one imports first submodules and only afterwards the containing libraries?</p>
<p>maybe the neatest style is the last one, where it is clear (at least to me) that I first import the two modules and putting their names directly in the current namespace and that the second import adds the <code>model</code> submodule to both modules just imported.</p>
<p>on the other hand, (1) allows me to import only the inner modules and to refer to them in a compact though clear way (<code>specific.models</code> and <code>base.models</code>)</p>
<p>not so sure whether this is question, but I'm curious to read comments.</p>
| 0 | 2009-07-29T11:58:04Z | 1,205,070 | <p>so I have looked into it a bit deeper, using this further useless package:</p>
<pre><code>A:(__init__.py: print 'importing A',
B:(__init__.py: print 'importing B',
C1:(__init__.py: print 'importing C1',
D:(__init__.py: print 'importing D'))
C2:(__init__.py: print 'importing C2',
D:(__init__.py: print 'importing D'))))
</code></pre>
<p>notice that <code>C1</code> and <code>C2</code> contain two different modules, both named <code>D</code> in their different namespaces. I will need them both, I don't want to use the whole path A.B.C1.D and A.B.C2.D because that looks too clumsy and I can't put them both in the current namespace because one would overwrite the other and -no- I don't like the idea of changing their names. what I want is to have <code>C1</code> and <code>C2</code> in the current namespace and to load the two included <code>D</code> modules. </p>
<p>oh, yes: and I want the code to be readable.</p>
<p>I tried the two forms</p>
<pre><code>from A.B import C1
</code></pre>
<p>and the much uglier one</p>
<pre><code>import A.B.C1
C1 = A.B.C1
</code></pre>
<p>and I would conclude that they are equivalent:</p>
<p><hr /></p>
<pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2
>>> from A.B import C1
importing A
importing B
importing C1
>>> C1
<module 'A.B.C1' from 'A/B/C1/__init__.pyc'>
>>>
</code></pre>
<p><hr /></p>
<pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2
>>> import A.B.C1
importing A
importing B
importing C1
>>> C1=A.B.C1
>>> C1
<module 'A.B.C1' from 'A/B/C1/__init__.pyc'>
>>>
</code></pre>
<p>Importing package C1 or C2 does not import included modules just because they are there. and too bad that the form <code>from A.B import C1.D</code> is not syntactically accepted: that would be a nice compact thing to have.</p>
<p>on the other hand, I am offered the opportunity to do so in <code>A.B.C1.__init__.py</code> if I please. so if I append the line <code>import D</code> to the <code>__init__.py</code> in <code>A.B.C1</code>, this is what happens:</p>
<pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2
>>> from A.B import C1
importing A
importing B
importing C1
importing D
>>>
</code></pre>
<p>importing included modules is probably best done at the end of the package initialization.</p>
<p><hr /></p>
<p>considering all this and in given some specific django behaviour (that makes it difficult/impossible to automatically <code>import models</code> while importing the package), I think I prefer style 3.</p>
| 0 | 2009-07-30T07:55:58Z | [
"python",
"coding-style"
] |
Cython and numpy speed | 1,199,972 | <p>I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at that point. This method works very well and it's accurate enough.</p>
<p>The problem is that with pure python this takes more than one minute. With my cython code, it takes about 17 seconds. This still is too much. Do you have any hints how to speed-up this code:</p>
<pre><code>import numpy as np
cimport numpy as np
cimport cython
FTYPE = np.float
ctypedef np.float_t FTYPE_t
@cython.boundscheck(False)
def delay(np.ndarray[FTYPE_t, ndim=1] f, np.ndarray[FTYPE_t, ndim=1] g):
cdef int size1 = f.shape[0]
cdef int size2 = g.shape[0]
cdef int max_correlation = 0
cdef int delay = 0
cdef int current_correlation, i, j
# Move second data set frame by frame
for i in range(0, size1 - size2):
current_correlation = 0
# Calculate correlation at that point
for j in range(size2):
current_correlation += f[<unsigned int>(i+j)] * g[j]
# Check if current correlation is highest so far
if current_correlation > max_correlation:
max_correlation = current_correlation
delay = i
return delay
</code></pre>
| 13 | 2009-07-29T12:39:52Z | 1,200,064 | <p>The trick with this sort of thing is to find a way to divide and conquer.</p>
<p>Currently, you're sliding to every position and check every point at every position -- effectively an <strong>O</strong>( n ^ 2 ) operation.</p>
<p>You need to reduce the check of <em>every</em> point and the comparison of <em>every</em> position to something that does less work to determine a non-match.</p>
<p>For example, you could have a shorter "is this even close?" filter that checks the first few positions. If the correlation is above some threshold, then keep going otherwise give up and move on.</p>
<p>You could have a "check every 8th position" that you multiply by 8. If this is too low, skip it and move on. If this is high enough, then check all of the values to see if you've found the maxima.</p>
<p>The issue is the time required to do all these multiplies -- (<code>f[<unsigned int>(i+j)] * g[j]</code>) In effect, you're filling a big matrix with all these products and picking the row with the maximum sum. You don't want to compute "all" the products. Just enough of the products to be sure you've found the maximum sum.</p>
<p>The issue with finding maxima is that you have to sum <em>everything</em> to see if it's biggest. If you can turn this into a minimization problem, it's easier to abandon computing products and sums once an intermediate result exceeds a threshold.</p>
<p>(I think this might work. I have't tried it.)</p>
<p>If you used <code>max(g)-g[j]</code> to work with negative numbers, you'd be looking for the smallest, not the biggest. You could compute the correlation for the first position. Anything that summed to a bigger value could be stopped immediately -- no more multiplies or adds for that offset, shift to another.</p>
| 2 | 2009-07-29T12:58:22Z | [
"python",
"numpy",
"cython"
] |
Cython and numpy speed | 1,199,972 | <p>I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at that point. This method works very well and it's accurate enough.</p>
<p>The problem is that with pure python this takes more than one minute. With my cython code, it takes about 17 seconds. This still is too much. Do you have any hints how to speed-up this code:</p>
<pre><code>import numpy as np
cimport numpy as np
cimport cython
FTYPE = np.float
ctypedef np.float_t FTYPE_t
@cython.boundscheck(False)
def delay(np.ndarray[FTYPE_t, ndim=1] f, np.ndarray[FTYPE_t, ndim=1] g):
cdef int size1 = f.shape[0]
cdef int size2 = g.shape[0]
cdef int max_correlation = 0
cdef int delay = 0
cdef int current_correlation, i, j
# Move second data set frame by frame
for i in range(0, size1 - size2):
current_correlation = 0
# Calculate correlation at that point
for j in range(size2):
current_correlation += f[<unsigned int>(i+j)] * g[j]
# Check if current correlation is highest so far
if current_correlation > max_correlation:
max_correlation = current_correlation
delay = i
return delay
</code></pre>
| 13 | 2009-07-29T12:39:52Z | 1,200,096 | <ul>
<li>you can extract range(size2) from the external loop</li>
<li>you can use sum() instead of a loop to compute current_correlation</li>
<li>you can store correlations and delays in a list and then use max() to get the biggest one</li>
</ul>
| 2 | 2009-07-29T13:04:13Z | [
"python",
"numpy",
"cython"
] |
Cython and numpy speed | 1,199,972 | <p>I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at that point. This method works very well and it's accurate enough.</p>
<p>The problem is that with pure python this takes more than one minute. With my cython code, it takes about 17 seconds. This still is too much. Do you have any hints how to speed-up this code:</p>
<pre><code>import numpy as np
cimport numpy as np
cimport cython
FTYPE = np.float
ctypedef np.float_t FTYPE_t
@cython.boundscheck(False)
def delay(np.ndarray[FTYPE_t, ndim=1] f, np.ndarray[FTYPE_t, ndim=1] g):
cdef int size1 = f.shape[0]
cdef int size2 = g.shape[0]
cdef int max_correlation = 0
cdef int delay = 0
cdef int current_correlation, i, j
# Move second data set frame by frame
for i in range(0, size1 - size2):
current_correlation = 0
# Calculate correlation at that point
for j in range(size2):
current_correlation += f[<unsigned int>(i+j)] * g[j]
# Check if current correlation is highest so far
if current_correlation > max_correlation:
max_correlation = current_correlation
delay = i
return delay
</code></pre>
| 13 | 2009-07-29T12:39:52Z | 1,228,914 | <p><strong>Edit:</strong><br>
There's now <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.fftconvolve.html" rel="nofollow"><code>scipy.signal.fftconvolve</code></a> which would be the preferred approach to doing the FFT based convolution approach that I describe below. I'll leave the original answer to explain the speed issue, but in practice use <code>scipy.signal.fftconvolve</code>.</p>
<p><strong>Original answer:</strong><br>
Using <strong>FFTs</strong> and the <strong><a href="http://en.wikipedia.org/wiki/Convolution#Convolution_theorem" rel="nofollow">convolution theorem</a></strong> will give you dramatic speed gains by converting the problem from O(n^2) to O(n log n). This is particularly useful for long data sets, like yours, and can give speed gains of 1000s or much more, depending on length. It's also easy to do: just FFT both signals, multiply, and inverse FFT the product. <code>numpy.correlate</code> doesn't use the FFT method in the cross-correlation routine and is better used with very small kernels.</p>
<p>Here's an example</p>
<pre><code>from timeit import Timer
from numpy import *
times = arange(0, 100, .001)
xdata = 1.*sin(2*pi*1.*times) + .5*sin(2*pi*1.1*times + 1.)
ydata = .5*sin(2*pi*1.1*times)
def xcorr(x, y):
return correlate(x, y, mode='same')
def fftxcorr(x, y):
fx, fy = fft.fft(x), fft.fft(y[::-1])
fxfy = fx*fy
xy = fft.ifft(fxfy)
return xy
if __name__ == "__main__":
N = 10
t = Timer("xcorr(xdata, ydata)", "from __main__ import xcorr, xdata, ydata")
print 'xcorr', t.timeit(number=N)/N
t = Timer("fftxcorr(xdata, ydata)", "from __main__ import fftxcorr, xdata, ydata")
print 'fftxcorr', t.timeit(number=N)/N
</code></pre>
<p>Which gives the running times per cycle (in seconds, for a 10,000 long waveform)</p>
<pre><code>xcorr 34.3761689901
fftxcorr 0.0768054962158
</code></pre>
<p>It's clear the fftxcorr method is much faster.</p>
<p>If you plot out the results, you'll see that they are very similar near zero time shift. Note, though, as you get further away the xcorr will decrease and the fftxcorr won't. This is because it's a bit ambiguous what to do with the parts of the waveform that don't overlap when the waveforms are shifted. xcorr treats it as zero and the FFT treats the waveforms as periodic, but if it's an issue it can be fixed by zero padding.</p>
| 35 | 2009-08-04T17:40:00Z | [
"python",
"numpy",
"cython"
] |
Django CharField limitations | 1,200,046 | <p>how can I specify a blacklist for a CharField. However I want the blacklist to be effective in the Django admin panel aswell...otherwise I would just validate it in the view.</p>
<p>By blacklist I mean values that can't be used. I also set unique for the value but I would like to disable a few strings aswell.</p>
<p>Thanks,
Max</p>
| 1 | 2009-07-29T12:54:25Z | 1,200,069 | <p>This is not possible out of the box. You would have to write a <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation" rel="nofollow">custom form field</a> or otherwise add <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get%5Furls" rel="nofollow">custom admin handling</a> to do admin-level validation. To do it at the database level, I suspect you would need to set up some kind of trigger and stored procedure, but that's not my area so I'll leave that to others.</p>
| 0 | 2009-07-29T12:59:15Z | [
"python",
"django"
] |
Django CharField limitations | 1,200,046 | <p>how can I specify a blacklist for a CharField. However I want the blacklist to be effective in the Django admin panel aswell...otherwise I would just validate it in the view.</p>
<p>By blacklist I mean values that can't be used. I also set unique for the value but I would like to disable a few strings aswell.</p>
<p>Thanks,
Max</p>
| 1 | 2009-07-29T12:54:25Z | 1,200,373 | <p>I would override the model's save() method and the to be inserted value against a blacklist before calling the parent class' save() method.</p>
<p>Something like that (simplified):</p>
<pre><code>class BlackListModel(models.Model):
blacklist = ['a', 'b', 'c']
# your model fields definitions...
def save(self, *args, **kwargs):
if self.blacklist_field in self.blacklist:
raise Exception("Attempting to save a blacklisted value!")
return super(BlackListModel, self).save(*args, **kwargs)
</code></pre>
<p>That way it works in all of your applications.</p>
| 1 | 2009-07-29T13:42:12Z | [
"python",
"django"
] |
Writing a Template Tag in Django | 1,200,548 | <p>I'm trying to customise a CMS written in Django. The content editors aren't flexible enough so I'm trying to come up with a better solution.</p>
<p>Without over-explaining it, I'd like it to be a bit like <a href="http://bitbucket.org/hakanw/django-better-chunks/wiki/Home" rel="nofollow">django-better-chunks</a> or <code>django-flatblocks</code>. You set up an editable region entirely from within the template. I want to bind these editable regions to a mix of strings and object instances. One example would be having multiple editable regions based on one product:</p>
<pre><code>{% block product_instance "title" %}
{% block product_instance "product description" %}
</code></pre>
<p>So if you have a view with another product as <code>product_instance</code> those two <code>blocks</code> would show different data. I would also see there being use for site-wide blocks that only pass through the string part. Essentially, I would like to be able to pass 1-infinity identifiers.</p>
<p>But I'm really struggling on two fronts here:</p>
<ol>
<li><p>How do I define the relationship between the mixed identifier and the actual content "<code>block</code>" instance? I have a feeling contenttypes might feature here but I've really no idea where to start looking!</p></li>
<li><p>And how do I write a template tag to read the above syntax and convert that into an object for rendering?</p></li>
</ol>
| 1 | 2009-07-29T14:12:16Z | 1,828,445 | <p>for this you can create an inclusion tag and use it like:</p>
<pre><code>{% load my_tags %}
{% product bicycle <extra vars ...> %}
</code></pre>
<p>To define the tag, add to your app/templatetags/mytags.py:</p>
<pre><code>@register.inclusion_tag('results.html')
def product(item, *extra):
#maybe repackage extra variables
#and add them to the returned dictionary
item_form = ItemForm(item) #form.ModelForm instance
return {'item': item, 'item_form':item_form, ...}
</code></pre>
<p>Then you'll need a template that returns html for the item:</p>
<pre><code><h1>{{item.title}}</h1>
{{item_form}}
... add some conditional statements depending on extra vars
</code></pre>
| 2 | 2009-12-01T19:50:52Z | [
"python",
"django",
"django-templates"
] |
Which events can be bound to a Tkinter Frame? | 1,200,592 | <p>I am making a small application with Tkinter. I would like to clean few things in a function called when my window is closed. I am trying to bind the <em>close event</em> of my window with that function. I don't know if it is possible and what is the corresponding sequence.</p>
<p>The Python documentation says: <code>See the bind man page and page 201 of John Ousterhoutâs book for details</code>.</p>
<p>Unfortunately, I don't have these resources in my hands. Does anybody know the list of events that can be bound?</p>
<p>An alternative solution would be to clean everything in the <code>__del__</code> of my Frame class. For an unknown reason it seems that it is never called. Does anybody knows what can be the cause? Some circular dependencies? </p>
<p>As soon as, I add a control (uncomment in the code below), the <code>__del__</code> is not called anymore. Any solution for that problem?</p>
<pre><code>from tkinter import *
class MyDialog(Frame):
def __init__(self):
print("hello")
self.root = Tk()
self.root.title("Test")
Frame.__init__(self, self.root)
self.list = Listbox(self, selectmode=BROWSE)
self.list.pack(fill=BOTH, expand=1)
self.pack(fill=BOTH, expand=1)
def __del__(self):
print("bye-bye")
dialog = MyDialog()
dialog.root.mainloop()
</code></pre>
| 1 | 2009-07-29T14:18:04Z | 1,200,907 | <p>I believe <a href="http://tcl.tk/man/tcl8.5/TkCmd/bind.htm" rel="nofollow">this</a> is the bind man page you may have been looking for; I believe the event you're trying to bind is <code>Destroy</code>. <code>__del__</code> is not to be relied on (just too hard to know when a circular reference loop, e.g. parent to child widget and back, will stop it from triggering!), using event binding is definitely preferable.</p>
| 3 | 2009-07-29T14:59:32Z | [
"python",
"python-3.x",
"tkinter"
] |
Which events can be bound to a Tkinter Frame? | 1,200,592 | <p>I am making a small application with Tkinter. I would like to clean few things in a function called when my window is closed. I am trying to bind the <em>close event</em> of my window with that function. I don't know if it is possible and what is the corresponding sequence.</p>
<p>The Python documentation says: <code>See the bind man page and page 201 of John Ousterhoutâs book for details</code>.</p>
<p>Unfortunately, I don't have these resources in my hands. Does anybody know the list of events that can be bound?</p>
<p>An alternative solution would be to clean everything in the <code>__del__</code> of my Frame class. For an unknown reason it seems that it is never called. Does anybody knows what can be the cause? Some circular dependencies? </p>
<p>As soon as, I add a control (uncomment in the code below), the <code>__del__</code> is not called anymore. Any solution for that problem?</p>
<pre><code>from tkinter import *
class MyDialog(Frame):
def __init__(self):
print("hello")
self.root = Tk()
self.root.title("Test")
Frame.__init__(self, self.root)
self.list = Listbox(self, selectmode=BROWSE)
self.list.pack(fill=BOTH, expand=1)
self.pack(fill=BOTH, expand=1)
def __del__(self):
print("bye-bye")
dialog = MyDialog()
dialog.root.mainloop()
</code></pre>
| 1 | 2009-07-29T14:18:04Z | 1,200,931 | <p>A more-or-less definitive resource for events is the <a href="http://tcl.tk/man/tcl8.6/TkCmd/bind.htm" rel="nofollow">bind man page for Tk</a>. I'm not exactly clear what you're wanting to do, but binding on <code>"<Destroy>"</code> is probably the event you are looking for. Whether it does what you really need, I don't know. </p>
<pre><code> ...
self.bind("<Destroy>", self.callback)
...
def callback(self, event):
print("callback called")
</code></pre>
| 3 | 2009-07-29T15:02:49Z | [
"python",
"python-3.x",
"tkinter"
] |
Python wx (Python Card) logging subprocess output to window | 1,200,610 | <p>There are <a href="http://stackoverflow.com/questions/531708/logging-output-of-external-program-with-wxpython">similar</a> <a href="http://stackoverflow.com/questions/865082/python-plugging-wx-py-shell-shell-into-a-separate-process">questions</a> to this one, but I'd like to see a clarified answer. I'm building a simple GUI with PythonCard to wrap a command line process. Specifically, it's a wrapper for a series of ANT Tasks and other custom operations so non-devs can use it.</p>
<p>I'd like to redirect the output of the subprocess to a TextArea in the window. It looks like the way to do this is to use <code>subprocess.Popen(command, stdout=subprocess.PIPE)</code> and load the output to a variable. </p>
<p>The question is how do I live update the window with the output of the subprocess? Any hints would be welcome</p>
<p>Thanks</p>
| 1 | 2009-07-29T14:20:31Z | 1,200,684 | <p>Just about every subprocess you can wrap will buffer its output unless you manage to fool it into believing it's actually connected to a terminal -- and subprocess can't do that. Rather, look into <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> (runs well on every platform that lets you have a pseudoterminal, i.e., every platform except Microsoft Windows; on Windows you might try <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/" rel="nofollow">wexpect</a> but I have no experience with the latter).</p>
<p>These modules give you the subprocess's output as soon as it's produced, and strive to fool the module into producing that output ASAP and without buffering, so they should make it easy for you to receive that output in real time and append it to the text field you want to keep updating.</p>
| 1 | 2009-07-29T14:29:38Z | [
"python",
"wxpython",
"pythoncard"
] |
Python wx (Python Card) logging subprocess output to window | 1,200,610 | <p>There are <a href="http://stackoverflow.com/questions/531708/logging-output-of-external-program-with-wxpython">similar</a> <a href="http://stackoverflow.com/questions/865082/python-plugging-wx-py-shell-shell-into-a-separate-process">questions</a> to this one, but I'd like to see a clarified answer. I'm building a simple GUI with PythonCard to wrap a command line process. Specifically, it's a wrapper for a series of ANT Tasks and other custom operations so non-devs can use it.</p>
<p>I'd like to redirect the output of the subprocess to a TextArea in the window. It looks like the way to do this is to use <code>subprocess.Popen(command, stdout=subprocess.PIPE)</code> and load the output to a variable. </p>
<p>The question is how do I live update the window with the output of the subprocess? Any hints would be welcome</p>
<p>Thanks</p>
| 1 | 2009-07-29T14:20:31Z | 1,811,747 | <p>I was searching for a solution for this too. It turns out the solution is remarkably simple:
<p>
proc = subprocess.Popen("whatever program", cwd="startup dir", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
<br>
while True:
<br>
txt = proc.stdout.readline()
<br>
if not txt: break
<br>
txt=txt.replace("\r\n","\n").replace("\r\n","\n").replace("\\","\")
<br>
self.components.taStdout.appendText(txt)</p>
| 1 | 2009-11-28T06:09:12Z | [
"python",
"wxpython",
"pythoncard"
] |
python interpolation | 1,200,644 | <p>I have a set of data's as,</p>
<pre><code>Table-1
X1 | Y1
------+--------
0.1 | 0.52147
0.02 | 0.8879
0.08 | 0.901
0.11 | 1.55
0.15 | 1.82
0.152 | 1.95
Table-2
X2 | Y2
-----+------
0.2 | 0.11
0.21 | 0.112
0.34 | 0.120
0.33 | 1.121
</code></pre>
<p>I have to interpolate Table-2 'Y2' value for Table-1 'X1' value like,</p>
<pre><code> X1 | Y2
-------+-------
0.1 |
0.02 |
0.08 |
0.11 |
0.15 |
0.152 |
</code></pre>
<p>Note: Both Table-1 & 2 are unequal intervals with number of (X | Y) entries will differ, for eg. here we have 6 (X1 | Y1) entries in Table-1 and only 4 (X2 | Y2) in Table-2</p>
<p>Please help me which interpolation algorithm to use in Numpy, and how to proceed?</p>
| 17 | 2009-07-29T14:25:01Z | 1,200,722 | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html">numpy.interp</a> seems to be the function you want: pass your X1 as the first argument x, your X2 as the second argument xp, your Y2 as the third argument fp, and you'll get the Y values corresponding to the X1 coordinates (looks like you want to completely ignore the existing Y1, right? this is what this does - otherwise you'll have to clarify your question much better explaining what role you have in might for the Y1's!).</p>
<p>If you want more than linear interpolation, I suggest you see <a href="http://docs.scipy.org/doc/scipy/reference/interpolate.html">scipy.interpolate</a> and its <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html">tutorial</a> rather than trying to stretch numpy beyond its simplicity;-).</p>
| 25 | 2009-07-29T14:35:04Z | [
"python",
"numpy"
] |
How to get lxml working under IronPython? | 1,200,726 | <p>I need to port some code that relies heavily on lxml from a CPython application to IronPython.</p>
<p>lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions.</p>
<p>Does anyone know of a workaround to allow lxml under IronPython or a version of lxml that doesn't have those C-extension dependencies?</p>
| 6 | 2009-07-29T14:36:12Z | 1,211,395 | <p>Something which you might have already considered: </p>
<p>An alternative is to first port the lxml library to IPy and then your code (depending on the code size). You might have to write some C# wrappers for the native C calls to the C extensions -- I'm not sure what issues, if any, are involved in this with regards to IPy.</p>
<p>Or if the code which you are porting is small, as compared to lxml, then maybe you can just remove the lxml dependency and use the .NET XML libraries.</p>
| 1 | 2009-07-31T08:54:27Z | [
".net",
"xml",
"ironpython",
"python",
"lxml"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.