title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,242 | <pre><code>>>> import string
>>> safechars = '_-.()' + string.digits + string.ascii_letters
>>> allchars = string.maketrans('', '')
>>> deletions = ''.join(set(allchars) - set(safechars))
>>> filename = '#abc.$%.txt'
>>> safe_filename = string.translate(filename, allchars, deletions)
>>> safe_filename
'abc..txt'
>>>
</code></pre>
<p>The above code doesn't work for unicode strings. It doesn't handle empty strings, special filenames ('nul', 'con', etc) also.</p>
| 6 | 2008-11-17T10:15:15Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,298 | <p>Keep in mind, there are actually no restrictions on filenames on Unix systems other than </p>
<ul>
<li>It may not contain \0 </li>
<li>It may not contain /</li>
</ul>
<p>Everything else is fair game. </p>
<pre>
$ touch "
> even multiline
> haha
> ^[[31m red ^[[0m
> evil"
$ ls -la
-rw-r--r-- 0 Nov 17 23:39 ?even multiline?haha??[31m red ?[0m?evil
$ ls -lab
-rw-r--r-- 0 Nov 17 23:39 \neven\ multiline\nhaha\n\033[31m\ red\ \033[0m\nevil
$ perl -e 'for my $i ( glob(q{./*even*}) ){ print $i; } '
./
even multiline
haha
red
evil
</pre>
<p>Yes, i just stored ANSI Colour Codes in a file name and had them take effect. </p>
<p>For entertainment, put a BEL character in a directory name and watch the fun that ensues when you CD into it ;) </p>
| 12 | 2008-11-17T10:45:54Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,354 | <p>Why not just wrap the "osopen" with a try/except and let the underlying OS sort out whether the file is valid?</p>
<p>This seems like much less work and is valid no matter which OS you use.</p>
| 6 | 2008-11-17T11:24:49Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,466 | <p>You can look at the <a href="http://www.djangoproject.com" rel="nofollow">Django framework</a> for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly.</p>
<p>Their <code>template/defaultfilters.py</code> (at around line 183) defines a function, <code>slugify</code>, that's probably the gold standard for this kind of thing. Essentially, their code is the following.</p>
<pre><code>def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
value = unicode(re.sub('[-\s]+', '-', value))
</code></pre>
<p>There's more, but I left it out, since it doesn't address slugification, but escaping.</p>
| 84 | 2008-11-17T12:23:52Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 295,560 | <p>Another issue that the other comments haven't addressed yet is the empty string, which is obviously not a valid filename. You can also end up with an empty string from stripping too many characters.</p>
<p>What with the Windows reserved filenames and issues with dots, the safest answer to the question âhow do I normalise a valid filename from arbitrary user input?â is âdon't even bother tryâ: if you can find any other way to avoid it (eg. using integer primary keys from a database as filenames), do that.</p>
<p>If you must, and you really need to allow spaces and â.â for file extensions as part of the name, try something like:</p>
<pre><code>import re
badchars= re.compile(r'[^A-Za-z0-9_. ]+|^\.|\.$|^ | $|^$')
badnames= re.compile(r'(aux|com[1-9]|con|lpt[1-9]|prn)(\.|$)')
def makeName(s):
name= badchars.sub('_', s)
if badnames.match(name):
name= '_'+name
return name
</code></pre>
<p>Even this can't be guaranteed right especially on unexpected OSsâââfor example RISC OS hates spaces and uses â.â as a directory separator.</p>
| 4 | 2008-11-17T13:24:19Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 634,023 | <p>Though you have to be careful. It is not clearly said in your intro, if you are looking only at latine language. Some words can become meaningless or another meaning if you sanitize them with ascii characters only.</p>
<p>imagine you have "forêt poésie" (forest poetry), your sanitization might give "fort-posie" (strong + something meaningless)</p>
<p>Worse if you have to deal with chinese characters.</p>
<p>"ä¸åæ²¢" your system might end up doing "---" which is doomed to fail after a while and not very helpful. So if you deal with only files I would encourage to either call them a generic chain that you control or to keep the characters as it is. For URIs, about the same.</p>
| 4 | 2009-03-11T10:44:46Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 698,714 | <p>This is the solution I ultimately used:</p>
<pre><code>import unicodedata
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
</code></pre>
<p>The unicodedata.normalize call replaces accented characters with the unaccented equivalent, which is better than simply stripping them out. After that all disallowed characters are removed.</p>
<p>My solution doesn't prepend a known string to avoid possible disallowed filenames, because I know they can't occur given my particular filename format. A more general solution would need to do so.</p>
| 12 | 2009-03-30T19:40:17Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 1,108,783 | <p><strong>UPDATE</strong></p>
<p>All links broken beyond repair in this 6 year old answer.</p>
<p>Also, I also wouldn't do it this way anymore, just <code>base64</code> encode or drop unsafe chars. Python 3 example:</p>
<pre><code>import re
t = re.compile("[a-zA-Z0-9.,_-]")
unsafe = "abcâéåîâËË©¬ñâÆÂµÂ©ââ«Ã¸"
safe = [ch for ch in unsafe if t.match(ch)]
# => 'abc'
</code></pre>
<p>With <code>base64</code> you can encode and decode, so you can retrieve the original filename again.</p>
<p>But depending on the use case you might be better off generating a random filename and storing the metadata in separate file or DB.</p>
<pre><code>from random import choice
from string import ascii_lowercase, ascii_uppercase, digits
allowed_chr = ascii_lowercase + ascii_uppercase + digits
safe = ''.join([choice(allowed_chr) for _ in range(16)])
# => 'CYQ4JDKE9JfcRzAZ'
</code></pre>
<p><strong>ORIGINAL LINKROTTEN ANSWER</strong>:</p>
<p>The <code>bobcat</code> project contains a python module that does just this.</p>
<p>It's not completely robust, see this <a href="http://mail.python.org/pipermail/python-list/2007-September/628023.html" rel="nofollow">post</a> and this <a href="http://mail.python.org/pipermail/python-list/2007-September/628042.html" rel="nofollow">reply</a>.</p>
<p>So, as noted: <code>base64</code> encoding is probably a better idea if readability doesn't matter.</p>
<ul>
<li>Docs <a href="https://svn.origo.ethz.ch/bobcat/src-doc/safefilename-module.html" rel="nofollow">https://svn.origo.ethz.ch/bobcat/src-doc/safefilename-module.html</a></li>
<li>Source <a href="https://svn.origo.ethz.ch/bobcat/trunk/src/bobcatlib/safefilename.py" rel="nofollow">https://svn.origo.ethz.ch/bobcat/trunk/src/bobcatlib/safefilename.py</a></li>
</ul>
| 0 | 2009-07-10T10:19:11Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 10,458,710 | <p>I'm sure this isn't a great answer, since it modifies the string it's looping over, but it seems to work alright:</p>
<pre><code>import string
for chr in your_string:
if chr == ' ':
your_string = your_string.replace(' ', '_')
elif chr not in string.ascii_letters or chr not in string.digits:
your_string = your_string.replace(chr, '')
</code></pre>
| 0 | 2012-05-05T03:56:00Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 10,610,768 | <p>Most of these solutions don't work.</p>
<p>'/hello/world' -> 'helloworld'</p>
<p>'/helloworld'/ -> 'helloworld'</p>
<p>This isn't what you want generally, say you are saving the html for each link, you're going to overwrite the html for a different webpage.</p>
<p>I pickle a dict such as:</p>
<pre><code>{'helloworld':
(
{'/hello/world': 'helloworld', '/helloworld/': 'helloworld1'},
2)
}
</code></pre>
<p>2 represents the number that should be appended to the next filename.</p>
<p>I look up the filename each time from the dict. If it's not there, I create a new one, appending the max number if needed.</p>
| 2 | 2012-05-16T01:04:34Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 25,808,207 | <p>Not exactly what OP was asking for but this is what I use because I need unique and reversible conversions:</p>
<pre><code># p3 code
def safePath (url):
return ''.join(map(lambda ch: chr(ch) if ch in safePath.chars else '%%%02x' % ch, url.encode('utf-8')))
safePath.chars = set(map(lambda x: ord(x), '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-_ .'))
</code></pre>
<p>Result is "somewhat" readable, at least from a sysadmin point of view.</p>
| 0 | 2014-09-12T12:19:39Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 29,942,164 | <p>There is a nice project on Github called <a href="https://github.com/un33k/python-slugify">python-slugify</a>: </p>
<p>Install:</p>
<pre><code>pip install python-slugify
</code></pre>
<p>Then use:</p>
<pre><code>>>> from slugify import slugify
>>> txt = "This\ is/ a%#$ test ---"
>>> slugify(txt)
'this-is-a-test'
</code></pre>
| 7 | 2015-04-29T11:19:47Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
Turn a string into a valid filename in Python | 295,135 | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p>
| 160 | 2008-11-17T09:02:07Z | 38,766,141 | <p>In one line:</p>
<pre><code>valid_file_name = re.sub('[^\w_.)( -]', '', any_string)
</code></pre>
<p>you can also put '_' character to make it more readable (in case of replacing slashs, for example)</p>
| 1 | 2016-08-04T11:29:03Z | [
"python",
"filenames",
"slug",
"sanitize"
] |
How do I add a directory with a colon to PYTHONPATH? | 295,195 | <p>The problem is simple:</p>
<p>Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following</p>
<pre><code>export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"
</code></pre>
<p>None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required?</p>
| 3 | 2008-11-17T09:46:19Z | 295,226 | <p>There is only one you didn't try: </p>
<pre><code>export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com\:3344/"
</code></pre>
<p>The problem is without the quotes, the escaping is interpreted directly, and converted into a literal ":" in the string. But the ":" needs to be evaluated later. </p>
<pre><code>$ echo "foo:"
foo:
$ echo \:foo
:foo
$ echo ":foo"
:foo
$ echo "\:foo"
\:foo
</code></pre>
<p>I can't guarantee this will fix your python-path problem, but it will get the \ literal into the string. </p>
| 1 | 2008-11-17T10:08:42Z | [
"python",
"bash",
"shell"
] |
How do I add a directory with a colon to PYTHONPATH? | 295,195 | <p>The problem is simple:</p>
<p>Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following</p>
<pre><code>export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"
</code></pre>
<p>None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required?</p>
| 3 | 2008-11-17T09:46:19Z | 295,233 | <p>I don't know if what you want is directly possible, but a workaround if you are using a linux filesystem would be to create a symlink to your "coloned" directory and add this symlink to your PYTHONPATH like this:</p>
<pre><code>ln -s /home/shane/mywebsite.com\:3344 /home/shane/mywebsite.3344
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.3344
</code></pre>
| 1 | 2008-11-17T10:10:58Z | [
"python",
"bash",
"shell"
] |
How do I add a directory with a colon to PYTHONPATH? | 295,195 | <p>The problem is simple:</p>
<p>Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following</p>
<pre><code>export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"
</code></pre>
<p>None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required?</p>
| 3 | 2008-11-17T09:46:19Z | 295,249 | <p>The symlink hack is probably the only viable option, unless there is some heuristic to determine how to handle colons in PYTHONPATH.</p>
| 0 | 2008-11-17T10:17:31Z | [
"python",
"bash",
"shell"
] |
How do I add a directory with a colon to PYTHONPATH? | 295,195 | <p>The problem is simple:</p>
<p>Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following</p>
<pre><code>export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"
</code></pre>
<p>None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required?</p>
| 3 | 2008-11-17T09:46:19Z | 295,276 | <p>The problem is not with bash. It should be setting your environment variable correctly, complete with the <code>:</code> character.</p>
<p>The problem, instead, is with Python's parsing of the <code>PYTHONPATH</code> variable. Following the example set by the <a href="http://sourceware.org/cgi-bin/cvsweb.cgi/libc/posix/execvp.c?rev=1.27&content-type=text/x-cvsweb-markup&cvsroot=glibc"><code>PATH</code> variable</a>, it seems there is no escape character at all, so there is no way to make it interpret the <code>:</code> as something other than a separator. You can see it for yourself in the <a href="http://svn.python.org/view/python/trunk/Modules/getpath.c?rev=54257&view=auto">Python interpreter source code</a>.</p>
<p>The only solution is, as several people already mentioned, to use a symlink or something else to allow you to give a colon-less name for your directories.</p>
| 7 | 2008-11-17T10:38:26Z | [
"python",
"bash",
"shell"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 295,465 | <p>Probably the best way to handle this is to split up the code, so that logic that processes the page contents is split from the code that fetches the page.</p>
<p>Then pass an instance of the fetcher code into the processing logic, then you can easily replace it with a mock fetcher for the unit test.</p>
<p>e.g.</p>
<pre><code>class Processor(oject):
def __init__(self, fetcher):
self.m_fetcher = fetcher
def doProcessing(self):
## use self.m_fetcher to get page contents
class RealFetcher(object):
def fetchPage(self, url):
## get real contents
class FakeFetcher(object):
def fetchPage(self, url):
## Return whatever fake contents are required for this test
</code></pre>
| 8 | 2008-11-17T12:23:30Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 295,469 | <p>The simplest way is to change your function so that it doesn't necessarily use urllib.urlopen. Let's say this is your original function:</p>
<pre><code>def my_grabber(arg1, arg2, arg3):
# .. do some stuff ..
url = make_url_somehow()
data = urllib.urlopen(url)
# .. do something with data ..
return answer
</code></pre>
<p>Add an argument which is the function to use to open the URL. Then you can provide a mock function to do whatever you need:</p>
<pre><code>def my_grabber(arg1, arg2, arg3, urlopen=urllib.urlopen):
# .. do some stuff ..
url = make_url_somehow()
data = urlopen(url)
# .. do something with data ..
return answer
def test_my_grabber():
my_grabber(arg1, arg2, arg3, urlopen=my_mock_open)
</code></pre>
| 4 | 2008-11-17T12:26:06Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 295,481 | <p>Another simple approach is to have your test override urllib's <code>urlopen()</code> function. For example, if your module has</p>
<pre><code>import urllib
def some_function_that_uses_urllib():
...
urllib.urlopen()
...
</code></pre>
<p>You could define your test like this:</p>
<pre><code>import mymodule
def dummy_urlopen(url):
...
mymodule.urllib.urlopen = dummy_urlopen
</code></pre>
<p>Then, when your tests invoke functions in <code>mymodule</code>, <code>dummy_urlopen()</code> will be called instead of the real <code>urlopen()</code>. Dynamic languages like Python make it super easy to stub out methods and classes for testing.</p>
<p>See my blog posts at <a href="http://softwarecorner.wordpress.com/">http://softwarecorner.wordpress.com/</a> for more information about stubbing out dependencies for tests.</p>
| 78 | 2008-11-17T12:32:42Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 295,503 | <p>Did you give <a href="https://pypi.python.org/pypi/mox" rel="nofollow">Mox</a> a look? It should do everything you need. Here is a simple interactive session illustrating the solution you need:</p>
<pre><code>>>> import urllib
>>> # check that it works
>>> urllib.urlopen('http://www.google.com/')
<addinfourl at 3082723820L ...>
>>> # check what happens when it doesn't
>>> urllib.urlopen('http://hopefully.doesnotexist.com/')
#-- snip --
IOError: [Errno socket error] (-2, 'Name or service not known')
>>> # OK, let's mock it up
>>> import mox
>>> m = mox.Mox()
>>> m.StubOutWithMock(urllib, 'urlopen')
>>> # We can be verbose if we want to :)
>>> urllib.urlopen(mox.IgnoreArg()).AndRaise(
... IOError('socket error', (-2, 'Name or service not known')))
>>> # Let's check if it works
>>> m.ReplayAll()
>>> urllib.urlopen('http://www.google.com/')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/mox.py", line 568, in __call__
raise expected_method._exception
IOError: [Errno socket error] (-2, 'Name or service not known')
>>> # yay! now unset everything
>>> m.UnsetStubs()
>>> m.VerifyAll()
>>> # and check that it still works
>>> urllib.urlopen('http://www.google.com/')
<addinfourl at 3076773548L ...>
</code></pre>
| 26 | 2008-11-17T12:49:46Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 2,392,989 | <p>I am using <a href="http://www.voidspace.org.uk/python/mock/">Mock's</a> patch decorator:</p>
<pre><code>from mock import patch
[...]
@patch('urllib.urlopen')
def test_foo(self, urlopen_mock):
urlopen_mock.return_value = MyUrlOpenMock()
</code></pre>
| 58 | 2010-03-06T15:31:31Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 6,644,608 | <p>In case you don't want to even load the module:</p>
<pre><code>import sys,types
class MockCallable():
""" Mocks a function, can be enquired on how many calls it received """
def __init__(self, result):
self.result = result
self._calls = []
def __call__(self, *arguments):
"""Mock callable"""
self._calls.append(arguments)
return self.result
def called(self):
"""docstring for called"""
return self._calls
class StubModule(types.ModuleType, object):
""" Uses a stub instead of loading libraries """
def __init__(self, moduleName):
self.__name__ = moduleName
sys.modules[moduleName] = self
def __repr__(self):
name = self.__name__
mocks = ', '.join(set(dir(self)) - set(['__name__']))
return "<StubModule: %(name)s; mocks: %(mocks)s>" % locals()
class StubObject(object):
pass
</code></pre>
<p>And then:</p>
<pre><code>>>> urllib = StubModule("urllib")
>>> import urllib # won't actually load urllib
>>> urls.urlopen = MockCallable(StubObject())
>>> example = urllib.urlopen('http://example.com')
>>> example.read = MockCallable('foo')
>>> print(example.read())
'foo'
</code></pre>
| 6 | 2011-07-11T00:12:41Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How can one mock/stub python module like urllib | 295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| 57 | 2008-11-17T12:07:40Z | 13,296,807 | <p><a href="https://github.com/gabrielfalcao/HTTPretty" rel="nofollow">HTTPretty</a> works in the exact same way that FakeWeb does. HTTPretty works in the socket layer, so it should work intercepting any python http client libraries. It's battle tested against urllib2, httplib2 and requests</p>
<pre><code>import urllib2
from httpretty import HTTPretty, httprettified
@httprettified
def test_one():
HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/",
body="Find the best daily deals")
fd = urllib2.urlopen('http://yipit.com')
got = fd.read()
fd.close()
assert got == "Find the best daily deals"
</code></pre>
| 13 | 2012-11-08T20:01:37Z | [
"python",
"unit-testing",
"testing",
"mocking"
] |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| 27 | 2008-11-17T12:17:49Z | 295,471 | <p><a href="http://web.archive.org/web/20081222144252/http://www.python.org/doc/2.5.2/lib/node535.html" rel="nofollow">http://www.python.org/doc/2.5.2/lib/node535.html</a> covered this pretty well. Is there some part of this you didn't understand?</p>
<p>Your program would be pretty similar, but the second <code>Popen</code> would have stdout= to a file, and you wouldn't need the output of its <code>.communicate()</code>.</p>
| 3 | 2008-11-17T12:26:50Z | [
"python",
"pipe",
"subprocess"
] |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| 27 | 2008-11-17T12:17:49Z | 295,564 | <p>You'd be a little happier with the following.</p>
<pre><code>import subprocess
awk_sort = subprocess.Popen( "awk -f script.awk | sort > outfile.txt",
stdin=subprocess.PIPE, shell=True )
awk_sort.communicate( b"input data\n" )
</code></pre>
<p>Delegate part of the work to the shell. Let it connect two processes with a pipeline.</p>
<p>You'd be a lot happier rewriting 'script.awk' into Python, eliminating awk and the pipeline.</p>
<p><strong>Edit</strong>. Some of the reasons for suggesting that awk isn't helping.</p>
<p>[There are too many reasons to respond via comments.]</p>
<ol>
<li><p>Awk is adding a step of no significant value. There's nothing unique about awk's processing that Python doesn't handle.</p></li>
<li><p>The pipelining from awk to sort, for large sets of data, may improve elapsed processing time. For short sets of data, it has no significant benefit. A quick measurement of <code>awk >file ; sort file</code> and <code>awk | sort</code> will reveal of concurrency helps. With sort, it rarely helps because sort is not a once-through filter.</p></li>
<li><p>The simplicity of "Python to sort" processing (instead of "Python to awk to sort") prevents the exact kind of questions being asked here.</p></li>
<li><p>Python -- while wordier than awk -- is also explicit where awk has certain implicit rules that are opaque to newbies, and confusing to non-specialists.</p></li>
<li><p>Awk (like the shell script itself) adds Yet Another Programming language. If all of this can be done in one language (Python), eliminating the shell and the awk programming eliminates two programming languages, allowing someone to focus on the value-producing parts of the task.</p></li>
</ol>
<p>Bottom line: awk can't add significant value. In this case, awk is a net cost; it added enough complexity that it was necessary to ask this question. Removing awk will be a net gain.</p>
<p><strong>Sidebar</strong> Why building a pipeline (<code>a | b</code>) is so hard.</p>
<p>When the shell is confronted with <code>a | b</code> it has to do the following.</p>
<ol>
<li><p>Fork a child process of the original shell. This will eventually become b.</p></li>
<li><p>Build an os pipe. (not a Python subprocess.PIPE) but call <code>os.pipe()</code> which returns two new file descriptors that are connected via common buffer. At this point the process has stdin, stdout, stderr from its parent, plus a file that will be "a's stdout" and "b's stdin". </p></li>
<li><p>Fork a child. The child replaces its stdout with the new a's stdout. Exec the <code>a</code> process.</p></li>
<li><p>The b child closes replaces its stdin with the new b's stdin. Exec the <code>b</code> process.</p></li>
<li><p>The b child waits for a to complete. </p></li>
<li><p>The parent is waiting for b to complete.</p></li>
</ol>
<p>I think that the above can be used recursively to spawn <code>a | b | c</code>, but you have to implicitly parenthesize long pipelines, treating them as if they're <code>a | (b | c)</code>.</p>
<p>Since Python has <code>os.pipe()</code>, <code>os.exec()</code> and <code>os.fork()</code>, and you can replace <code>sys.stdin</code> and <code>sys.stdout</code>, there's a way to do the above in pure Python. Indeed, you may be able to work out some shortcuts using <code>os.pipe()</code> and <code>subprocess.Popen</code>.</p>
<p>However, it's easier to delegate that operation to the shell.</p>
| 27 | 2008-11-17T13:32:13Z | [
"python",
"pipe",
"subprocess"
] |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| 27 | 2008-11-17T12:17:49Z | 9,164,238 | <pre><code>import subprocess
some_string = b'input_data'
sort_out = open('outfile.txt', 'wb', 0)
sort_in = subprocess.Popen('sort', stdin=subprocess.PIPE, stdout=sort_out).stdin
subprocess.Popen(['awk', '-f', 'script.awk'], stdout=sort_in,
stdin=subprocess.PIPE).communicate(some_string)
</code></pre>
| 10 | 2012-02-06T17:20:01Z | [
"python",
"pipe",
"subprocess"
] |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| 27 | 2008-11-17T12:17:49Z | 16,709,666 | <p>To emulate a shell pipeline:</p>
<pre><code>from subprocess import check_call
check_call('echo "input data" | a | b > outfile.txt', shell=True)
</code></pre>
<p>without invoking the shell (see <a href="http://docs.python.org/2.7/library/subprocess.html#replacing-shell-pipeline" rel="nofollow">17.1.4.2. Replacing shell pipeline</a>):</p>
<pre><code>#!/usr/bin/env python
from subprocess import Popen, PIPE
a = Popen(["a"], stdin=PIPE, stdout=PIPE)
with a.stdin:
with a.stdout, open("outfile.txt", "wb") as outfile:
b = Popen(["b"], stdin=a.stdout, stdout=outfile)
a.stdin.write(b"input data")
statuses = [a.wait(), b.wait()] # both a.stdin/stdout are closed already
</code></pre>
<p><a href="http://plumbum.readthedocs.org/en/latest/" rel="nofollow"><code>plumbum</code></a> provides some syntax sugar:</p>
<pre><code>#!/usr/bin/env python
from plumbum.cmd import a, b # magic
(a << "input data" | b > "outfile.txt")()
</code></pre>
<p>The analog of:</p>
<pre><code>#!/bin/sh
echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>is:</p>
<pre><code>#!/usr/bin/env python
from plumbum.cmd import awk, sort
(awk["-f", "script.awk"] << "input data" | sort > "outfile.txt")()
</code></pre>
| 8 | 2013-05-23T09:01:24Z | [
"python",
"pipe",
"subprocess"
] |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| 27 | 2008-11-17T12:17:49Z | 27,301,712 | <p><strong>EDIT:</strong> <code>pipes</code> is available on Windows but, crucially, doesn't appear to actually <em>work</em> on Windows. See comments below.</p>
<p>The Python standard library now includes the <code>pipes</code> module for handling this:</p>
<p><a href="https://docs.python.org/2/library/pipes.html" rel="nofollow">https://docs.python.org/2/library/pipes.html</a>, <a href="https://docs.python.org/3.4/library/pipes.html" rel="nofollow">https://docs.python.org/3.4/library/pipes.html</a></p>
<p>I'm not sure how long this module has been around, but this approach appears to be vastly simpler than mucking about with <code>subprocess</code>.</p>
| 0 | 2014-12-04T18:51:58Z | [
"python",
"pipe",
"subprocess"
] |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| 27 | 2008-11-17T12:17:49Z | 28,429,789 | <p>Inspired by @Cristian's answer. I met just the same issue, but with a different command. So I'm putting my tested example, which I believe could be helpful:</p>
<pre><code>grep_proc = subprocess.Popen(["grep", "rabbitmq"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
subprocess.Popen(["ps", "aux"], stdout=grep_proc.stdin)
out, err = grep_proc.communicate()
</code></pre>
<p>This is tested. </p>
<h2>What has been done</h2>
<ul>
<li>Declared lazy <code>grep</code> execution with stdin from pipe. This command will be executed at the <code>ps</code> command execution when the pipe will be filled with the stdout of <code>ps</code>.</li>
<li>Called the primary command <code>ps</code> with stdout directed to the pipe used by the <code>grep</code> command.</li>
<li>Grep communicated to get stdout from the pipe.</li>
</ul>
<p>I like this way because it is natural pipe conception gently wrapped with <code>subprocess</code> interfaces.</p>
| 0 | 2015-02-10T10:50:04Z | [
"python",
"pipe",
"subprocess"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 295,676 | <p>A <a href="http://msdn.microsoft.com/en-us/library/wa80x488.aspx">partial type</a> (it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.</p>
<p>The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.</p>
<p>I've no idea whether Python/Perl have the same capabilities, I'm afraid.</p>
| 19 | 2008-11-17T14:26:55Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 295,704 | <p>Because python is a dynamic language you don't need a concept like partial class. In python is possible to extend object with functionality in runtime so it possible to break class declaration into different files</p>
| 1 | 2008-11-17T14:39:54Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 295,713 | <p>The concept of partial types have already been explained.</p>
<p>This can be done in python. As an example, do the following in a python shell.</p>
<pre><code>class A(object):
pass
obj = A()
def _some_method(self):
print self.__class__
A.identify = _some_method
obj.identify()
</code></pre>
| 2 | 2008-11-17T14:42:02Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 295,733 | <p>A partial class is simply a class that's contained in more than one file. Sometimes it's so that one part can be machine-generated, and another part user-edited.</p>
<p>I use them in C# when I'm making a class that's getting a bit too large. I'll put the accessors and constructors in one file, and all of the interesting methods in a different file.</p>
<p>In Perl, you'd simply have two (or more) files that each declare themselves to be in a package:</p>
<p>(main program)</p>
<pre><code> use MyClass;
</code></pre>
<p>(in MyClass.pm)</p>
<pre><code> use MyClassOtherStuff;
package MyClass;
# [..class code here...]
</code></pre>
<p>(in MyClassOtherStuff.pm)</p>
<pre><code> package MyClass;
# [...rest of code here...]
</code></pre>
| 6 | 2008-11-17T14:50:12Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 295,735 | <p>A Partial type is a type whose declaration is separated across multiple files. It makes sense to use them if you have a big class, which is hard to handle and read for a typical developer, to separate that class definition in separate files and to put in each file a logically separated section of code (for instance all public methods and proprieties in one file, private in other, db handling code in third and so on..)</p>
<p>No you don't have the same syntactical element in Python. </p>
| 0 | 2008-11-17T14:51:13Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 295,760 | <p>The c# partial class has been already explained here so I'll just cover the python part. You can use multiple inheritance to elegantly distribute the definition of a class.</p>
<pre><code>class A_part1:
def m1(self):
print "m1"
class A_part2:
def m2(self):
print "m2"
class A(A_part1, A_part2):
pass
a = A()
a.m1()
a.m2()
</code></pre>
| 9 | 2008-11-17T14:58:09Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 296,801 | <p>Python also has meta classes but that is more like a template class than a partial class. A good example of meta class usage is the Django ORM. All of your table models inherit from a base model class which also gets functionality included from a meta class. It is a pretty cool concept that enables an active record like pattern (is it full active record?).</p>
| 0 | 2008-11-17T20:32:03Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
What is a partial class? | 295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| 8 | 2008-11-17T14:24:32Z | 15,490,754 | <p>Partial class comes handy when you have <code>auto-generated code</code> by some tool. Refer question <a href="http://stackoverflow.com/questions/15447072/project-structure-for-schema-first-service-development-using-wcf">Project structure for Schema First Service Development using WCF</a> for an example.</p>
<p>You can put your logic in the partial class. Even if the auto-generated file is destroyed and recreated, your logic will persist in the partial class.</p>
| 0 | 2013-03-19T02:59:06Z | [
"c#",
"python",
"oop",
"programming-languages"
] |
Does python optimize modules when they are imported multiple times? | 296,036 | <p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p>
<p>For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p>
<pre><code>import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
</code></pre>
<p>or just</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
| 22 | 2008-11-17T16:21:43Z | 296,046 | <p>It is the same performancewise. There is no JIT compiler in Python yet.</p>
| -1 | 2008-11-17T16:24:20Z | [
"python",
"python-import"
] |
Does python optimize modules when they are imported multiple times? | 296,036 | <p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p>
<p>For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p>
<pre><code>import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
</code></pre>
<p>or just</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
| 22 | 2008-11-17T16:21:43Z | 296,062 | <p>Python modules could be considered as singletons... no matter how many times you import them they get initialized only once, so it's better to do:</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
<p>Relevant documentation on the import statement:</p>
<p><a href="https://docs.python.org/2/reference/simple_stmts.html#the-import-statement">https://docs.python.org/2/reference/simple_stmts.html#the-import-statement</a></p>
<blockquote>
<p>Once the name of the module is known (unless otherwise specified, the term âmoduleâ will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.</p>
</blockquote>
<p>The imported modules are cached in <a href="https://docs.python.org/2/library/sys.html#sys.modules">sys.modules</a>:</p>
<blockquote>
<p>This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.</p>
</blockquote>
| 34 | 2008-11-17T16:27:04Z | [
"python",
"python-import"
] |
Does python optimize modules when they are imported multiple times? | 296,036 | <p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p>
<p>For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p>
<pre><code>import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
</code></pre>
<p>or just</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
| 22 | 2008-11-17T16:21:43Z | 296,064 | <p>It makes no substantial difference. If the big module has already been loaded, the second import in your second example does nothing except adding 'ReallyBigLib' to the current namespace.</p>
| 7 | 2008-11-17T16:27:44Z | [
"python",
"python-import"
] |
Does python optimize modules when they are imported multiple times? | 296,036 | <p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p>
<p>For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p>
<pre><code>import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
</code></pre>
<p>or just</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
| 22 | 2008-11-17T16:21:43Z | 298,106 | <p>As others have pointed out, Python maintains an internal list of all modules that have been imported. When you import a module for the first time, the module (a script) is executed in its own namespace until the end, the internal list is updated, and execution of continues after the import statement. </p>
<p>Try this code:</p>
<pre><code> # module/file a.py
print "Hello from a.py!"
import b
# module/file b.py
print "Hello from b.py!"
import a
</code></pre>
<p>There is no loop: there is only a cache lookup.</p>
<pre><code>>>> import b
Hello from b.py!
Hello from a.py!
>>> import a
>>>
</code></pre>
<p>One of the beauties of Python is how everything devolves to executing a script in a namespace.</p>
| 12 | 2008-11-18T08:01:14Z | [
"python",
"python-import"
] |
Does python optimize modules when they are imported multiple times? | 296,036 | <p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p>
<p>For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p>
<pre><code>import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
</code></pre>
<p>or just</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
| 22 | 2008-11-17T16:21:43Z | 301,344 | <p>The internal registry of imported modules is the <code>sys.modules</code> dictionary, which maps module names to module objects. You can look there to see all the modules that are currently imported.</p>
<p>You can also pull some useful tricks (if you need to) by monkeying with <code>sys.modules</code> - for example adding your own objects as pseudo-modules which can be imported by other modules.</p>
| 3 | 2008-11-19T09:00:41Z | [
"python",
"python-import"
] |
Does python optimize modules when they are imported multiple times? | 296,036 | <p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p>
<p>For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p>
<pre><code>import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
</code></pre>
<p>or just</p>
<pre><code>import MyLib
import ReallyBigLib
</code></pre>
| 22 | 2008-11-17T16:21:43Z | 1,676,903 | <p>WARNING: Python does not guarantee that module will not be initialized twice.
I've stubled upon such issue. See discussion:
<a href="http://code.djangoproject.com/ticket/8193" rel="nofollow">http://code.djangoproject.com/ticket/8193</a></p>
| 3 | 2009-11-04T21:50:58Z | [
"python",
"python-import"
] |
How do I copy files with specific file extension to a folder in my python (version 2.5) script? | 296,173 | <p>I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use <code>os.walk</code> but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.</p>
| 14 | 2008-11-17T17:02:43Z | 296,184 | <pre><code>import glob, os, shutil
files = glob.iglob(os.path.join(source_dir, "*.ext"))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, dest_dir)
</code></pre>
<p>Read the <a href="http://www.python.org/doc/2.5.2/lib/module-shutil.html">documentation</a> of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()).</p>
| 23 | 2008-11-17T17:06:37Z | [
"python",
"file",
"copy"
] |
How do I copy files with specific file extension to a folder in my python (version 2.5) script? | 296,173 | <p>I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use <code>os.walk</code> but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.</p>
| 14 | 2008-11-17T17:02:43Z | 296,620 | <p>This will walk a tree with sub-directories. You can do an os.path.isfile check to make it a little safer.</p>
<pre><code>for root, dirs, files in os.walk(srcDir):
for file in files:
if file[-4:].lower() == '.jpg':
shutil.copy(os.path.join(root, file), os.path.join(dest, file))
</code></pre>
| 2 | 2008-11-17T19:39:10Z | [
"python",
"file",
"copy"
] |
How do I copy files with specific file extension to a folder in my python (version 2.5) script? | 296,173 | <p>I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use <code>os.walk</code> but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.</p>
| 14 | 2008-11-17T17:02:43Z | 296,621 | <p>If you're not recursing, you don't need walk().</p>
<p>Federico's answer with glob is fine, assuming you aren't going to have any directories called âsomething.extâ. Otherwise try:</p>
<pre><code>import os, shutil
for basename in os.listdir(srcdir):
if basename.endswith('.ext'):
pathname = os.path.join(srcdir, basename)
if os.path.isfile(pathname):
shutil.copy2(pathname, dstdir)
</code></pre>
| 6 | 2008-11-17T19:39:49Z | [
"python",
"file",
"copy"
] |
How do I copy files with specific file extension to a folder in my python (version 2.5) script? | 296,173 | <p>I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use <code>os.walk</code> but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.</p>
| 14 | 2008-11-17T17:02:43Z | 299,685 | <p>Here is a non-recursive version with <code>os.walk</code>:</p>
<pre><code>import fnmatch, os, shutil
def copyfiles(srcdir, dstdir, filepattern):
def failed(exc):
raise exc
for dirpath, dirs, files in os.walk(srcdir, topdown=True, onerror=failed):
for file in fnmatch.filter(files, filepattern):
shutil.copy2(os.path.join(dirpath, file), dstdir)
break # no recursion
</code></pre>
<p>Example:</p>
<pre><code>copyfiles(".", "test", "*.ext")
</code></pre>
| 3 | 2008-11-18T18:32:59Z | [
"python",
"file",
"copy"
] |
How do I copy files with specific file extension to a folder in my python (version 2.5) script? | 296,173 | <p>I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use <code>os.walk</code> but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.</p>
| 14 | 2008-11-17T17:02:43Z | 14,833,938 | <p>Copy files with extension "extension" from srcDir to dstDir...</p>
<pre><code>import os, shutil, sys
srcDir = sys.argv[1]
dstDir = sys.argv[2]
extension = sys.argv[3]
print "Source Dir: ", srcDir, "\n", "Destination Dir: ",dstDir, "\n", "Extension: ", extension
for root, dirs, files in os.walk(srcDir):
for file_ in files:
if file_.endswith(extension):
shutil.copy(os.path.join(root, file_), os.path.join(dstDir, file_))
</code></pre>
| 1 | 2013-02-12T13:41:45Z | [
"python",
"file",
"copy"
] |
Which is more efficient in Python: standard imports or contextual imports? | 296,270 | <p>I apologize in advance if this question seems remedial.</p>
<p>Which would be considered more efficient in Python:</p>
<p><strong>Standard import</strong></p>
<pre><code>import logging
try:
...some code...
exception Exception, e:
logging.error(e)
</code></pre>
<p>...or...</p>
<p><strong>Contextual import</strong></p>
<pre><code>try:
...some code...
exception Exception, e:
import logging
logging.error(e)
</code></pre>
| 4 | 2008-11-17T17:37:44Z | 296,292 | <p>They're essentially the same. The Python interpreter will only load a used module <em>once</em>, no matter how many times you import it. Changing the location of the import statement only has an effect on where the name is bound -- for example, if your <code>import</code> statement is inside a function, the name can only be used in that function.</p>
<p>Generally, though, imports are usually done as close to the "top" of a file as possible.</p>
| 2 | 2008-11-17T17:42:01Z | [
"python"
] |
Which is more efficient in Python: standard imports or contextual imports? | 296,270 | <p>I apologize in advance if this question seems remedial.</p>
<p>Which would be considered more efficient in Python:</p>
<p><strong>Standard import</strong></p>
<pre><code>import logging
try:
...some code...
exception Exception, e:
logging.error(e)
</code></pre>
<p>...or...</p>
<p><strong>Contextual import</strong></p>
<pre><code>try:
...some code...
exception Exception, e:
import logging
logging.error(e)
</code></pre>
| 4 | 2008-11-17T17:37:44Z | 296,303 | <p>Contextual imports are technically more efficient, but I think they can create other problems.</p>
<p>Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.</p>
| 5 | 2008-11-17T17:45:08Z | [
"python"
] |
Which is more efficient in Python: standard imports or contextual imports? | 296,270 | <p>I apologize in advance if this question seems remedial.</p>
<p>Which would be considered more efficient in Python:</p>
<p><strong>Standard import</strong></p>
<pre><code>import logging
try:
...some code...
exception Exception, e:
logging.error(e)
</code></pre>
<p>...or...</p>
<p><strong>Contextual import</strong></p>
<pre><code>try:
...some code...
exception Exception, e:
import logging
logging.error(e)
</code></pre>
| 4 | 2008-11-17T17:37:44Z | 296,380 | <p>It depends on how often you execute the contextual import.</p>
<p>An <code>import</code> statement requires checking to see if the module exists, which has a non-zero cost.</p>
<p>Lots of contextual imports will be a performance penalty for no real gain in simplicity. There's very little benefit, unless you are really sure that the import will be used rarely or never.</p>
<p>Contextual imports inside <code>if</code> statements make sense, especially when it's done at the top level, which means precisely once. </p>
<pre><code>if someConfig:
import this as bigDeal
else:
import that as bigDeal
</code></pre>
| 3 | 2008-11-17T18:16:05Z | [
"python"
] |
Which is more efficient in Python: standard imports or contextual imports? | 296,270 | <p>I apologize in advance if this question seems remedial.</p>
<p>Which would be considered more efficient in Python:</p>
<p><strong>Standard import</strong></p>
<pre><code>import logging
try:
...some code...
exception Exception, e:
logging.error(e)
</code></pre>
<p>...or...</p>
<p><strong>Contextual import</strong></p>
<pre><code>try:
...some code...
exception Exception, e:
import logging
logging.error(e)
</code></pre>
| 4 | 2008-11-17T17:37:44Z | 296,481 | <p>This is a microoptimization. Don't worry about it.</p>
| 3 | 2008-11-17T18:51:53Z | [
"python"
] |
Which is more efficient in Python: standard imports or contextual imports? | 296,270 | <p>I apologize in advance if this question seems remedial.</p>
<p>Which would be considered more efficient in Python:</p>
<p><strong>Standard import</strong></p>
<pre><code>import logging
try:
...some code...
exception Exception, e:
logging.error(e)
</code></pre>
<p>...or...</p>
<p><strong>Contextual import</strong></p>
<pre><code>try:
...some code...
exception Exception, e:
import logging
logging.error(e)
</code></pre>
| 4 | 2008-11-17T17:37:44Z | 297,182 | <p>The performance differences between these two approaches will be very small in practice. I have never seen a case where this has made a difference that was noticeable. </p>
<p>It is worth remembering that the python interpreter will only ever do the work of parsing the module once when it is 1st imported.</p>
<p>In general you will end up with more maintainable code it you just import all the modules you need at the top of the file.</p>
| 1 | 2008-11-17T22:22:26Z | [
"python"
] |
How do I remove a specific number of files using python (version 2.5)? | 296,490 | <p>I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. </p>
| 0 | 2008-11-17T18:56:12Z | 296,495 | <p>Just call <code>os.remove("path/to/file")</code>. For example, to remove the file <code>.emacs</code>, call</p>
<pre><code>os.remove(".emacs")
</code></pre>
<p>The path should be a <code>str</code> that's the pathname of the file. It may be relative or absolute.</p>
| -1 | 2008-11-17T18:58:58Z | [
"python",
"file"
] |
How do I remove a specific number of files using python (version 2.5)? | 296,490 | <p>I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. </p>
| 0 | 2008-11-17T18:56:12Z | 296,498 | <p>It is perfectly acceptable to have a 'cleanup()' function that you call at the end of your script, which will call 'os.remove()' on your files.</p>
| 0 | 2008-11-17T18:59:19Z | [
"python",
"file"
] |
How do I remove a specific number of files using python (version 2.5)? | 296,490 | <p>I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. </p>
| 0 | 2008-11-17T18:56:12Z | 296,528 | <p>It sounds like what you really want is a temp file:
<a href="http://docs.python.org/library/tempfile.html" rel="nofollow">http://docs.python.org/library/tempfile.html</a></p>
| 4 | 2008-11-17T19:08:30Z | [
"python",
"file"
] |
How do I zip the contents of a folder using python (version 2.5)? | 296,499 | <p>Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance.</p>
| 27 | 2008-11-17T19:00:07Z | 296,565 | <p>Here is a recursive version</p>
<pre><code>def zipfolder(path, relname, archive):
paths = os.listdir(path)
for p in paths:
p1 = os.path.join(path, p)
p2 = os.path.join(relname, p)
if os.path.isdir(p1):
zipfolder(p1, p2, archive)
else:
archive.write(p1, p2)
def create_zip(path, relname, archname):
archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
if os.path.isdir(path):
zipfolder(path, relname, archive)
else:
archive.write(path, relname)
archive.close()
</code></pre>
| 5 | 2008-11-17T19:19:01Z | [
"python",
"file",
"zip",
"python-2.5"
] |
How do I zip the contents of a folder using python (version 2.5)? | 296,499 | <p>Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance.</p>
| 27 | 2008-11-17T19:00:07Z | 296,722 | <p>Adapted version of <a href="http://mail.python.org/pipermail/python-list/2006-May/384142.html">the script</a> is:</p>
<pre><code>#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os
def zipdir(basedir, archivename):
assert os.path.isdir(basedir)
with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(basedir):
#NOTE: ignore empty directories
for fn in files:
absfn = os.path.join(root, fn)
zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
z.write(absfn, zfn)
if __name__ == '__main__':
import sys
basedir = sys.argv[1]
archivename = sys.argv[2]
zipdir(basedir, archivename)
</code></pre>
<p>Example:</p>
<pre><code>C:\zipdir> python -mzipdir c:\tmp\test test.zip
</code></pre>
<p>It creates <code>'C:\zipdir\test.zip'</code> archive with the contents of the <code>'c:\tmp\test'</code> directory.</p>
| 29 | 2008-11-17T20:07:58Z | [
"python",
"file",
"zip",
"python-2.5"
] |
How do I zip the contents of a folder using python (version 2.5)? | 296,499 | <p>Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance.</p>
| 27 | 2008-11-17T19:00:07Z | 11,880,001 | <p>On python 2.7 you might use: <a href="http://docs.python.org/library/shutil#shutil.make_archive">shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])</a>. </p>
<p><strong>base_name</strong> archive name minus extension</p>
<p><strong>format</strong> format of the archive </p>
<p><strong>root_dir</strong> directory to compress.</p>
<p>For example</p>
<pre><code> shutil.make_archive(target_file, format="bztar", root_dir=compress_me)
</code></pre>
| 37 | 2012-08-09T09:04:52Z | [
"python",
"file",
"zip",
"python-2.5"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 296,663 | <p>You may be interested in this question: <a href="http://stackoverflow.com/questions/69316/biggest-differences-of-thrift-vs-protocol-buffers">"Biggest differences of Thrift vs Protocol Buffers?"</a></p>
| 7 | 2008-11-17T19:52:38Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 296,677 | <p>One of the things near the top of my "to-do" list for PBs is to port Google's internal Protocol Buffer performance benchmark - it's mostly a case of taking confidential message formats and turning them into entirely bland ones, and then doing the same for the data.</p>
<p>When that's been done, I'd imagine you could build the same messages in Thrift and then compare the performance.</p>
<p>In other words, I don't have the data for you yet - but hopefully in the next couple of weeks...</p>
| 4 | 2008-11-17T19:56:14Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 297,193 | <p>If the raw net performance is the target, then nothing beats IIOP (see RMI/IIOP).
Smallest possible footprint -- only binary data, no markup at all. Serialization/deserialization is very fast too.</p>
<p>Since it's IIOP (that is CORBA), almost all languages have bindings.</p>
<p>But I presume the performance is not the <strong>only</strong> requirement, right?</p>
| 4 | 2008-11-17T22:25:23Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 297,448 | <p>I'm in the process of writing some code in an <a href="http://code.google.com/p/thrift-protobuf-compare/">open source project named thrift-protobuf-compare</a> comparing between protobuf and thrift. For now it covers few serialization aspects, but I intend to cover more. The results (for <a href="http://eishay.blogspot.com/search/label/Thrift">Thrift</a> and <a href="http://eishay.blogspot.com/search/label/protobuf">Protobuf</a>) are discussed in my blog, I'll add more when I'll get to it.
You may look at the code to compare API, description language and generated code. I'll be happy to have contributions to achieve a more rounded comparison. </p>
| 14 | 2008-11-18T00:13:01Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 628,329 | <p>I did test performance of PB with number of other data formats (xml, json, default object serialization, hessian, one proprietary one) and libraries (jaxb, fast infoset, hand-written) for data binding task (both reading and writing), but thrift's format(s) was not included. Performance for formats with multiple converters (like xml) had very high variance, from very slow to pretty-darn-fast. Correlation between claims of authors and perceived performance was rather weak. Especially so for packages that made wildest claims.</p>
<p>For what it is worth, I found PB performance to be bit over hyped (usually not by its authors, but others who only know who wrote it). With default settings it did not beat fastest textual xml alternative. With optimized mode (why is this not default?), it was bit faster, comparable with the fastest JSON package. Hessian was rather fast, textual json also. Properietary binary format (no name here, it was company internal) was the slowest. Java object serialization was fast for larger messages, less so for small objects (i.e. high fixed per-operation noverhead).
With PB message size was compact, but given all trade-offs you have to do (data is not self-descriptive: if you lose the schema, you lose data; there are indexes of course, and value types, but from what you have reverse-engineer back to field names if you want), I personally would only choose it for specific use cases -- size-sensitive, closely coupled system where interface/format never (or very very rarely) changes.</p>
<p>My opinion in this is that (a) implementation often matters more than specification (of data format), (b) end-to-end, differences between best-of-breed (for different formats) are usually not big enough to dictate the choice.
That is, you may be better off choosing format+API/lib/framework you like using most (or has best tool support), find best implementation, and see if that works fast enough.
If (and only if!) not, consider next best alternative.</p>
<p>ps. Not sure what EJB3 here would be. Maybe just plain of Java serialization?</p>
| 6 | 2009-03-09T22:46:07Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 675,527 | <p>Latest comparison available here at the <a href="https://github.com/eishay/jvm-serializers/wiki/">thrift-protobuf-compare</a> project wiki. It includes many other serialization libraries.</p>
| 49 | 2009-03-23T22:48:30Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p>
<p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p>
<p>Primarily languages will be Java, C/C++, Python, and PHP.</p>
<p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
| 61 | 2008-11-17T19:48:44Z | 5,557,802 | <p>To back up Vladimir's point about IIOP, here's an interesting performance test, that should give some additional info over the google benchmarks, since it compares Thrift and CORBA. (Performance_TIDorb_vs_Thrift_morfeo.pdf // link no longer valid)
To quote from the study:</p>
<blockquote>
<ul>
<li>Thrift is very efficient with small
data (basic types as operation
arguments)</li>
<li>Thrifts transports are not so efficient as CORBA with medium and
large data (struct and >complex
types > 1 kilobytes).</li>
</ul>
</blockquote>
<p>Another odd limitation, not having to do with performance, is that Thrift is limited to returning only several values as a struct - although this, like performance, can surely be improved perhaps. </p>
<p>It is interesting that the Thrift IDL closely matches the CORBA IDL, nice. I haven't used Thrift, it looks interesting especially for smaller messages, and one of the design goals was for a less cumbersome install, so these are other advantages of Thrift. That said, CORBA has a bad rap, there are many excellent implementations out there like <a href="http://omniorb.sourceforge.net/" rel="nofollow">omniORB</a> for example, which has bindings for Python, that are easy to install and use.</p>
<p>Edited: The Thrift and CORBA link is no longer valid, but I did find another useful paper from CERN. They evaluated replacements for their CORBA system, and, while they <a href="http://zeromq.wdfiles.com/local--files/intro%3aread-the-manual/Middleware%20Trends%20and%20Market%20Leaders%202011.pdf" rel="nofollow">evaluated Thrift</a>, they eventually went with ZeroMQ. While Thrift performed the fastest in their performance tests, at 9000 msg/sec vs. 8000 (ZeroMQ) and 7000+ RDA (CORBA-based), they chose not to test Thrift further because of other issues notably:</p>
<blockquote>
<p>It is still an immature product with a buggy implementation</p>
</blockquote>
| 3 | 2011-04-05T20:04:16Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] |
how do i use python libraries in C++? | 297,112 | <p>I want to use the <a href="http://nltk.sourceforge.net/index.php/Main_Page">nltk</a> libraries in c++. </p>
<p>Is there a glue language/mechanism I can use to do this? </p>
<p>Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.</p>
<p>Thanks</p>
| 8 | 2008-11-17T22:03:24Z | 297,137 | <p>I haven't tried directly calling Python functions from C++, but here are some alternative ideas...</p>
<p>Generally, it's easier to call C++ code from a high-level language like Python than the other way around. If you're interested in this approach, then you could create a C++ codebase and access it from Python. You could either directly use the external API provided by python [it should be described somewhere in the Python docs] or use a tool like SWIG to automate the C++-to-Python wrapping process.</p>
<p>Depending on how you want to use the library, you could alternatively create Python scripts which you call from C++ with the <a href="http://www.opengroup.org/onlinepubs/000095399/functions/exec.html" rel="nofollow">exec*</a> functions.</p>
| 1 | 2008-11-17T22:10:08Z | [
"c++",
"python",
"nltk"
] |
how do i use python libraries in C++? | 297,112 | <p>I want to use the <a href="http://nltk.sourceforge.net/index.php/Main_Page">nltk</a> libraries in c++. </p>
<p>Is there a glue language/mechanism I can use to do this? </p>
<p>Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.</p>
<p>Thanks</p>
| 8 | 2008-11-17T22:03:24Z | 297,155 | <p>Although calling c++ libs from python is more normal - you can call a python module from c++ by bascially calling the python intepreter and have it execute the python source.
This is called <a href="https://docs.python.org/2.7/extending/embedding.html" rel="nofollow">embedding</a> </p>
<p>Alternatively the <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/index.html" rel="nofollow">boost.python</a> library makes it very easy.</p>
| 14 | 2008-11-17T22:13:29Z | [
"c++",
"python",
"nltk"
] |
how do i use python libraries in C++? | 297,112 | <p>I want to use the <a href="http://nltk.sourceforge.net/index.php/Main_Page">nltk</a> libraries in c++. </p>
<p>Is there a glue language/mechanism I can use to do this? </p>
<p>Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.</p>
<p>Thanks</p>
| 8 | 2008-11-17T22:03:24Z | 297,175 | <p>You can also try the <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/index.html">Boost.Python</a> library; which has <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/callbacks.html">this capability</a>. This library is mainly used to expose C++ to Python, but can be used the other way around.</p>
| 12 | 2008-11-17T22:18:46Z | [
"c++",
"python",
"nltk"
] |
how do i use python libraries in C++? | 297,112 | <p>I want to use the <a href="http://nltk.sourceforge.net/index.php/Main_Page">nltk</a> libraries in c++. </p>
<p>Is there a glue language/mechanism I can use to do this? </p>
<p>Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.</p>
<p>Thanks</p>
| 8 | 2008-11-17T22:03:24Z | 297,520 | <p><a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a> can be cleanly used for this purpose. There's an <a href="http://www.pysoy.org/changeset/11/branches/pyrex-soy/Demos/embed/" rel="nofollow">example</a> in the source-code release.</p>
| 1 | 2008-11-18T00:58:43Z | [
"c++",
"python",
"nltk"
] |
Why doesn't xpath work when processing an XHTML document with lxml (in python)? | 297,239 | <p>I am testing against the following test document:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</head>
<body>
<img class="foo" src="bar.png"/>
</body>
</html>
</code></pre>
<p>If I parse the document using lxml.html, I can get the IMG with an xpath just fine:</p>
<pre><code>>>> root = lxml.html.fromstring(doc)
>>> root.xpath("//img")
[<Element img at 1879e30>]
</code></pre>
<p>However, if I parse the document as XML and try to get the IMG tag, I get an empty result:</p>
<pre><code>>>> tree = etree.parse(StringIO(doc))
>>> tree.getroot().xpath("//img")
[]
</code></pre>
<p>I can navigate to the element directly:</p>
<pre><code>>>> tree.getroot().getchildren()[1].getchildren()[0]
<Element {http://www.w3.org/1999/xhtml}img at f56810>
</code></pre>
<p>But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do:</p>
<pre><code>>>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0])
'/*/*[2]/*'
>>> tree.getroot().xpath('/*/*[2]/*')
[<Element {http://www.w3.org/1999/xhtml}img at fa1750>]
</code></pre>
<p>But that xpath is, again, obviously not useful for parsing arbitrary documents.</p>
<p>Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces.</p>
<p>So, what am I missing?</p>
| 20 | 2008-11-17T22:42:58Z | 297,243 | <p>The problem is the namespaces. When parsed as XML, the img tag is in the <a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a> namespace since that is the default namespace for the element. You are asking for the img tag in no namespace.</p>
<p>Try this:</p>
<pre><code>>>> tree.getroot().xpath(
... "//xhtml:img",
... namespaces={'xhtml':'http://www.w3.org/1999/xhtml'}
... )
[<Element {http://www.w3.org/1999/xhtml}img at 11a29e0>]
</code></pre>
| 26 | 2008-11-17T22:45:15Z | [
"python",
"xml",
"xhtml",
"xpath",
"lxml"
] |
Why doesn't xpath work when processing an XHTML document with lxml (in python)? | 297,239 | <p>I am testing against the following test document:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</head>
<body>
<img class="foo" src="bar.png"/>
</body>
</html>
</code></pre>
<p>If I parse the document using lxml.html, I can get the IMG with an xpath just fine:</p>
<pre><code>>>> root = lxml.html.fromstring(doc)
>>> root.xpath("//img")
[<Element img at 1879e30>]
</code></pre>
<p>However, if I parse the document as XML and try to get the IMG tag, I get an empty result:</p>
<pre><code>>>> tree = etree.parse(StringIO(doc))
>>> tree.getroot().xpath("//img")
[]
</code></pre>
<p>I can navigate to the element directly:</p>
<pre><code>>>> tree.getroot().getchildren()[1].getchildren()[0]
<Element {http://www.w3.org/1999/xhtml}img at f56810>
</code></pre>
<p>But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do:</p>
<pre><code>>>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0])
'/*/*[2]/*'
>>> tree.getroot().xpath('/*/*[2]/*')
[<Element {http://www.w3.org/1999/xhtml}img at fa1750>]
</code></pre>
<p>But that xpath is, again, obviously not useful for parsing arbitrary documents.</p>
<p>Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces.</p>
<p>So, what am I missing?</p>
| 20 | 2008-11-17T22:42:58Z | 297,310 | <p><a href="http://www.w3.org/TR/xpath#node-tests">XPath considers all unprefixed names to be in "no namespace"</a>.</p>
<p>In particular the spec says:</p>
<p>"A QName in the node test is expanded into an expanded-name using the namespace declarations from the expression context. This is the same way expansion is done for element type names in start and end-tags except that the default namespace declared with xmlns is not used: if the QName does not have a prefix, then the namespace URI is null (this is the same way attribute names are expanded). "</p>
<p>See those two detailed explanations of the problem and its solution: <a href="http://www.topxml.com/people/bosley/defaultns.asp"><strong>here</strong></a> and <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1455253&SiteID=1"><strong>here</strong></a>. The solution is to associate a prefix (with the API that's being used) and to use it to prefix any unprefixed name in the XPath expression.</p>
<p>Hope this helped.</p>
<p>Cheers,</p>
<p>Dimitre Novatchev</p>
| 7 | 2008-11-17T23:13:07Z | [
"python",
"xml",
"xhtml",
"xpath",
"lxml"
] |
Why doesn't xpath work when processing an XHTML document with lxml (in python)? | 297,239 | <p>I am testing against the following test document:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</head>
<body>
<img class="foo" src="bar.png"/>
</body>
</html>
</code></pre>
<p>If I parse the document using lxml.html, I can get the IMG with an xpath just fine:</p>
<pre><code>>>> root = lxml.html.fromstring(doc)
>>> root.xpath("//img")
[<Element img at 1879e30>]
</code></pre>
<p>However, if I parse the document as XML and try to get the IMG tag, I get an empty result:</p>
<pre><code>>>> tree = etree.parse(StringIO(doc))
>>> tree.getroot().xpath("//img")
[]
</code></pre>
<p>I can navigate to the element directly:</p>
<pre><code>>>> tree.getroot().getchildren()[1].getchildren()[0]
<Element {http://www.w3.org/1999/xhtml}img at f56810>
</code></pre>
<p>But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do:</p>
<pre><code>>>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0])
'/*/*[2]/*'
>>> tree.getroot().xpath('/*/*[2]/*')
[<Element {http://www.w3.org/1999/xhtml}img at fa1750>]
</code></pre>
<p>But that xpath is, again, obviously not useful for parsing arbitrary documents.</p>
<p>Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces.</p>
<p>So, what am I missing?</p>
| 20 | 2008-11-17T22:42:58Z | 5,978,436 | <p>If you are going to use tags from a single namespace only, as I see it the case above, you are much better off using lxml.objectify.</p>
<p>In your case it would be like</p>
<pre><code>from lxml import objectify
root = objectify.parse(url) #also available: fromstring
</code></pre>
<p>You can access the nodes as</p>
<pre><code>root.html
body = root.html.body
for img in body.img: #Assuming all images are within the body tag
</code></pre>
<p>While it might not be of great help in html, it can be highly useful in well structured xml.</p>
<p>For more info, check out <a href="http://lxml.de/objectify.html" rel="nofollow">http://lxml.de/objectify.html</a></p>
| 2 | 2011-05-12T13:06:52Z | [
"python",
"xml",
"xhtml",
"xpath",
"lxml"
] |
Integrating command-line generated python .coverage files with PyDev | 297,294 | <p>My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). </p>
<p>I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to convert my whole build environment to Eclipse (and thus generate the coverage data directly from the IDE, as it's designed to do)</p>
<p>PyDev seems to be using the same coverage tool (or something very similar to it) to generate its coverage information, so I'm guessing there should be some way of integrating my external coverage files into Eclipse/PyDev.</p>
<p>Any idea on how to do this?</p>
| 2 | 2008-11-17T23:04:50Z | 297,764 | <p>I don't know anything about PyDev's integration of coverage.py (or if it even uses coverage.py), but the .coverage files are pretty simple. They are marhsal'ed dictionaries.</p>
<p>I haven't tested this code, but you can try this to combine two .coverage files into one:</p>
<pre><code>import marshal
c1_dict = marshal.load(open(file_name_1, 'rb'))
c2_dict = marshal.load(open(file_name_2, 'rb'))
c1_dict.update(c2_dict)
marshal.dump(c1_dict, open(file_name_out, 'wb'))
</code></pre>
| 3 | 2008-11-18T03:15:32Z | [
"python",
"eclipse",
"code-coverage",
"pydev",
"python-coverage"
] |
Integrating command-line generated python .coverage files with PyDev | 297,294 | <p>My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). </p>
<p>I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to convert my whole build environment to Eclipse (and thus generate the coverage data directly from the IDE, as it's designed to do)</p>
<p>PyDev seems to be using the same coverage tool (or something very similar to it) to generate its coverage information, so I'm guessing there should be some way of integrating my external coverage files into Eclipse/PyDev.</p>
<p>Any idea on how to do this?</p>
| 2 | 2008-11-17T23:04:50Z | 489,721 | <p>I needed exactly something like this some time ago, when PyDev still used an older version of <code>coverage.py</code> than the one accessible from the script creator's page.</p>
<p>What I did was detecting where PyDev was saving his <code>.coverage</code> file. For me it was:</p>
<pre><code> C:\Users\Admin\workspace\.metadata\.plugins\org.python.pydev.debug\.coverage
</code></pre>
<p>Then I manually ran a new version of <code>coverage.py</code> from a separate script and told it to save its .coverage file in the place where PyDev saves its. I cannot remember if there is a command-line argument to <code>coverage.py</code> or if I simply copied the <code>.coverage</code> file with a script, but after that, if you simply open the <strong>Code Coverage Results View</strong> and click <strong>Refresh coverage information!</strong>, PyDev will nicely process the data as if it generated the file itself.</p>
| 3 | 2009-01-28T22:35:08Z | [
"python",
"eclipse",
"code-coverage",
"pydev",
"python-coverage"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 297,376 | <p>gzip.GzipFile writes the data in gzipped chunks , which you can set the size of your chunks according to the numbers of lines read from the files.</p>
<p>an example: </p>
<pre><code>file = gzip.GzipFile('blah.gz', 'wb')
sourcefile = open('source', 'rb')
chunks = []
for line in sourcefile:
chunks.append(line)
if len(chunks) >= X:
file.write("".join(chunks))
file.flush()
chunks = []
</code></pre>
| 3 | 2008-11-17T23:41:27Z | [
"python",
"zip"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 297,423 | <p>The gzip library will take a file-like object for compression.</p>
<pre><code>class GzipFile([filename [,mode [,compresslevel [,fileobj]]]])
</code></pre>
<p>You still need to provide a nominal filename for inclusion in the zip file, but you can pass your data-source to the fileobj.</p>
<p><em>(This answer differs from that of Damnsweet, in that the focus should be on the data-source being incrementally read, not the compressed file being incrementally written.)</em></p>
<p><em>And I see now the original questioner won't accept Gzip :-(</em></p>
| 0 | 2008-11-18T00:02:46Z | [
"python",
"zip"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 297,444 | <p>Some (many? most?) compression algorithms are based on looking at redundancies across the <em>entire</em> file.</p>
<p>Some compression libraries will choose between several compression algorithms based on which works best on the file.</p>
<p>I believe the ZipFile module does this, so it wants to see the entire file, not just pieces at a time.</p>
<p>Hence, it won't work with generators or files to big to load in memory. That would explain the limitation of the Zipfile library.</p>
| 2 | 2008-11-18T00:11:34Z | [
"python",
"zip"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 297,711 | <p>The essential compression is done by zlib.compressobj. ZipFile (under Python 2.5 on MacOSX appears to be compiled). The Python 2.3 version is as follows.</p>
<p>You can see that it builds the compressed file in 8k chunks. Taking out the source file information is complex because a lot of source file attributes (like uncompressed size) is recorded in the zip file header. </p>
<pre><code>def write(self, filename, arcname=None, compress_type=None):
"""Put the bytes from filename into the archive under the name
arcname."""
st = os.stat(filename)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
# Create ZipInfo instance to store file information
if arcname is None:
zinfo = ZipInfo(filename, date_time)
else:
zinfo = ZipInfo(arcname, date_time)
zinfo.external_attr = st[0] << 16L # Unix attributes
if compress_type is None:
zinfo.compress_type = self.compression
else:
zinfo.compress_type = compress_type
self._writecheck(zinfo)
fp = open(filename, "rb")
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell() # Start of header bytes
# Must overwrite CRC and sizes with correct data later
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
zinfo.file_size = file_size = 0
self.fp.write(zinfo.FileHeader())
zinfo.file_offset = self.fp.tell() # Start of file bytes
if zinfo.compress_type == ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
zlib.DEFLATED, -15)
else:
cmpr = None
while 1:
buf = fp.read(1024 * 8)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
fp.close()
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
# Seek backwards and write CRC and file sizes
position = self.fp.tell() # Preserve current position in file
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
</code></pre>
| 3 | 2008-11-18T02:45:19Z | [
"python",
"zip"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 299,830 | <p>The only solution is to rewrite the method it uses for zipping files to read from a buffer. It would be trivial to add this to the standard libraries; I'm kind of amazed it hasn't been done yet. I gather there's a lot of agreement the entire interface needs to be overhauled, and that seems to be blocking any incremental improvements.</p>
<pre><code>import zipfile, zlib, binascii, struct
class BufferedZipFile(zipfile.ZipFile):
def writebuffered(self, zipinfo, buffer):
zinfo = zipinfo
zinfo.file_size = file_size = 0
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell()
self._writecheck(zinfo)
self._didModify = True
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
self.fp.write(zinfo.FileHeader())
if zinfo.compress_type == zipfile.ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
else:
cmpr = None
while True:
buf = buffer.read(1024 * 8)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC) & 0xffffffff
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
position = self.fp.tell()
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
</code></pre>
| 9 | 2008-11-18T19:23:41Z | [
"python",
"zip"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 2,734,156 | <p>I took <a href="http://stackoverflow.com/questions/297345/create-a-zip-file-from-a-generator-in-python/299830#299830">Chris B.'s answer</a> and created a complete solution. Here it is in case anyone else is interested:</p>
<pre><code>import os
import threading
from zipfile import *
import zlib, binascii, struct
class ZipEntryWriter(threading.Thread):
def __init__(self, zf, zinfo, fileobj):
self.zf = zf
self.zinfo = zinfo
self.fileobj = fileobj
zinfo.file_size = 0
zinfo.flag_bits = 0x00
zinfo.header_offset = zf.fp.tell()
zf._writecheck(zinfo)
zf._didModify = True
zinfo.CRC = 0
zinfo.compress_size = compress_size = 0
zf.fp.write(zinfo.FileHeader())
super(ZipEntryWriter, self).__init__()
def run(self):
zinfo = self.zinfo
zf = self.zf
file_size = 0
CRC = 0
if zinfo.compress_type == ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
else:
cmpr = None
while True:
buf = self.fileobj.read(1024 * 8)
if not buf:
self.fileobj.close()
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
zf.fp.write(buf)
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
zf.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
position = zf.fp.tell()
zf.fp.seek(zinfo.header_offset + 14, 0)
zf.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size))
zf.fp.seek(position, 0)
zf.filelist.append(zinfo)
zf.NameToInfo[zinfo.filename] = zinfo
class EnhZipFile(ZipFile, object):
def _current_writer(self):
return hasattr(self, 'cur_writer') and self.cur_writer or None
def assert_no_current_writer(self):
cur_writer = self._current_writer()
if cur_writer and cur_writer.isAlive():
raise ValueError('An entry is already started for name: %s' % cur_write.zinfo.filename)
def write(self, filename, arcname=None, compress_type=None):
self.assert_no_current_writer()
super(EnhZipFile, self).write(filename, arcname, compress_type)
def writestr(self, zinfo_or_arcname, bytes):
self.assert_no_current_writer()
super(EnhZipFile, self).writestr(zinfo_or_arcname, bytes)
def close(self):
self.finish_entry()
super(EnhZipFile, self).close()
def start_entry(self, zipinfo):
"""
Start writing a new entry with the specified ZipInfo and return a
file like object. Any data written to the file like object is
read by a background thread and written directly to the zip file.
Make sure to close the returned file object, before closing the
zipfile, or the close() would end up hanging indefinitely.
Only one entry can be open at any time. If multiple entries need to
be written, make sure to call finish_entry() before calling any of
these methods:
- start_entry
- write
- writestr
It is not necessary to explicitly call finish_entry() before closing
zipfile.
Example:
zf = EnhZipFile('tmp.zip', 'w')
w = zf.start_entry(ZipInfo('t.txt'))
w.write("some text")
w.close()
zf.close()
"""
self.assert_no_current_writer()
r, w = os.pipe()
self.cur_writer = ZipEntryWriter(self, zipinfo, os.fdopen(r, 'r'))
self.cur_writer.start()
return os.fdopen(w, 'w')
def finish_entry(self, timeout=None):
"""
Ensure that the ZipEntry that is currently being written is finished.
Joins on any background thread to exit. It is safe to call this method
multiple times.
"""
cur_writer = self._current_writer()
if not cur_writer or not cur_writer.isAlive():
return
cur_writer.join(timeout)
if __name__ == "__main__":
zf = EnhZipFile('c:/tmp/t.zip', 'w')
import time
w = zf.start_entry(ZipInfo('t.txt', time.localtime()[:6]))
w.write("Line1\n")
w.write("Line2\n")
w.close()
zf.finish_entry()
w = zf.start_entry(ZipInfo('p.txt', time.localtime()[:6]))
w.write("Some text\n")
w.close()
zf.close()
</code></pre>
| 7 | 2010-04-29T01:06:09Z | [
"python",
"zip"
] |
Create a zip file from a generator in Python? | 297,345 | <p>I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.</p>
<p>Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?</p>
<p>By zip file, I mean zip file. As supported in the Python zipfile package.</p>
| 15 | 2008-11-17T23:27:03Z | 18,664,094 | <p>Now with python 2.7 you can add data to the zipfile insted of the file :</p>
<p><a href="http://docs.python.org/2/library/zipfile#zipfile.ZipFile.writestr" rel="nofollow">http://docs.python.org/2/library/zipfile#zipfile.ZipFile.writestr</a></p>
| 0 | 2013-09-06T18:16:40Z | [
"python",
"zip"
] |
Dynamically update ModelForm's Meta class | 297,383 | <p>I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from <code>as_p()</code>, <code>as_ul()</code>, etc does not reflect the updated Meta exclude.</p>
<p>I assume then that the html is generated when the ModelForm is created not when the <code>as_*()</code> is called. Is there a way to force the update of the HTML? </p>
<p>Is this even the best way to do it? I just assumed this <em>should</em> work.</p>
<p>Thoughts?</p>
<pre><code>from django.forms import ModelForm
from testprogram.online_bookings.models import Passenger
class PassengerInfoForm(ModelForm):
def set_form_excludes(self, exclude_list):
self.Meta.exclude = excludes_list
class Meta:
model = Passenger
exclude = []
</code></pre>
| 17 | 2008-11-17T23:44:27Z | 297,478 | <p>The Meta class is used to dynamically construct the form definition - so by the time you've created the ModelForm instance, the fields not in the exclude have already been added as the new object's attributes.</p>
<p>The normal way to do it would be to just have multiple class definitions for each possible exclude list. But if you want the form itself to be dynamic, you'll have to create a class definition on the fly. Something like:</p>
<pre><code>def get_form(exclude_list):
class MyForm(ModelForm):
class Meta:
model = Passenger
exclude = exclude_list
return MyForm
form_class = get_form(('field1', 'field2'))
form = form_class()
</code></pre>
<p><strong>UPDATE</strong>: I just revisited this post and thought I'd post a little more idiomatic way to handle a dynamic class:</p>
<pre><code>def PassengerForm(exclude_list, *args, **kwargs):
class MyPassengerForm(ModelForm):
class Meta:
model = Passenger
exclude = exclude_list
def __init__(self):
super(MyPassengerForm, self).__init__(*args, **kwargs)
return MyPassengerForm()
form = PassengerForm(('field1', 'field2'))
</code></pre>
| 46 | 2008-11-18T00:38:08Z | [
"python",
"django",
"django-forms",
"metaprogramming",
"modelform"
] |
Dynamically update ModelForm's Meta class | 297,383 | <p>I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from <code>as_p()</code>, <code>as_ul()</code>, etc does not reflect the updated Meta exclude.</p>
<p>I assume then that the html is generated when the ModelForm is created not when the <code>as_*()</code> is called. Is there a way to force the update of the HTML? </p>
<p>Is this even the best way to do it? I just assumed this <em>should</em> work.</p>
<p>Thoughts?</p>
<pre><code>from django.forms import ModelForm
from testprogram.online_bookings.models import Passenger
class PassengerInfoForm(ModelForm):
def set_form_excludes(self, exclude_list):
self.Meta.exclude = excludes_list
class Meta:
model = Passenger
exclude = []
</code></pre>
| 17 | 2008-11-17T23:44:27Z | 703,888 | <p>Another way:</p>
<pre><code>class PassengerInfoForm(ModelForm):
def __init__(self, *args, **kwargs):
exclude_list=kwargs.pop('exclude_list', '')
super(PassengerInfoForm, self).__init__(*args, **kwargs)
for field in exclude_list:
del self.fields[field]
class Meta:
model = Passenger
form = PassengerInfoForm(exclude_list=['field1', 'field2'])
</code></pre>
| 12 | 2009-04-01T02:54:06Z | [
"python",
"django",
"django-forms",
"metaprogramming",
"modelform"
] |
Dynamically update ModelForm's Meta class | 297,383 | <p>I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from <code>as_p()</code>, <code>as_ul()</code>, etc does not reflect the updated Meta exclude.</p>
<p>I assume then that the html is generated when the ModelForm is created not when the <code>as_*()</code> is called. Is there a way to force the update of the HTML? </p>
<p>Is this even the best way to do it? I just assumed this <em>should</em> work.</p>
<p>Thoughts?</p>
<pre><code>from django.forms import ModelForm
from testprogram.online_bookings.models import Passenger
class PassengerInfoForm(ModelForm):
def set_form_excludes(self, exclude_list):
self.Meta.exclude = excludes_list
class Meta:
model = Passenger
exclude = []
</code></pre>
| 17 | 2008-11-17T23:44:27Z | 3,840,924 | <p>Similar approach, somewhat different goal (generic ModelForm for arbitrary models):</p>
<pre><code>from django.contrib.admin.widgets import AdminDateWidget
from django.forms import ModelForm
from django.db import models
def ModelFormFactory(some_model, *args, **kwargs):
"""
Create a ModelForm for some_model
"""
widdict = {}
# set some widgets for special fields
for field in some_model._meta.local_fields:
if type(field) is models.DateField:
widdict[field.name] = AdminDateWidget()
class MyModelForm(ModelForm): # I use my personal BaseModelForm as parent
class Meta:
model = some_model
widgets = widdict
return MyModelForm(*args, **kwargs)
</code></pre>
| 3 | 2010-10-01T16:02:02Z | [
"python",
"django",
"django-forms",
"metaprogramming",
"modelform"
] |
Dynamically update ModelForm's Meta class | 297,383 | <p>I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from <code>as_p()</code>, <code>as_ul()</code>, etc does not reflect the updated Meta exclude.</p>
<p>I assume then that the html is generated when the ModelForm is created not when the <code>as_*()</code> is called. Is there a way to force the update of the HTML? </p>
<p>Is this even the best way to do it? I just assumed this <em>should</em> work.</p>
<p>Thoughts?</p>
<pre><code>from django.forms import ModelForm
from testprogram.online_bookings.models import Passenger
class PassengerInfoForm(ModelForm):
def set_form_excludes(self, exclude_list):
self.Meta.exclude = excludes_list
class Meta:
model = Passenger
exclude = []
</code></pre>
| 17 | 2008-11-17T23:44:27Z | 33,685,003 | <p>Use <code>modelform_factory</code> (<a href="https://docs.djangoproject.com/en/stable/ref/forms/models/#django.forms.models.modelform_factory" rel="nofollow">doc</a>):</p>
<pre><code>from django.forms.models import modelform_factory
from testprogram.online_bookings.models import Passenger
exclude = ('field1', 'field2')
CustomForm = modelform_factory(model=Passenger, exclude=exclude) # generates ModelForm dynamically
custom_form = CustomForm(data=request.POST, ...) # form instance
</code></pre>
| 0 | 2015-11-13T02:31:33Z | [
"python",
"django",
"django-forms",
"metaprogramming",
"modelform"
] |
python (jython) archiving library | 298,004 | <p>Is there a neat archiving library that automatically handles archiving a folder or directories for you out there?
I am using Jython, so Java libs are also open for use.
-UPDATE-
Also Im looking for timestamp archiving. ie </p>
<p>archive-dir/2008/11/16/zipfilebypreference.zip</p>
<p>then the next day call it again and it creates another folder.
Im sure there is something out there on the internet, who knows?</p>
| 1 | 2008-11-18T06:32:35Z | 298,027 | <p>You can use java.util.zip, when I was using Jython the built in zip library in python didn't work </p>
| 1 | 2008-11-18T06:59:56Z | [
"java",
"python",
"jython",
"archive"
] |
python (jython) archiving library | 298,004 | <p>Is there a neat archiving library that automatically handles archiving a folder or directories for you out there?
I am using Jython, so Java libs are also open for use.
-UPDATE-
Also Im looking for timestamp archiving. ie </p>
<p>archive-dir/2008/11/16/zipfilebypreference.zip</p>
<p>then the next day call it again and it creates another folder.
Im sure there is something out there on the internet, who knows?</p>
| 1 | 2008-11-18T06:32:35Z | 298,030 | <p>You have either the:</p>
<ul>
<li><a href="http://www.xhaus.com/alan/python/httpcomp.html" rel="nofollow">gzip library</a> used here in a Jython servlet: </li>
</ul>
<p> </p>
<pre><code>import javax.servlet.http.HttpServlet
import cStringIO
import gzip
import string
def compressBuf(buf):
zbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 6)
zfile.write(buf)
zfile.close()
return zbuf.getvalue()
</code></pre>
<ul>
<li>or the direct used of java.util.zip as illustrated <a href="https://www.acm.org/crossroads/xrds6-3/ovp63.html" rel="nofollow">here</a>, for one file, or for a all directory content.</li>
</ul>
| 3 | 2008-11-18T07:08:09Z | [
"java",
"python",
"jython",
"archive"
] |
How to make the keywords recognizable in simpleparse? | 298,034 | <p>I've been trying to create a parser using simpleparse. I've defined the grammar like this:</p>
<pre><code><w> := [ \n]*
statement_list := statement,(w,statement)?
statement := "MOVE",w,word,w,"TO",w,(word,w)+
word := [A-Za-z],[A-Za-z0-9]*,([-]+,[A-Za-z0-9]+)*
</code></pre>
<p>Now if I try to parse a string</p>
<pre><code>MOVE ABC-DEF TO ABC
MOVE DDD TO XXX
</code></pre>
<p>The second statement gets interpreted as parameters of the first one... This sucks and is obviously not what I want. I have been able to get this working using pyparsing like this:</p>
<pre><code>word = Word(alphas,alphanums+'-')
statement = "MOVE"+word+"TO"+word
statement_list = OneOrMore(statement.setResultsName('statement',True))
</code></pre>
<p>Is there any way to get this working in simpleparse as well?</p>
<p><em>EDIT: clarification below</em></p>
<p>I am not trying to achieve a line-based grammar. What I would like to see being parsed is:</p>
<p>Simple case</p>
<pre><code>MOVE AA TO BB
</code></pre>
<p>More comlex case</p>
<pre><code>MOVE AA TO BB
CC DD
EE FF
</code></pre>
<p>Several of the above statments</p>
<pre><code>MOVE AA TO BB
CC
MOVE CC TO EE
MOVE EE TO FF
GG
HH IIJJK
</code></pre>
| 0 | 2008-11-18T07:12:39Z | 298,492 | <p>The grammar is currently ambiguous. On paper you cannot parse if "MOVE A TO B MOVE C TO D" is two statements, or one statement with particular badly named destinations.</p>
<p>You have two answers. You may like neither.</p>
<ol>
<li><p>You explicitly make your WORD not match any reserved word. That is, you specifically disallow matching MOVE or TO. This is equivalent to saying "MOVE is not a valid parameter name". This makes "MOVE TL TO TM TN TO" an error.</p></li>
<li><p>You modify your grammar so that you can tell where the statement ends. You could add commas "MOVE AA TO BB, CC MOVE TM TO TN, TO, TP". You could add semi-colons or blank lines at the end of statements. You could require that MOVE be the least indented, like Python.</p></li>
</ol>
| 1 | 2008-11-18T11:30:03Z | [
"python",
"parsing"
] |
Optimization of Google App Engine Code | 298,185 | <p>Google app engine tells me to optimize this code. Anybody any ideas what I could do?</p>
<pre><code>def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
</code></pre>
<p>And later in the template I do:</p>
<pre><code>{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
</code></pre>
<p>Where the methods used are:</p>
<pre><code>def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
</code></pre>
| 3 | 2008-11-18T08:51:41Z | 298,204 | <p>I would guess that performing an md5 hash on every item every time is pretty costly. Better store the gravatar email hash somewhere.</p>
| 3 | 2008-11-18T09:03:47Z | [
"python",
"google-app-engine",
"optimization"
] |
Optimization of Google App Engine Code | 298,185 | <p>Google app engine tells me to optimize this code. Anybody any ideas what I could do?</p>
<pre><code>def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
</code></pre>
<p>And later in the template I do:</p>
<pre><code>{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
</code></pre>
<p>Where the methods used are:</p>
<pre><code>def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
</code></pre>
| 3 | 2008-11-18T08:51:41Z | 298,443 | <p>The high CPU usage will be due to fetching 100 entities per request. You have several options here:</p>
<ul>
<li>Using Profile.all().fetch(100) will be ever so slightly faster, and easier to read besides.</li>
<li>Remove any extraneous properties from the Profile model. There's significant per-property overhead deserializing entities.</li>
<li>Display fewer users per page.</li>
<li>Store the output of this page in memcache, and render from memcache whenever you can. That way, you don't need to generate the page often, so it doesn't matter so much if it's high CPU.</li>
</ul>
| 6 | 2008-11-18T11:03:59Z | [
"python",
"google-app-engine",
"optimization"
] |
Optimization of Google App Engine Code | 298,185 | <p>Google app engine tells me to optimize this code. Anybody any ideas what I could do?</p>
<pre><code>def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
</code></pre>
<p>And later in the template I do:</p>
<pre><code>{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
</code></pre>
<p>Where the methods used are:</p>
<pre><code>def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
</code></pre>
| 3 | 2008-11-18T08:51:41Z | 394,928 | <p>It depends where you get the warning of too much CPU.</p>
<p>Is it in the dashboard, it probably is a lot of datastore CPU, no need for optimization.</p>
<p>If the request takes more then 10 sec you need to optimize.</p>
<p>If you get regular Log warnings that a certain request is x.xx over CPU limit it means your application code is taking too long. And needs optimization.</p>
<p>I have found that a lot of Django template stuff does not take a lot of application CPU (50-100 Mcycle). If all the fields for the template are precomputed.</p>
| 0 | 2008-12-27T11:42:45Z | [
"python",
"google-app-engine",
"optimization"
] |
Optimization of Google App Engine Code | 298,185 | <p>Google app engine tells me to optimize this code. Anybody any ideas what I could do?</p>
<pre><code>def index(request):
user = users.get_current_user()
return base.views.render('XXX.html',
dict(profiles=Profile.gql("").fetch(limit=100), user=user))
</code></pre>
<p>And later in the template I do:</p>
<pre><code>{% for profile in profiles %}
<a href="/profile/{{profile.user.email}}/"><img src="{{profile.gravatarUrl}}"></a>
<a href="/profile/{{profile.user.email}}/">{{ profile.user.nickname }}</a>
<br/>{{ profile.shortDisplay }}
</code></pre>
<p>Where the methods used are:</p>
<pre><code>def shortDisplay(self):
return "%s/day; %s/week; %s days" % (self.maxPerDay, self.maxPerWeek, self.days)
def gravatarUrl(self):
email = self.user.email().lower()
default = "..."
gravatar_url = "http://www.gravatar.com/avatar.php?"
gravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email).hexdigest(),
'default':default, 'size':"64"})
return gravatar_url
</code></pre>
| 3 | 2008-11-18T08:51:41Z | 1,995,866 | <p>I had an issue with a lot of CPU being used for seemingly little work, which turned out ot be queries running multiple times. Eg. In my Django template, I did post.comments.count and then looped through post.comments. This resulted in two executions - one getting the count, and one getting the entities. Oops!</p>
<p>I'd also say grab a copy of Guido's Appstats. It won't help with the Python, but it's very useful to see the time spent in API calls (and the time between them - which often gives an indication of where you've got slow Python).</p>
<p>You can get the library here: <a href="https://sites.google.com/site/appengineappstats/" rel="nofollow">https://sites.google.com/site/appengineappstats/</a></p>
<p>I wrote an article about it on my blog (with some screenshots): <a href="http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats" rel="nofollow">http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats</a></p>
<p><a href="http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats" rel="nofollow"><img src="http://blog.dantup.com/pi/appstats_4_thumb.png" alt="Appstats"></a></p>
| 1 | 2010-01-03T18:50:42Z | [
"python",
"google-app-engine",
"optimization"
] |
Looping in Django forms | 298,446 | <p>I've just started building a prototype application in Django. I started out by working through the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">Django app tutorial on the Django site</a> which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions:</p>
<p>I want to put a loop into views.py, looping over a set of variables that have been passed in from a form. So I have a load of items in the HTML form, each of which has a SELECT drop-down list for people to select a score from 0-10, like this:</p>
<pre><code><select name="score1">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</code></pre>
<p>So I have, let's say, 100 of these variables, score1, score2, score3, ..., score99, score100. When the form is submitted, I want to loop through each of these variables and see if it's been set (i.e. is not 0) and if so, I want to store that value in a suitable place in the database. My problem is that I can't figure out how to loop through those variables.
I'm guessing that I want something like this:</p>
<pre><code>for o in request.POST.all
endfor
</code></pre>
<p>but then I'm really not sure what to do with that.</p>
<p>I'm not looking for someone to write the code for me, really: I just would like some guidance on how to write a loop like this in python / Django, and also maybe some pointers as to a good reference guide I can either see online or buy that will give me access to this kind of thing.</p>
<p>Also, the select object above I created pretty much by hand, and I'd really like to be able to ue a loop to generate it in the template in the first place. My template currently has this:</p>
<pre><code><table>
{% for movie in movie_list %}
<tr>
<td> {{ movie }} </td>
<td>
<select name="score{{ movie.id }}">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</td></tr>
{% endfor %}
</table>
</code></pre>
<p>I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that...</p>
| 0 | 2008-11-18T11:05:53Z | 298,489 | <p>You need to look at the Django <a href="http://docs.djangoproject.com/en/dev/topics/forms/#topics-forms-index">forms</a>.</p>
<p>You should never build your own form like that.</p>
<p>You should declare a Form class which includes a <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield">ChoiceField</a> and provide the domain of choices to that field. Everything will happen pretty much automatically from there.</p>
<p>The choices, BTW, should be defined in your Model as the range of values for that Model field.</p>
<p>Your page merely includes <code>{{form}}</code>. Django builds the form with the choices and decodes the choices to a final result.</p>
| 7 | 2008-11-18T11:27:21Z | [
"python",
"django"
] |
Looping in Django forms | 298,446 | <p>I've just started building a prototype application in Django. I started out by working through the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">Django app tutorial on the Django site</a> which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions:</p>
<p>I want to put a loop into views.py, looping over a set of variables that have been passed in from a form. So I have a load of items in the HTML form, each of which has a SELECT drop-down list for people to select a score from 0-10, like this:</p>
<pre><code><select name="score1">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</code></pre>
<p>So I have, let's say, 100 of these variables, score1, score2, score3, ..., score99, score100. When the form is submitted, I want to loop through each of these variables and see if it's been set (i.e. is not 0) and if so, I want to store that value in a suitable place in the database. My problem is that I can't figure out how to loop through those variables.
I'm guessing that I want something like this:</p>
<pre><code>for o in request.POST.all
endfor
</code></pre>
<p>but then I'm really not sure what to do with that.</p>
<p>I'm not looking for someone to write the code for me, really: I just would like some guidance on how to write a loop like this in python / Django, and also maybe some pointers as to a good reference guide I can either see online or buy that will give me access to this kind of thing.</p>
<p>Also, the select object above I created pretty much by hand, and I'd really like to be able to ue a loop to generate it in the template in the first place. My template currently has this:</p>
<pre><code><table>
{% for movie in movie_list %}
<tr>
<td> {{ movie }} </td>
<td>
<select name="score{{ movie.id }}">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</td></tr>
{% endfor %}
</table>
</code></pre>
<p>I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that...</p>
| 0 | 2008-11-18T11:05:53Z | 298,499 | <blockquote>
<p>I feel like there must be a way to
create a simple loop that counts from
1 to 10 that would generate most of
those options for me, but I can't
figure out how to do that...</p>
</blockquote>
<p>If you don't want to use Django forms (why btw?), check out this <a href="http://www.djangosnippets.org/snippets/779/" rel="nofollow">custom range tag</a> or just pass a range(1, 11) object into your template and use it in the <code>{% for %}</code> loop.</p>
| 1 | 2008-11-18T11:33:58Z | [
"python",
"django"
] |
Looping in Django forms | 298,446 | <p>I've just started building a prototype application in Django. I started out by working through the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">Django app tutorial on the Django site</a> which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions:</p>
<p>I want to put a loop into views.py, looping over a set of variables that have been passed in from a form. So I have a load of items in the HTML form, each of which has a SELECT drop-down list for people to select a score from 0-10, like this:</p>
<pre><code><select name="score1">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</code></pre>
<p>So I have, let's say, 100 of these variables, score1, score2, score3, ..., score99, score100. When the form is submitted, I want to loop through each of these variables and see if it's been set (i.e. is not 0) and if so, I want to store that value in a suitable place in the database. My problem is that I can't figure out how to loop through those variables.
I'm guessing that I want something like this:</p>
<pre><code>for o in request.POST.all
endfor
</code></pre>
<p>but then I'm really not sure what to do with that.</p>
<p>I'm not looking for someone to write the code for me, really: I just would like some guidance on how to write a loop like this in python / Django, and also maybe some pointers as to a good reference guide I can either see online or buy that will give me access to this kind of thing.</p>
<p>Also, the select object above I created pretty much by hand, and I'd really like to be able to ue a loop to generate it in the template in the first place. My template currently has this:</p>
<pre><code><table>
{% for movie in movie_list %}
<tr>
<td> {{ movie }} </td>
<td>
<select name="score{{ movie.id }}">
<option value=0 SELECTED>No score</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select>
</td></tr>
{% endfor %}
</table>
</code></pre>
<p>I feel like there must be a way to create a simple loop that counts from 1 to 10 that would generate most of those options for me, but I can't figure out how to do that...</p>
| 0 | 2008-11-18T11:05:53Z | 300,462 | <p>Follow S.Lotts advice on forms, it'll save time in the long run to do them the Django way now. For that loop you were looking for:</p>
<pre><code><select name="score{{ movie.id }}">
<option value=0 SELECTED>No score</option>
{% for i in range(1, 11) %}
<option value={{ i }}>{{ i }}</option>
{% endfor %}
</select>
</code></pre>
| 1 | 2008-11-18T22:56:56Z | [
"python",
"django"
] |
Django Template Variables and Javascript | 298,772 | <p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p>
<p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
| 92 | 2008-11-18T13:52:31Z | 298,793 | <p>The <code>{{variable}}</code> is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.</p>
<p>Having said that, you can put this kind of substitution into your JavaScript.</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
</code></pre>
<p>This gives you "dynamic" javascript.</p>
| 131 | 2008-11-18T14:00:58Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] |
Django Template Variables and Javascript | 298,772 | <p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p>
<p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
| 92 | 2008-11-18T13:52:31Z | 304,627 | <p>For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library. </p>
| 7 | 2008-11-20T08:19:31Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] |
Django Template Variables and Javascript | 298,772 | <p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p>
<p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
| 92 | 2008-11-18T13:52:31Z | 8,483,184 | <p>A solution that worked for me is using the hidden input field in the template</p>
<pre><code><input type="hidden" id="myVar" name="variable" value="{{ variable }}">
</code></pre>
<p>Then getting the value in javascript this way,</p>
<pre><code>var myVar = document.getElementById("myVar").value;
</code></pre>
| 22 | 2011-12-13T01:15:07Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.