title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Manually giving the twisted (web) network stack a packet to process? | 1,546,745 | <p>I am running an HTTP server using the twisted framework. Is there any way I can "manually" ask it to process some payload? For example, if I've constructed some Ethernet frame can I ask twisted's reactor to handle it just as if it had just arrived on my network card?</p>
| 1 | 2009-10-10T01:09:29Z | 8,650,185 | <p>You can do something like this:</p>
<pre><code>from twisted.web import server
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ClientFactory
class SomeWebThing(Resource):
def render_GET(self, request):
return "hello\n"
class SomeClient(Protocol):
def dataReceived(self, data):
p = self.factory.site.buildProtocol(self.transport.addr)
p.transport = self.transport
p.dataReceived(data)
class SomeClientFactory(ClientFactory):
protocol = SomeClient
def __init__(self, site):
self.site = site
if __name__ == '__main__':
root = Resource()
root.putChild('thing', SomeWebThing())
site = server.Site(root)
reactor.listenTCP(8000, site)
factory = SomeClientFactory(site)
reactor.connectTCP('localhost', 9000, factory)
reactor.run()
</code></pre>
<p>and save it as simpleinjecter.py, if you then do (from the commandline):</p>
<pre><code>echo -e "GET /thing HTTP/1.1\r\n\r\n" | nc -l 9000 # runs a server, ready to send req to first client connection
python simpleinjecter.py
</code></pre>
<p>it should work as expected, with the request from the nc server on port 9000 getting funneled as the payload into the twisted web server, and the response coming back as expected.</p>
<p>The key lines are in SomeClient.dataRecieved(). You'll need a transport object with the right methods -- in the example above, I just steal the object from the client connection. If you aren't going to do that, I imagine you'll have to make one up, as the stack will want to do things like call getPeer() on it.</p>
| 2 | 2011-12-27T23:07:21Z | [
"python",
"twisted"
] |
How to create a specific if condition templatetag with Django? | 1,546,816 | <p>My problem is a if condition.</p>
<p>I would like somethings like that but cannot figure out how to do it.</p>
<pre><code>{% if restaurant.is_favorite_of(user) %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}
</code></pre>
<p>In the Favorite manager, I created :</p>
<pre><code>def is_favorite(self, user, content_object):
"""
This method returns :
- True if content_object is favorite of user
- False if not
>>> user = User.objects.get(username="alice")
>>> fav_user = User.objects.get(username="bob")
>>> fav1 = Favorite.create_favorite(user, fav_user)
>>> Favorite.objects.is_favorite(user, fav_user)
True
>>> Favorite.objects.is_favorite(user, user)
False
>>> Favorite.objects.all().delete()
Above if we test if bob is favorite of alice it is true.
But alice is not favorite of alice.
"""
ct = ContentType.objects.get_for_model(type(content_object))
try:
self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id)
return True
except Favorite.DoesNotExist:
return False
</code></pre>
<p>Because in Django templates there is no way of doing it likes this, I could do a templatetag that act like that :</p>
<pre><code>{% is_favorite user resto %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}
</code></pre>
<p>But how to do it ?
Do you have a better idea ?</p>
| 3 | 2009-10-10T01:53:39Z | 1,546,838 | <p>Maybe I could use <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags" rel="nofollow">the inclusion tag</a>.</p>
<p>Create a tag like that :</p>
<pre><code>{% show_favorite_img user restaurant %}
</code></pre>
<p>templatetags/user_extra.py :</p>
<pre><code>@register.inclusion_tag('users/favorites.html')
def show_favorite_img(user, restaurant):
return {'is_favorite': Favorite.objects.is_favorite(user, restaurant)}
</code></pre>
| 2 | 2009-10-10T02:09:08Z | [
"python",
"django",
"django-templates",
"favorites"
] |
How to create a specific if condition templatetag with Django? | 1,546,816 | <p>My problem is a if condition.</p>
<p>I would like somethings like that but cannot figure out how to do it.</p>
<pre><code>{% if restaurant.is_favorite_of(user) %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}
</code></pre>
<p>In the Favorite manager, I created :</p>
<pre><code>def is_favorite(self, user, content_object):
"""
This method returns :
- True if content_object is favorite of user
- False if not
>>> user = User.objects.get(username="alice")
>>> fav_user = User.objects.get(username="bob")
>>> fav1 = Favorite.create_favorite(user, fav_user)
>>> Favorite.objects.is_favorite(user, fav_user)
True
>>> Favorite.objects.is_favorite(user, user)
False
>>> Favorite.objects.all().delete()
Above if we test if bob is favorite of alice it is true.
But alice is not favorite of alice.
"""
ct = ContentType.objects.get_for_model(type(content_object))
try:
self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id)
return True
except Favorite.DoesNotExist:
return False
</code></pre>
<p>Because in Django templates there is no way of doing it likes this, I could do a templatetag that act like that :</p>
<pre><code>{% is_favorite user resto %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}
</code></pre>
<p>But how to do it ?
Do you have a better idea ?</p>
| 3 | 2009-10-10T01:53:39Z | 1,547,306 | <p>Easiest way is to create a filter.</p>
<pre><code>@register.filter
def is_favourite_of(object, user):
return Favourite.objects.is_favourite(user, object)
</code></pre>
<p>and in the template:</p>
<pre><code>{% if restaurant|is_favourite_of:user %}
</code></pre>
| 11 | 2009-10-10T07:35:06Z | [
"python",
"django",
"django-templates",
"favorites"
] |
How to create a specific if condition templatetag with Django? | 1,546,816 | <p>My problem is a if condition.</p>
<p>I would like somethings like that but cannot figure out how to do it.</p>
<pre><code>{% if restaurant.is_favorite_of(user) %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}
</code></pre>
<p>In the Favorite manager, I created :</p>
<pre><code>def is_favorite(self, user, content_object):
"""
This method returns :
- True if content_object is favorite of user
- False if not
>>> user = User.objects.get(username="alice")
>>> fav_user = User.objects.get(username="bob")
>>> fav1 = Favorite.create_favorite(user, fav_user)
>>> Favorite.objects.is_favorite(user, fav_user)
True
>>> Favorite.objects.is_favorite(user, user)
False
>>> Favorite.objects.all().delete()
Above if we test if bob is favorite of alice it is true.
But alice is not favorite of alice.
"""
ct = ContentType.objects.get_for_model(type(content_object))
try:
self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id)
return True
except Favorite.DoesNotExist:
return False
</code></pre>
<p>Because in Django templates there is no way of doing it likes this, I could do a templatetag that act like that :</p>
<pre><code>{% is_favorite user resto %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}
</code></pre>
<p>But how to do it ?
Do you have a better idea ?</p>
| 3 | 2009-10-10T01:53:39Z | 1,549,535 | <p>When all else fails you can use the {% expr whatever %} tag to compute a value and stick it in a variable that you can use in your template. I don't let designers know about it, but sometimes it's the only thing that works short of standing on your head and ... well, you know.</p>
<p>See <a href="http://www.djangosnippets.org/snippets/9/" rel="nofollow">http://www.djangosnippets.org/snippets/9/</a></p>
| 0 | 2009-10-11T01:01:17Z | [
"python",
"django",
"django-templates",
"favorites"
] |
Str in Python's map and sum | 1,546,846 | <p><strong>Why do you need to use the function 'str' in the following code?</strong></p>
<p>I am trying to count the sum of digits in a number.</p>
<p><strong>My code</strong></p>
<pre><code>for i in number:
sum(map(int, str(i))
</code></pre>
<p>where <em>number</em> is the following array</p>
<pre><code>[7,79,9]
</code></pre>
<p>I read my code as follows</p>
<ol>
<li>loop though the array such that</li>
<li>count sum of the integer digits</li>
<li>by getting given digits in a number by <strong>map</strong> increasingly</li>
<li>such that each object (given number) is converted to String <strong>// This does not make sense</strong></li>
</ol>
<p>Manual says this for <em>str</em></p>
<pre><code>Type: type
Base Class: <type 'type'>
String Form: <type 'str'>
Namespace: Python builtin
Docstring:
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
</code></pre>
| 1 | 2009-10-10T02:13:21Z | 1,546,853 | <p>What happens when you try that code without using <code>str()</code>?</p>
<p>The <code>str()</code> is used to convert the integer into a sequence of characters, so that <code>map()</code> can iterate over the sequence. The key point here is that a "string" can be treated as a "sequence of characters".</p>
| 2 | 2009-10-10T02:19:02Z | [
"python",
"string"
] |
Str in Python's map and sum | 1,546,846 | <p><strong>Why do you need to use the function 'str' in the following code?</strong></p>
<p>I am trying to count the sum of digits in a number.</p>
<p><strong>My code</strong></p>
<pre><code>for i in number:
sum(map(int, str(i))
</code></pre>
<p>where <em>number</em> is the following array</p>
<pre><code>[7,79,9]
</code></pre>
<p>I read my code as follows</p>
<ol>
<li>loop though the array such that</li>
<li>count sum of the integer digits</li>
<li>by getting given digits in a number by <strong>map</strong> increasingly</li>
<li>such that each object (given number) is converted to String <strong>// This does not make sense</strong></li>
</ol>
<p>Manual says this for <em>str</em></p>
<pre><code>Type: type
Base Class: <type 'type'>
String Form: <type 'str'>
Namespace: Python builtin
Docstring:
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
</code></pre>
| 1 | 2009-10-10T02:13:21Z | 1,546,862 | <p>Given <code>79</code> you need to get <code>[7, 9]</code> in order to sum up this list.</p>
<p>What does it mean to split a number into digits? It means to represent the number in a numerical system with some base (base <code>10</code> in this case). E. g. <code>79</code> is <code>7 * 10**1 + 9 * 10**0</code>.</p>
<p>And what is the simplest (well, at least in this context) way to get such a representation of a number? To convert it to a string of decimals!</p>
<p>Your code does exactly that:</p>
<pre><code>>>> str(79)
'79'
# Another way to say this is [int(c) for c in str(79)]
>>> map(int, str(79))
[7, 9]
>>> sum(map(int, str(79)))
16
</code></pre>
| 8 | 2009-10-10T02:24:11Z | [
"python",
"string"
] |
Str in Python's map and sum | 1,546,846 | <p><strong>Why do you need to use the function 'str' in the following code?</strong></p>
<p>I am trying to count the sum of digits in a number.</p>
<p><strong>My code</strong></p>
<pre><code>for i in number:
sum(map(int, str(i))
</code></pre>
<p>where <em>number</em> is the following array</p>
<pre><code>[7,79,9]
</code></pre>
<p>I read my code as follows</p>
<ol>
<li>loop though the array such that</li>
<li>count sum of the integer digits</li>
<li>by getting given digits in a number by <strong>map</strong> increasingly</li>
<li>such that each object (given number) is converted to String <strong>// This does not make sense</strong></li>
</ol>
<p>Manual says this for <em>str</em></p>
<pre><code>Type: type
Base Class: <type 'type'>
String Form: <type 'str'>
Namespace: Python builtin
Docstring:
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
</code></pre>
| 1 | 2009-10-10T02:13:21Z | 1,547,166 | <p><strong>Why do you need to use the function 'str' in the following code?</strong></p>
<p>Because map takes an iterable, like a list or a tuple or a string.</p>
<p>The code in question adds upp all the numbers in an integer. And it does it by a little clever hack. It converts the number into a sequence of numbers by doing</p>
<pre><code>map(int, str(i))
</code></pre>
<p>This will convert the integer 2009 to the list [2, 0, 0, 9]. The sum() then adds all this integers up, and you get 11.</p>
<p>A less hacky version would be:</p>
<pre><code>>>> number = [7,79,9]
>>> for i in number:
... result = 0
... while i:
... i, n = divmod(i, 10)
... result +=n
... print result
...
7
16
9
</code></pre>
<p>But your version is admittedly more clever.</p>
| 2 | 2009-10-10T05:47:06Z | [
"python",
"string"
] |
Workflow for maintaining different versions of codebase for different versions of Python | 1,546,917 | <p>I'm developing an open source application called <a href="http://garlicsim.org" rel="nofollow">GarlicSim</a>.</p>
<p>Up to now I've been developing it only for Python 2.6. It seems not to work on any other version.</p>
<p>I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4.</p>
<p>So I have several questions:</p>
<ol>
<li>What would be a good way to organize the folder structure of my repo to include these different versions?</li>
<li>What would be a good way to 'merge' changes I do in one version of the code to other versions? I know how to do merges in my SCM (which is git), but these are folders that are all in the same repo, and I want to do a merge between them. There is of course the option of having a repo for each version, but I think it's not a good idea.</li>
</ol>
<p>Does anyone have any suggestions?</p>
| 4 | 2009-10-10T03:10:20Z | 1,546,944 | <p>I would try to maintain one branch to cover all the python 2.4-2.6</p>
<p>The differences are not so great, after all if you have to write a bunch of extra code for 2.4 to do something that is easy in 2.6, it will be less work for you in the long run to use the 2.4 version for 2.5 and 2.6.</p>
<p>Python 3 should have a different branch, you should still try to keep as much code in common as you can.</p>
| 2 | 2009-10-10T03:28:21Z | [
"python",
"git",
"merge",
"version",
"organization"
] |
Workflow for maintaining different versions of codebase for different versions of Python | 1,546,917 | <p>I'm developing an open source application called <a href="http://garlicsim.org" rel="nofollow">GarlicSim</a>.</p>
<p>Up to now I've been developing it only for Python 2.6. It seems not to work on any other version.</p>
<p>I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4.</p>
<p>So I have several questions:</p>
<ol>
<li>What would be a good way to organize the folder structure of my repo to include these different versions?</li>
<li>What would be a good way to 'merge' changes I do in one version of the code to other versions? I know how to do merges in my SCM (which is git), but these are folders that are all in the same repo, and I want to do a merge between them. There is of course the option of having a repo for each version, but I think it's not a good idea.</li>
</ol>
<p>Does anyone have any suggestions?</p>
| 4 | 2009-10-10T03:10:20Z | 1,547,094 | <p>If your code is not overly dependent on the run-time performance in exception handlers, you might even get away without having a separate branch for Py3. I've managed to keep one version of pyparsing for all of my Py2.x versions, although I've had to stick with a "lowest common denominator" approach, meaning that I have to forego using some constructs like generator expressions, and to your point, context managers. I use dicts in place of sets, and all my generator expressions get wrapped as list comprehensions, so they will still work going back to Python 2.3. I have a block at the top of my code that takes care of a number of 2vs3 issues (contributed by pyparsing user Robert A Clark):</p>
<pre><code>_PY3K = sys.version_info[0] > 2
if _PY3K:
_MAX_INT = sys.maxsize
basestring = str
unichr = chr
unicode = str
_str2dict = set
alphas = string.ascii_lowercase + string.ascii_uppercase
else:
_MAX_INT = sys.maxint
range = xrange
def _str2dict(strg):
return dict( [(c,0) for c in strg] )
alphas = string.lowercase + string.uppercase
</code></pre>
<p>The biggest difficulty I've had has been with the incompatible syntax for catching exceptions, that was introduced in Py3, changing from </p>
<pre><code>except exceptiontype,varname:
</code></pre>
<p>to</p>
<pre><code>except exceptionType as varname:
</code></pre>
<p>Of course, if you don't really need the exception variable, you can just write:</p>
<pre><code>except exceptionType:
</code></pre>
<p>and this will work on Py2 or Py3. But if you need to access the exception, you can still come up with a cross-version compatible syntax as:</p>
<pre><code>except exceptionType:
exceptionvar = sys.exc_info()[1]
</code></pre>
<p>This has a minor run-time penalty, which makes this unusable in some places in pyparsing, so I still have to maintain separate Py2 and Py3 versions. For source merging, I use the utility <a href="http://winmerge.org/" rel="nofollow">WinMerge</a>, which I find very good for keeping directories of source code in synch.</p>
<p>So even though I keep two versions of my code, some of these unification techniques help me to keep the differences down to the absolute incompatible minimum.</p>
| 1 | 2009-10-10T04:55:29Z | [
"python",
"git",
"merge",
"version",
"organization"
] |
Workflow for maintaining different versions of codebase for different versions of Python | 1,546,917 | <p>I'm developing an open source application called <a href="http://garlicsim.org" rel="nofollow">GarlicSim</a>.</p>
<p>Up to now I've been developing it only for Python 2.6. It seems not to work on any other version.</p>
<p>I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4.</p>
<p>So I have several questions:</p>
<ol>
<li>What would be a good way to organize the folder structure of my repo to include these different versions?</li>
<li>What would be a good way to 'merge' changes I do in one version of the code to other versions? I know how to do merges in my SCM (which is git), but these are folders that are all in the same repo, and I want to do a merge between them. There is of course the option of having a repo for each version, but I think it's not a good idea.</li>
</ol>
<p>Does anyone have any suggestions?</p>
| 4 | 2009-10-10T03:10:20Z | 1,547,148 | <p>You need separate branches for separate versions only in the rarest of cases. You mention context managers, and they are great, and it would suck not to use them, and you are right. But for Python 2.4 you will have to not use them. So that will suck. So therefore, if you want to support Python 2.4 you'll have to write a version without context managers. But that one will work under Python 2.6 too, so there is no point in having separate versions there.</p>
<p>As for Python 3, having a separate branch there is a solution, but generally not the best one.
For Python 3 support there is something called 2to3 which will convert your Python 2 code to Python 3 code. It's not perfect, so quite often you will have to modify the Python 2 code to generate nice Python 3 code, but the Python 2 code has a tendency to become better as a result anyway.</p>
<p>With Distribute (a maintained fork of setuptools) you can make this conversation automatically during install. That way you don't have to have a separate branch even for Python 3. See <a href="http://bitbucket.org/tarek/distribute/src/tip/docs/python3.txt" rel="nofollow">http://bitbucket.org/tarek/distribute/src/tip/docs/python3.txt</a> for the docs on that.</p>
<p>As Paul McGuire writes it is even possible to support Python 3 and Python 2 with the same code without using 2to3, but I would not recommend it if you want to support anything else than 2.6 and 3.x. You get too much of this ugly special hacks. With 2.6 there is enough forwards compatibility with Python 3 to make it possible to write decent looking code and support both Python 2.6 and 3.x, but not Python 2.5 and 3.x.</p>
| 3 | 2009-10-10T05:32:09Z | [
"python",
"git",
"merge",
"version",
"organization"
] |
Workflow for maintaining different versions of codebase for different versions of Python | 1,546,917 | <p>I'm developing an open source application called <a href="http://garlicsim.org" rel="nofollow">GarlicSim</a>.</p>
<p>Up to now I've been developing it only for Python 2.6. It seems not to work on any other version.</p>
<p>I decided it's important to produce versions of it that will support other versions of Python. I'm thinking I'll make a version for 2.5, 3.1 and maybe 2.4.</p>
<p>So I have several questions:</p>
<ol>
<li>What would be a good way to organize the folder structure of my repo to include these different versions?</li>
<li>What would be a good way to 'merge' changes I do in one version of the code to other versions? I know how to do merges in my SCM (which is git), but these are folders that are all in the same repo, and I want to do a merge between them. There is of course the option of having a repo for each version, but I think it's not a good idea.</li>
</ol>
<p>Does anyone have any suggestions?</p>
| 4 | 2009-10-10T03:10:20Z | 1,548,784 | <p>I eventually decided to have 4 different forks for my project, for 2.4, 2.5, 2.6 and 3.1. My main priority is 2.6 and I don't want to compromise the elegance of that code for the sake of 2.4. So the ugly compatibility hacks will be on the lower versions, not the higher versions.</p>
| 0 | 2009-10-10T18:57:39Z | [
"python",
"git",
"merge",
"version",
"organization"
] |
Defining private module functions in python | 1,547,145 | <p>According to <a href="http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html">http://www.faqs.org/docs/diveintopython/fileinfo_private.html</a>:</p>
<blockquote>
<p>Like most languages, Python has the
concept of private elements: </p>
<ul>
<li>Private
functions, which can't be called from
<strong>outside their module</strong></li>
</ul>
</blockquote>
<p>However, if I define two files:</p>
<pre><code>#a.py
__num=1
</code></pre>
<p>and:</p>
<pre><code>#b.py
import a
print a.__num
</code></pre>
<p>when i run <code>b.py</code> it prints out <code>1</code> without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to <strong>do</strong> define a module's function as private?</p>
| 106 | 2009-10-10T05:30:20Z | 1,547,159 | <p>Python allows for private <em>class</em> members with the double underscore prefix. This technique doesn't work at a module level so I am thinking this is a mistake in Dive Into Python.</p>
<p>Here is an example of private class functions:</p>
<pre><code>class foo():
def bar(self): pass
def __bar(self): pass
f = foo()
f.bar() # this call succeeds
f.__bar() # this call fails
</code></pre>
| 21 | 2009-10-10T05:39:17Z | [
"python",
"function",
"module",
"private"
] |
Defining private module functions in python | 1,547,145 | <p>According to <a href="http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html">http://www.faqs.org/docs/diveintopython/fileinfo_private.html</a>:</p>
<blockquote>
<p>Like most languages, Python has the
concept of private elements: </p>
<ul>
<li>Private
functions, which can't be called from
<strong>outside their module</strong></li>
</ul>
</blockquote>
<p>However, if I define two files:</p>
<pre><code>#a.py
__num=1
</code></pre>
<p>and:</p>
<pre><code>#b.py
import a
print a.__num
</code></pre>
<p>when i run <code>b.py</code> it prints out <code>1</code> without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to <strong>do</strong> define a module's function as private?</p>
| 106 | 2009-10-10T05:30:20Z | 1,547,160 | <p>There may be confusion between <strong><em>class privates</em></strong> and <strong><em>module privates</em></strong>.</p>
<p>A <em>module private</em> starts with <strong>one underscore</strong><br>
Such a element is not copied along when using the <code>from <module_name> import *</code> form of the import command; it is however imported if using the <code>import <moudule_name></code> syntax (<a href="https://stackoverflow.com/a/13618522/166686">see Ben Wilhelm's answer</a>)<br>
Simply remove one underscore from the a.__num of the question's example and it won't show in modules that import a.py using the <code>from a import *</code> syntax.</p>
<p>A <em>class private</em> starts with <strong>two underscores</strong> (aka dunder i.e. d-ouble under-score) <br>
Such a variable has its name "mangled" to include the classname etc.<br>
It can still be accessed outside of the class logic, through the mangled name.<br>
Although the name mangling can serve as a mild prevention device against unauthorized access, its main purpose is to prevent possible name collisions with class members of the ancestor classes.
See Alex Martelli's funny but accurate reference to <em>consenting adults</em> as he describes the convention used in regards to these variables.</p>
<pre><code>>>> class Foo(object):
... __bar = 99
... def PrintBar(self):
... print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar #direct attempt no go
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar() # the class itself of course can access it
99
>>> dir(Foo) # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar #and get to it by its mangled name ! (but I shouldn't!!!)
99
>>>
</code></pre>
| 141 | 2009-10-10T05:40:54Z | [
"python",
"function",
"module",
"private"
] |
Defining private module functions in python | 1,547,145 | <p>According to <a href="http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html">http://www.faqs.org/docs/diveintopython/fileinfo_private.html</a>:</p>
<blockquote>
<p>Like most languages, Python has the
concept of private elements: </p>
<ul>
<li>Private
functions, which can't be called from
<strong>outside their module</strong></li>
</ul>
</blockquote>
<p>However, if I define two files:</p>
<pre><code>#a.py
__num=1
</code></pre>
<p>and:</p>
<pre><code>#b.py
import a
print a.__num
</code></pre>
<p>when i run <code>b.py</code> it prints out <code>1</code> without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to <strong>do</strong> define a module's function as private?</p>
| 106 | 2009-10-10T05:30:20Z | 1,547,163 | <p>In Python, "privacy" depends on "consenting adults'" levels of agreement - you can't <em>force</em> it (any more than you can in real life;-). A single leading underscore means you're not <strong>supposed</strong> to access it "from the outside" -- <strong>two</strong> leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't <strong>handcuff</strong> every other programmer in the world to respect you wish.</p>
<p>((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple <code>#define private public</code> line before <code>#include</code>ing your <code>.h</code> file is all it takes for wily coders to make hash of your "privacy"...!-))</p>
| 145 | 2009-10-10T05:43:03Z | [
"python",
"function",
"module",
"private"
] |
Defining private module functions in python | 1,547,145 | <p>According to <a href="http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html">http://www.faqs.org/docs/diveintopython/fileinfo_private.html</a>:</p>
<blockquote>
<p>Like most languages, Python has the
concept of private elements: </p>
<ul>
<li>Private
functions, which can't be called from
<strong>outside their module</strong></li>
</ul>
</blockquote>
<p>However, if I define two files:</p>
<pre><code>#a.py
__num=1
</code></pre>
<p>and:</p>
<pre><code>#b.py
import a
print a.__num
</code></pre>
<p>when i run <code>b.py</code> it prints out <code>1</code> without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to <strong>do</strong> define a module's function as private?</p>
| 106 | 2009-10-10T05:30:20Z | 13,618,522 | <p>This question was not fully answered, since module privacy is not purely conventional, and since using <strong>import</strong> may or may not recognize module privacy, depending on how it is used.</p>
<p>If you define private names in a module, those names <strong>will</strong> be imported into any script that uses the syntax, 'import module_name'. Thus, assuming you had correctly defined in your example the module private, _num, in a.py, like so..</p>
<pre><code>#a.py
_num=1
</code></pre>
<p>..you would be able to access it in b.py with the module name symbol:</p>
<pre><code>#b.py
import a
...
foo = a._num # 1
</code></pre>
<p>To import only non-privates from a.py, you must use the <strong>from</strong> syntax:</p>
<pre><code>#b.py
from a import *
...
foo = _num # throws NameError: name '_num' is not defined
</code></pre>
<p>For the sake of clarity, however, it is better to be explicit when importing names from modules, rather than importing them all with a '*':</p>
<pre><code>#b.py
from a import name1
from a import name2
...
</code></pre>
| 45 | 2012-11-29T03:50:32Z | [
"python",
"function",
"module",
"private"
] |
Defining private module functions in python | 1,547,145 | <p>According to <a href="http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html">http://www.faqs.org/docs/diveintopython/fileinfo_private.html</a>:</p>
<blockquote>
<p>Like most languages, Python has the
concept of private elements: </p>
<ul>
<li>Private
functions, which can't be called from
<strong>outside their module</strong></li>
</ul>
</blockquote>
<p>However, if I define two files:</p>
<pre><code>#a.py
__num=1
</code></pre>
<p>and:</p>
<pre><code>#b.py
import a
print a.__num
</code></pre>
<p>when i run <code>b.py</code> it prints out <code>1</code> without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to <strong>do</strong> define a module's function as private?</p>
| 106 | 2009-10-10T05:30:20Z | 37,894,996 | <p>Python has three modes via., private, public and protected .While importing a module only public mode is accessible .So private and protected modules cannot be called from outside of the module i.e., when it is imported .</p>
| 0 | 2016-06-18T08:40:48Z | [
"python",
"function",
"module",
"private"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 1,547,201 | <p><strong>EDIT</strong> I modified it, tried it out, and it works. You just need this piece of code</p>
<p>As soon as ans = 4, ans * ans is no longer smaller than x. Try while ans*ans <= x: instead of just <</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans <= x:
if ans*ans == x:
print x, ' is a perfect square.'
return ans
else:
ans = ans + 1
</code></pre>
| 0 | 2009-10-10T06:18:43Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 1,547,203 | <p>Your <code>while</code> loop only executes once. No matter which branch the <code>if</code> statement inside it takes, the whole function will return immediately.</p>
| 1 | 2009-10-10T06:20:58Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 1,547,206 | <p>Change your code so it displays the value of <code>ans</code> as well as <code>x</code>, so you can tell how many times the loop is executed.</p>
| 0 | 2009-10-10T06:23:12Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 1,547,210 | <p>Indent your code correctly to let the <code>while</code> statement execute until <code>ans*ans < x</code>:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x: # this if statement was nested inside the while
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
print sqrt(y)
</code></pre>
<p>Try it out <a href="http://codepad.org/dnxYtH5t">here</a>.</p>
| 7 | 2009-10-10T06:30:43Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 1,547,224 | <p>If your code sample is actually correctly indentet the first round of the while will return on it's first round - always. So any positive value of x>1 will fullfil the ans*ans=1*1=1!=x, giving "x is not a perfect square". </p>
<p>You basically needs to get your indentation right - like you do in your other example. Again - if your code sample here actually is correctly indented. Try this: </p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
</code></pre>
| 0 | 2009-10-10T06:37:47Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 5,750,159 | <p>If the goal is to determine whether a number is a perfect square, I would think it would be simpler (and perhaps more efficient) to use math builtins, e.g.:</p>
<pre><code>def is_perfect_square(n):
if not ( ( isinstance(n, int) or isinstance(n, long) ) and ( n >= 0 ) ):
return False
else:
return math.sqrt(n) == math.trunc(math.sqrt(n))
</code></pre>
| -1 | 2011-04-21T21:50:41Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 5,767,169 | <p>Just thought I'd contribute a simpler solution:</p>
<pre><code>def is_square(n):
return sqrt(n).is_integer()
</code></pre>
<p><strong>This is valid for <code>n < 2**52 + 2**27 = 4503599761588224</code>.</strong></p>
<p>Examples:</p>
<pre><code>>>> is_square(4)
True
>>> is_square(123)
False
>>> is_square(123123123432**2)
True
</code></pre>
| 10 | 2011-04-23T21:49:19Z | [
"python"
] |
Finding perfect square | 1,547,196 | <p>I have this python code:</p>
<pre><code>def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
</code></pre>
<p>the output is:</p>
<pre><code>16 is not a perfect square.
</code></pre>
<p>Whereas this works perfectly:</p>
<pre><code>x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2009-10-10T06:15:36Z | 24,680,548 | <pre><code>def isPerfectSquare(number):
return len(str(math.sqrt(number)).split('.')[1]) == 1
</code></pre>
| 0 | 2014-07-10T15:29:23Z | [
"python"
] |
Prevent decorator from being used twice on the same function in python | 1,547,222 | <p>I have a decorator:</p>
<pre><code>from functools import wraps
def d(f):
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
return wrapper
</code></pre>
<p>And I want to prevent it from decorating the same function twice, e.g prevent things such as:</p>
<pre><code>@d
@d
def f():
print 2
</code></pre>
<p>Only possible solution I could think of is using a dict to store the functions the decorator has already decorated and raising an exception if asked to decorate a function that exists in the dict.
Do tell if you have a better idea...</p>
| 1 | 2009-10-10T06:35:59Z | 1,547,233 | <p>Look at <code>f.func_code</code>, it can tell you if f is a function or a wrapper.</p>
| -1 | 2009-10-10T06:45:07Z | [
"python",
"decorator"
] |
Prevent decorator from being used twice on the same function in python | 1,547,222 | <p>I have a decorator:</p>
<pre><code>from functools import wraps
def d(f):
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
return wrapper
</code></pre>
<p>And I want to prevent it from decorating the same function twice, e.g prevent things such as:</p>
<pre><code>@d
@d
def f():
print 2
</code></pre>
<p>Only possible solution I could think of is using a dict to store the functions the decorator has already decorated and raising an exception if asked to decorate a function that exists in the dict.
Do tell if you have a better idea...</p>
| 1 | 2009-10-10T06:35:59Z | 1,547,259 | <p>Noam, The property of <code>func_code</code> to use is <code>co_name</code>. See below, all that is changed is two lines at top of d()'s def</p>
<pre><code>def d(f):
if f.func_code.co_name == 'wrapper':
return f #ignore it (or can throw exception instead...)
@wraps(f)
def wrapper(*args, **kwargs):
print 'calling func'
return f(*args, **kwargs)
return wrapper
</code></pre>
<p>Also, see for Lukáš Lalinský's approach which uses a explicitly defined property attached to the function object. This may be preferable as the "wrapper" name may be used elsewhere...</p>
| 0 | 2009-10-10T07:01:49Z | [
"python",
"decorator"
] |
Prevent decorator from being used twice on the same function in python | 1,547,222 | <p>I have a decorator:</p>
<pre><code>from functools import wraps
def d(f):
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
return wrapper
</code></pre>
<p>And I want to prevent it from decorating the same function twice, e.g prevent things such as:</p>
<pre><code>@d
@d
def f():
print 2
</code></pre>
<p>Only possible solution I could think of is using a dict to store the functions the decorator has already decorated and raising an exception if asked to decorate a function that exists in the dict.
Do tell if you have a better idea...</p>
| 1 | 2009-10-10T06:35:59Z | 1,547,261 | <p>I'd store the information in the function itself. There is a risk of a conflict if multiple decorators decide to use the same variable, but if it's only your own code, you should be able to avoid it.</p>
<pre><code>def d(f):
if getattr(f, '_decorated_with_d', False):
raise SomeException('Already decorated')
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
wrapper._decorated_with_d = True
return wrapper
</code></pre>
<p>Another option can be this:</p>
<pre><code>def d(f):
decorated_with = getattr(f, '_decorated_with', set())
if d in decorated_with:
raise SomeException('Already decorated')
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
decorated_with.add(d)
wrapper._decorated_with = decorated_with
return wrapper
</code></pre>
<p>This assumes that you control all the decorators used. If there is a decorator that doesn't copy the <code>_decorated_with</code> attribute, you will not know what is it decorated with.</p>
| 2 | 2009-10-10T07:02:22Z | [
"python",
"decorator"
] |
Prevent decorator from being used twice on the same function in python | 1,547,222 | <p>I have a decorator:</p>
<pre><code>from functools import wraps
def d(f):
@wraps(f)
def wrapper(*args,**kwargs):
print 'Calling func'
return f(*args,**kwargs)
return wrapper
</code></pre>
<p>And I want to prevent it from decorating the same function twice, e.g prevent things such as:</p>
<pre><code>@d
@d
def f():
print 2
</code></pre>
<p>Only possible solution I could think of is using a dict to store the functions the decorator has already decorated and raising an exception if asked to decorate a function that exists in the dict.
Do tell if you have a better idea...</p>
| 1 | 2009-10-10T06:35:59Z | 1,547,305 | <p>I'll also propose my solution:</p>
<p>first, create another decorator:</p>
<pre><code>class DecorateOnce(object):
def __init__(self,f):
self.__f=f
self.__called={} #save all functions that have been decorated
def __call__(self,toDecorate):
#get the distinct func name
funcName=toDecorate.__module__+toDecorate.func_name
if funcName in self.__called:
raise Exception('function already decorated by this decorator')
self.__called[funcName]=1
print funcName
return self.__f(toDecorate)
</code></pre>
<p>Now every decorator you decorate with this decorator, will restrict itself to decorate a func only once:</p>
<pre><code>@DecorateOnce
def decorate(f):
def wrapper...
</code></pre>
| 2 | 2009-10-10T07:33:50Z | [
"python",
"decorator"
] |
Python 3.1.1 with --enable-shared : will not build any extensions | 1,547,310 | <p>Summary: Building Python 3.1 on RHEL 5.3 64 bit with <code>--enable-shared</code> fails to compile all extensions. Building "normal" works fine without any problems.</p>
<p><strong>Please note</strong> that this question may seem to blur the line between programming and system administration. However, I believe that because it has to deal directly with getting language support in place, and it very much has to do with supporting the process of programming, that I would cross-post it here. Also at: <a href="http://serverfault.com/questions/73196/python-3-1-1-with-enable-shared-will-not-build-any-extensions">http://serverfault.com/questions/73196/python-3-1-1-with-enable-shared-will-not-build-any-extensions</a>. Thank you!</p>
<p><strong>Problem:</strong></p>
<p>Building Python 3.1 on RHEL 5.3 64 bit with <code>--enable-shared</code> fails to compile all extensions. Building "normal" works fine without any problems.</p>
<p>I can build python 3.1 just fine, but when built as a shared library, it emits many warnings (see below), and refuses to build any of the <code>c</code> based modules. Despite this failure, I can still build mod_wsgi 3.0c5 against it, and run it under apache. Needless to say, the functionality of Python is greatly reduced...</p>
<p>Interesting to note that Python 3.2a0 (from svn) compiles fine with --enable-shared, and mod_wsgi compiles fine against it. But when starting apache, I get:</p>
<p><code>Cannot load /etc/httpd/modules/mod_wsgi.so into server: /etc/httpd/modules/mod_wsgi.so: undefined symbol: PyCObject_FromVoidPtr</code></p>
<p>The project that this is for is a long-term project, so I'm okay with alpha quality software if needed. Here are some more details on the problem.</p>
<p><strong>Host:</strong></p>
<ul>
<li>Dell PowerEdge</li>
<li>Intel Xenon </li>
<li>RHEL 5.3 64bit</li>
<li>Nothing "special"</li>
</ul>
<p><strong>Build:</strong></p>
<ul>
<li>Python 3.1.1 source distribution</li>
<li>Works fine with <code>./configure</code></li>
<li>Does not work fine with <code>./configure --enable-shared</code></li>
</ul>
<p>(<code>export CFLAGS="-fPIC"</code> has been done)</p>
<p><strong>make output</strong></p>
<p><hr /></p>
<p><code>gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -fPIC -DPy_BUILD_CORE -c ./Modules/_weakref.c -o Modules/_weakref.o</code></p>
<p><hr /></p>
<p><code>building 'bz2' extension
gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I./Include -I/usr/local/include -IInclude -I/home/build/RPMBUILD/BUILD/Python-3.1.1 -c /home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.c -o build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o
gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o -L/usr/local/lib -L. -lbz2 -lpython3.1 -o build/lib.linux-x86_64-3.1/bz2.so
/usr/bin/ld: /usr/local/lib/libpython3.1.a(abstract.o): relocation R_X86_64_32 against 'a local symbol' can not be used when making a shared object; recompile with -fPIC</code></p>
<p><hr /></p>
<pre><code>Failed to build these modules:
_bisect _codecs_cn _codecs_hk
_codecs_iso2022 _codecs_jp _codecs_kr
_codecs_tw _collections _csv
_ctypes _ctypes_test _curses
_curses_panel _dbm _elementtree
_gdbm _hashlib _heapq
_json _lsprof _multibytecodec
_multiprocessing _pickle _random
_socket _sqlite3 _ssl
_struct _testcapi array
atexit audioop binascii
bz2 cmath crypt
datetime fcntl grp
itertools math mmap
nis operator ossaudiodev
parser pyexpat readline
resource select spwd
syslog termios time
unicodedata zlib
</code></pre>
| 6 | 2009-10-10T07:37:29Z | 1,547,352 | <p>Something is wrong with your build environment. It is picking up a libpython3.1.a from <code>/usr/local/lib</code>; this confuses the error messages. It tries linking with that library, which fails - however, it shouldn't have tried that in the first place, since it should have used the libpython that it just built. I recommend taking the Python 3.1 installation in <code>/usr/local</code> out of the way.</p>
<p>You don't show in your output whether a libpython3.1.so.1.0 was created in the build tree; it would be important to find out whether it exists, how it was linked, and what symbols it has exported.</p>
| 5 | 2009-10-10T08:01:32Z | [
"python",
"compilation",
"python-3.x",
"mod-wsgi"
] |
Python 3.1.1 with --enable-shared : will not build any extensions | 1,547,310 | <p>Summary: Building Python 3.1 on RHEL 5.3 64 bit with <code>--enable-shared</code> fails to compile all extensions. Building "normal" works fine without any problems.</p>
<p><strong>Please note</strong> that this question may seem to blur the line between programming and system administration. However, I believe that because it has to deal directly with getting language support in place, and it very much has to do with supporting the process of programming, that I would cross-post it here. Also at: <a href="http://serverfault.com/questions/73196/python-3-1-1-with-enable-shared-will-not-build-any-extensions">http://serverfault.com/questions/73196/python-3-1-1-with-enable-shared-will-not-build-any-extensions</a>. Thank you!</p>
<p><strong>Problem:</strong></p>
<p>Building Python 3.1 on RHEL 5.3 64 bit with <code>--enable-shared</code> fails to compile all extensions. Building "normal" works fine without any problems.</p>
<p>I can build python 3.1 just fine, but when built as a shared library, it emits many warnings (see below), and refuses to build any of the <code>c</code> based modules. Despite this failure, I can still build mod_wsgi 3.0c5 against it, and run it under apache. Needless to say, the functionality of Python is greatly reduced...</p>
<p>Interesting to note that Python 3.2a0 (from svn) compiles fine with --enable-shared, and mod_wsgi compiles fine against it. But when starting apache, I get:</p>
<p><code>Cannot load /etc/httpd/modules/mod_wsgi.so into server: /etc/httpd/modules/mod_wsgi.so: undefined symbol: PyCObject_FromVoidPtr</code></p>
<p>The project that this is for is a long-term project, so I'm okay with alpha quality software if needed. Here are some more details on the problem.</p>
<p><strong>Host:</strong></p>
<ul>
<li>Dell PowerEdge</li>
<li>Intel Xenon </li>
<li>RHEL 5.3 64bit</li>
<li>Nothing "special"</li>
</ul>
<p><strong>Build:</strong></p>
<ul>
<li>Python 3.1.1 source distribution</li>
<li>Works fine with <code>./configure</code></li>
<li>Does not work fine with <code>./configure --enable-shared</code></li>
</ul>
<p>(<code>export CFLAGS="-fPIC"</code> has been done)</p>
<p><strong>make output</strong></p>
<p><hr /></p>
<p><code>gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -fPIC -DPy_BUILD_CORE -c ./Modules/_weakref.c -o Modules/_weakref.o</code></p>
<p><hr /></p>
<p><code>building 'bz2' extension
gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I./Include -I/usr/local/include -IInclude -I/home/build/RPMBUILD/BUILD/Python-3.1.1 -c /home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.c -o build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o
gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o -L/usr/local/lib -L. -lbz2 -lpython3.1 -o build/lib.linux-x86_64-3.1/bz2.so
/usr/bin/ld: /usr/local/lib/libpython3.1.a(abstract.o): relocation R_X86_64_32 against 'a local symbol' can not be used when making a shared object; recompile with -fPIC</code></p>
<p><hr /></p>
<pre><code>Failed to build these modules:
_bisect _codecs_cn _codecs_hk
_codecs_iso2022 _codecs_jp _codecs_kr
_codecs_tw _collections _csv
_ctypes _ctypes_test _curses
_curses_panel _dbm _elementtree
_gdbm _hashlib _heapq
_json _lsprof _multibytecodec
_multiprocessing _pickle _random
_socket _sqlite3 _ssl
_struct _testcapi array
atexit audioop binascii
bz2 cmath crypt
datetime fcntl grp
itertools math mmap
nis operator ossaudiodev
parser pyexpat readline
resource select spwd
syslog termios time
unicodedata zlib
</code></pre>
| 6 | 2009-10-10T07:37:29Z | 1,549,832 | <p>/usr/local/lib has been added to the library include path at compile time:</p>
<p>-L/usr/local/lib -L.</p>
<p>Its common for compile time to look in multiple 'common' paths for libraries (/usr/lib, /usr/local/lib, ./, etc) but also, it's possibly picking up /usr/local/lib from the environment variable LD_LIBRARY_PATH and tacking it on to the build command.</p>
| 0 | 2009-10-11T04:10:17Z | [
"python",
"compilation",
"python-3.x",
"mod-wsgi"
] |
A database for python 3? | 1,547,365 | <p>I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.</p>
<p>Since it's a threaded server, SQLite doesn't work. It complains about threads like this:</p>
<blockquote>
<p>ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712</p>
</blockquote>
<p>Besides, they say SQLite isn't great for concurrency anyhow.</p>
<p>Now since I started working with Python 3 (and would rather continue using it) I can't seem to get the MySQL module to work properly and others seem equally frustrated.</p>
<p>In that case, is there any other DB option for Python 3 that I could consider?</p>
| 3 | 2009-10-10T08:09:24Z | 1,547,369 | <p>I did a <a href="http://www.dcl.hpi.uni-potsdam.de/home/loewis/psycopg%5F3k.diff" rel="nofollow">port</a> of psycopg2 to Python 3.</p>
| 1 | 2009-10-10T08:11:53Z | [
"python",
"database",
"python-3.x"
] |
A database for python 3? | 1,547,365 | <p>I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.</p>
<p>Since it's a threaded server, SQLite doesn't work. It complains about threads like this:</p>
<blockquote>
<p>ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712</p>
</blockquote>
<p>Besides, they say SQLite isn't great for concurrency anyhow.</p>
<p>Now since I started working with Python 3 (and would rather continue using it) I can't seem to get the MySQL module to work properly and others seem equally frustrated.</p>
<p>In that case, is there any other DB option for Python 3 that I could consider?</p>
| 3 | 2009-10-10T08:09:24Z | 1,547,384 | <p>You could create a new sqlite object in each thread, each using the same database file. For such a small number of users you might not come across the problems with concurrency, unless they are all writing to it very heavily.</p>
| 0 | 2009-10-10T08:26:13Z | [
"python",
"database",
"python-3.x"
] |
A database for python 3? | 1,547,365 | <p>I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.</p>
<p>Since it's a threaded server, SQLite doesn't work. It complains about threads like this:</p>
<blockquote>
<p>ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712</p>
</blockquote>
<p>Besides, they say SQLite isn't great for concurrency anyhow.</p>
<p>Now since I started working with Python 3 (and would rather continue using it) I can't seem to get the MySQL module to work properly and others seem equally frustrated.</p>
<p>In that case, is there any other DB option for Python 3 that I could consider?</p>
| 3 | 2009-10-10T08:09:24Z | 1,547,572 | <p>First note that <a href="http://www.sqlite.org/faq.html#q6">sqlite is thread safe</a></p>
<pre><code>$ python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
>>> sqlite.threadsafety
1
</code></pre>
<p>Then just make sure you open a new handle to the database in each thread.</p>
<p>I do this using thread local storage to cache the database handle so there is only one per thread. Something like this... (from a py2.5 prog - hopefully it will work with 3.0!)</p>
<pre><code>import threading
class YourClass:
def __init__(self):
#...
self.local = threading.local() # Thread local storage for db handles
self.db_file = "/path/to/db"
#...
def db_open(self):
if not getattr(self.local, "db", None):
self.local.db = sqlite3.connect(self.db_file)
return self.local.db
</code></pre>
| 7 | 2009-10-10T10:20:12Z | [
"python",
"database",
"python-3.x"
] |
A database for python 3? | 1,547,365 | <p>I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.</p>
<p>Since it's a threaded server, SQLite doesn't work. It complains about threads like this:</p>
<blockquote>
<p>ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712</p>
</blockquote>
<p>Besides, they say SQLite isn't great for concurrency anyhow.</p>
<p>Now since I started working with Python 3 (and would rather continue using it) I can't seem to get the MySQL module to work properly and others seem equally frustrated.</p>
<p>In that case, is there any other DB option for Python 3 that I could consider?</p>
| 3 | 2009-10-10T08:09:24Z | 1,550,867 | <p>I know there is some Python <a href="http://www.firebirdsql.org/index.php?op=devel&sub=python" rel="nofollow">driver</a> for <a href="http://www.firebirdsql.org" rel="nofollow">Firebird</a> but I don't know if some exist for Python 3. May be you can ask in the Firebird-Python <a href="http://www.firebirdsql.org/index.php?op=lists#firebird-python" rel="nofollow">support list</a></p>
| 1 | 2009-10-11T14:49:14Z | [
"python",
"database",
"python-3.x"
] |
A database for python 3? | 1,547,365 | <p>I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.</p>
<p>Since it's a threaded server, SQLite doesn't work. It complains about threads like this:</p>
<blockquote>
<p>ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712</p>
</blockquote>
<p>Besides, they say SQLite isn't great for concurrency anyhow.</p>
<p>Now since I started working with Python 3 (and would rather continue using it) I can't seem to get the MySQL module to work properly and others seem equally frustrated.</p>
<p>In that case, is there any other DB option for Python 3 that I could consider?</p>
| 3 | 2009-10-10T08:09:24Z | 1,550,870 | <p>Surely a pragmatic option is to just use one SQLite connection per thread.</p>
| 0 | 2009-10-11T14:50:53Z | [
"python",
"database",
"python-3.x"
] |
A database for python 3? | 1,547,365 | <p>I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.</p>
<p>Since it's a threaded server, SQLite doesn't work. It complains about threads like this:</p>
<blockquote>
<p>ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712</p>
</blockquote>
<p>Besides, they say SQLite isn't great for concurrency anyhow.</p>
<p>Now since I started working with Python 3 (and would rather continue using it) I can't seem to get the MySQL module to work properly and others seem equally frustrated.</p>
<p>In that case, is there any other DB option for Python 3 that I could consider?</p>
| 3 | 2009-10-10T08:09:24Z | 10,863,434 | <p>pymongo works with Python 3 now.</p>
| 1 | 2012-06-02T15:09:33Z | [
"python",
"database",
"python-3.x"
] |
Forms in Django--cannot get past "cleaned_data" | 1,547,412 | <p>I have a form that allows users to upload text AND a file. However, I'd like to make it valid even if the user doesn't upload the file (file is optional). However, in Django, it is not allowing me to get past "clean(self)". I just want it simple--if text box, pass. If no text , return error.</p>
<pre><code>class PieceForm(forms.Form):
text = forms.CharField(max_length=600)
file = forms.FileField()
def clean(self):
cleaned_data = self.cleaned_data
text = cleaned_data.get('text')
file = cleaned_data.get('file')
return cleaned_data
</code></pre>
<p>In my views...</p>
<pre><code>form = PieceForm(request.POST, request.FILES)
if form.is_valid():
print 'It's valid!' ........this only prints if there is a file!
</code></pre>
| 2 | 2009-10-10T08:44:00Z | 1,547,457 | <p>You must set <code>required=False</code> for the fields which are optional as noted in <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#required" rel="nofollow">the documentation</a></p>
<p>In your case, the following line should do the trick:</p>
<pre><code> file = forms.FileField(required=False)
</code></pre>
| 4 | 2009-10-10T09:10:22Z | [
"python",
"django"
] |
Check if a parameter is a Python module? | 1,547,466 | <p>How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.</p>
<pre><code>>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
NameError: name 'module' is not defined
</code></pre>
<p>I can do this:</p>
<pre><code>>>> type(os)
<type 'module'>
</code></pre>
<p>But what do I compare it to? :(</p>
<p>I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:</p>
<pre><code>def gethelp(module, sstring):
# here i need to check if module is a module.
for func in listseek(dir(module), sstring):
help(module.__dict__[func])
</code></pre>
<p>Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.</p>
| 18 | 2009-10-10T09:18:38Z | 1,547,469 | <p>This seems a bit hacky, but:</p>
<pre><code>>>> import sys
>>> import os
>>> type(os) is type(sys)
True
</code></pre>
| 2 | 2009-10-10T09:20:44Z | [
"python",
"types"
] |
Check if a parameter is a Python module? | 1,547,466 | <p>How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.</p>
<pre><code>>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
NameError: name 'module' is not defined
</code></pre>
<p>I can do this:</p>
<pre><code>>>> type(os)
<type 'module'>
</code></pre>
<p>But what do I compare it to? :(</p>
<p>I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:</p>
<pre><code>def gethelp(module, sstring):
# here i need to check if module is a module.
for func in listseek(dir(module), sstring):
help(module.__dict__[func])
</code></pre>
<p>Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.</p>
| 18 | 2009-10-10T09:18:38Z | 1,547,475 | <pre><code>from types import ModuleType
isinstance(obj, ModuleType)
</code></pre>
| 37 | 2009-10-10T09:25:46Z | [
"python",
"types"
] |
Check if a parameter is a Python module? | 1,547,466 | <p>How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.</p>
<pre><code>>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
NameError: name 'module' is not defined
</code></pre>
<p>I can do this:</p>
<pre><code>>>> type(os)
<type 'module'>
</code></pre>
<p>But what do I compare it to? :(</p>
<p>I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:</p>
<pre><code>def gethelp(module, sstring):
# here i need to check if module is a module.
for func in listseek(dir(module), sstring):
help(module.__dict__[func])
</code></pre>
<p>Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.</p>
| 18 | 2009-10-10T09:18:38Z | 1,547,567 | <pre><code>>>> import inspect, os
>>> inspect.ismodule(os)
True
</code></pre>
| 20 | 2009-10-10T10:13:58Z | [
"python",
"types"
] |
How to do nested Django SELECT? | 1,547,494 | <pre><code>class Friendship(models.Model):
from_friend = models.ForeignKey(User, related_name='friend_set')
to_friend = models.ForeignKey(User, related_name='to_friend_set')
</code></pre>
<p>I'd like to SELECT all to_friends that have from_friend = a certain User.</p>
<p>Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it? </p>
<p>Thanks!</p>
| 3 | 2009-10-10T09:35:07Z | 1,547,534 | <blockquote>
<p>I'd like to <code>SELECT</code> all <code>to_friends</code> that have <code>from_friend</code> = a certain User.</p>
</blockquote>
<p>You could get all the Friendship objects for this step like so:</p>
<pre><code>friendships = Friendship.objects.filter(from_friend=some_user)
</code></pre>
<p>Then you can get all the to_friend fields into a flat list using the values_list method of a query set:</p>
<pre><code>friends = friendships.values_list("to_friend", flat=True)
</code></pre>
<p>At this point <code>friends</code> is a ValuesListQuery object that works just like a list. You can iterate over the friends and use the values in other filter() calls.</p>
| 3 | 2009-10-10T09:58:43Z | [
"python",
"mysql",
"django"
] |
How to do nested Django SELECT? | 1,547,494 | <pre><code>class Friendship(models.Model):
from_friend = models.ForeignKey(User, related_name='friend_set')
to_friend = models.ForeignKey(User, related_name='to_friend_set')
</code></pre>
<p>I'd like to SELECT all to_friends that have from_friend = a certain User.</p>
<p>Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it? </p>
<p>Thanks!</p>
| 3 | 2009-10-10T09:35:07Z | 1,549,654 | <p>As pccardune says, you get the relevant users like this:</p>
<pre><code>friendships = Friendship.objects.filter(from_friend=some_user)
</code></pre>
<p>But in fact you can pass this directly into your next query:</p>
<pre><code>second_select = Whatever.objects.filter(friend__in=friendships)
</code></pre>
| 2 | 2009-10-11T02:09:22Z | [
"python",
"mysql",
"django"
] |
How to do nested Django SELECT? | 1,547,494 | <pre><code>class Friendship(models.Model):
from_friend = models.ForeignKey(User, related_name='friend_set')
to_friend = models.ForeignKey(User, related_name='to_friend_set')
</code></pre>
<p>I'd like to SELECT all to_friends that have from_friend = a certain User.</p>
<p>Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it? </p>
<p>Thanks!</p>
| 3 | 2009-10-10T09:35:07Z | 1,549,673 | <p>This appears to return the desired results</p>
<pre><code>User.objects.filter(to_friend_set__from_friend=1)
</code></pre>
| 2 | 2009-10-11T02:24:22Z | [
"python",
"mysql",
"django"
] |
A minimalist, non-enterprisey approach for a SOAP server in Python | 1,547,520 | <p>I need to implement a small test utility which consumes extremely simple SOAP XML (HTTP POST) messages. This is a protocol which I have to support, and it's not my design decision to use SOAP (just trying to prevent those "why do you use protocol X?" answers) </p>
<p>I'd like to use stuff that's already in the basic python 2.6.x installation. What's the easiest way to do that? The sole SOAP message is really simple, I'd rather not use any enterprisey tools like WSDL class generation if possible. </p>
<p>I already implemented the same functionality earlier in Ruby with just plain HTTPServlet::AbstractServlet and REXML parser. Worked fine.</p>
<p>I thought I could a similar solution in Python with BaseHTTPServer, BaseHTTPRequestHandler and the elementree parser, but it's not obvious to me how I can read the <em>contents of my incoming SOAP POST message</em>. The documentation is not that great IMHO.</p>
| 1 | 2009-10-10T09:49:47Z | 1,547,530 | <p>You could write a WSGI function (see <a href="http://docs.python.org/library/wsgiref.html" rel="nofollow"><code>wsgiref</code></a>) and parse inside it an HTTP request body using the <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow"><code>xml.etree.ElementTree</code></a> module.</p>
<p>SOAP is basically very simple, I'm not sure that it deserves a special module. Just use a standard XML processing library you like.</p>
| 3 | 2009-10-10T09:55:24Z | [
"python",
"http",
"soap"
] |
A minimalist, non-enterprisey approach for a SOAP server in Python | 1,547,520 | <p>I need to implement a small test utility which consumes extremely simple SOAP XML (HTTP POST) messages. This is a protocol which I have to support, and it's not my design decision to use SOAP (just trying to prevent those "why do you use protocol X?" answers) </p>
<p>I'd like to use stuff that's already in the basic python 2.6.x installation. What's the easiest way to do that? The sole SOAP message is really simple, I'd rather not use any enterprisey tools like WSDL class generation if possible. </p>
<p>I already implemented the same functionality earlier in Ruby with just plain HTTPServlet::AbstractServlet and REXML parser. Worked fine.</p>
<p>I thought I could a similar solution in Python with BaseHTTPServer, BaseHTTPRequestHandler and the elementree parser, but it's not obvious to me how I can read the <em>contents of my incoming SOAP POST message</em>. The documentation is not that great IMHO.</p>
| 1 | 2009-10-10T09:49:47Z | 1,547,642 | <p>I wrote something like this in Boo, using a .Net HTTPListener, because I too had to implement someone else's defined WSDL.</p>
<p>The WSDL I was given used document/literal form (you'll need to make some adjustments to this information if your WSDL uses rpc/encoded). I wrapped the HTTPListener in a class that allowed client code to register callbacks by SOAP action, and then gave that class a Start method that would kick off the HTTPListener. You should be able to do something very similar in Python, with a getPOST() method on BaseHTTPServer to:</p>
<ul>
<li>extract the SOAP action from the HTTP
headers</li>
<li>use elementtree to extract the SOAP
header and SOAP body from the POST'ed
HTTP</li>
<li>call the defined callback for the
SOAP action, sending these extracted values</li>
<li>return the response text given by the
callback in a corresponding SOAP
envelope; if the callback raises an
exception, catch it and re-wrap it as
a SOAP fault</li>
</ul>
<p>Then you just implement a callback per SOAP action, which gets the XML content passed to it, parses this with elementtree, performs the desired action (or mock action if this is tester), and constructs the necessary response XML (I was not too proud to just create this explicitly using string interpolation, but you could use elementtree to create this by serializing a Python response object).</p>
<p>It will help if you can get some real SOAP sample messages in order to help you not tear out your hair, especially in the part where you create the necessary response XML. </p>
| 1 | 2009-10-10T10:55:40Z | [
"python",
"http",
"soap"
] |
Improvizing a drop-in replacement for the "with" statement for Python 2.4 | 1,547,526 | <p>Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4?</p>
<p>It would be a hack, but it would allow me to port my project to Python 2.4 more nicely.</p>
<p><strong>EDIT:</strong>
Removed irrelevant metaclass sketch</p>
| 6 | 2009-10-10T09:53:31Z | 1,547,559 | <p>You could (ab)use decorators to do this, I think. The following works, eg:</p>
<pre><code>def execute_with_context_manager(man):
def decorator(f):
target = man.__enter__()
exc = True
try:
try:
f(target)
except:
exc = False
if not man.__exit__(*sys.exc_info()):
raise
finally:
if exc:
man.__exit__(None, None, None)
return None
return decorator
@execute_with_context_manager(open("/etc/motd"))
def inside(motd_file):
for line in motd_file:
print line,
</code></pre>
<p>(Well, in Python 2.4 file objects don't have __enter__ and __exit__ methods, but otherwise it works)</p>
<p>The idea is you're replacing the with line in:</p>
<pre><code>with bar() as foo:
do_something_with(foo)
do_something_else_with(foo)
# etc...
</code></pre>
<p>with the decorated function "declaration" in:</p>
<pre><code>@execute_with_context_manager( bar() )
def dummyname( foo ):
do_something_with(foo)
do_something_else_with(foo)
# etc...
</code></pre>
<p>but getting the same behaviour (the do_something_... code executed). Note the decorator changes the function declaration into an <em>immediate invocation</em> which is more than a little evil.</p>
| 4 | 2009-10-10T10:11:16Z | [
"python",
"with-statement"
] |
Improvizing a drop-in replacement for the "with" statement for Python 2.4 | 1,547,526 | <p>Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4?</p>
<p>It would be a hack, but it would allow me to port my project to Python 2.4 more nicely.</p>
<p><strong>EDIT:</strong>
Removed irrelevant metaclass sketch</p>
| 6 | 2009-10-10T09:53:31Z | 1,547,565 | <p>Since you need to exit the context manager both during errors and not errors, I don't think it's possible to do a generic usecase with metaclasses, or in fact at all. You are going to need try/finally blocks for that.</p>
<p>But maybe it's possible to do something else in your case. That depends on what you use the context manager for. </p>
<p>Using <code>__del__</code> can help in some cases, like deallocating resource, but since you can't be sure it gets called, it can only be used of you need to release resources that will be released when the program exits. That also won't work if you are handling exceptions in the <code>__exit__</code> method.</p>
<p>I guess the cleanest method is to wrap the whole context management in a sort of context managing call, and extract the code block into a method. Something like this (untested code, but mostly stolen from PEP 343):</p>
<pre><code>def call_as_context_manager(mgr, function):
exit = mgr.__exit__
value = mgr.__enter__()
exc = True
try:
try:
function(value)
except:
exc = False
if not exit(*sys.exc_info()):
raise
finally:
if exc:
exit(None, None, None)
</code></pre>
| 1 | 2009-10-10T10:13:20Z | [
"python",
"with-statement"
] |
Improvizing a drop-in replacement for the "with" statement for Python 2.4 | 1,547,526 | <p>Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4?</p>
<p>It would be a hack, but it would allow me to port my project to Python 2.4 more nicely.</p>
<p><strong>EDIT:</strong>
Removed irrelevant metaclass sketch</p>
| 6 | 2009-10-10T09:53:31Z | 1,547,628 | <p>Just use try-finally.</p>
<p>Really, this may be nice as a mental exercise, but if you actually do it in code you care about you will end up with ugly, hard to maintain code.</p>
| 6 | 2009-10-10T10:47:10Z | [
"python",
"with-statement"
] |
Improvizing a drop-in replacement for the "with" statement for Python 2.4 | 1,547,526 | <p>Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4?</p>
<p>It would be a hack, but it would allow me to port my project to Python 2.4 more nicely.</p>
<p><strong>EDIT:</strong>
Removed irrelevant metaclass sketch</p>
| 6 | 2009-10-10T09:53:31Z | 1,548,883 | <p>How about this?</p>
<pre><code>def improvize_context_manager(*args, **kwargs):
assert (len(args) + len(kwargs)) == 1
if args:
context_manager = args[0]
as_ = None
else: # It's in kwargs
(as_, context_manager) = kwargs.items()[0]
def decorator(f):
exit_ = context_manager.__exit__ # Not calling it yet
enter_ = context_manager.__enter__()
exc = True
try:
try:
if as_:
f(*{as_: enter_})
else:
f()
except:
exc = False
if not exit_(*sys.exc_info()):
raise
finally:
if exc:
exit_(None, None, None)
return None
return decorator
</code></pre>
<p>Usage:</p>
<pre><code>@improvize_context_manager(lock)
def null():
do(stuff)
</code></pre>
<p>Which parallels the <code>with</code> keyword without <code>as</code>.</p>
<p>Or:</p>
<pre><code>@improvize_context_manager(my_lock=lock)
def null(my_lock):
do(stuff_with, my_lock)
</code></pre>
<p>Which parallels the <code>with</code> keyword with the <code>as</code>.</p>
| 1 | 2009-10-10T19:46:39Z | [
"python",
"with-statement"
] |
Improvizing a drop-in replacement for the "with" statement for Python 2.4 | 1,547,526 | <p>Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4?</p>
<p>It would be a hack, but it would allow me to port my project to Python 2.4 more nicely.</p>
<p><strong>EDIT:</strong>
Removed irrelevant metaclass sketch</p>
| 6 | 2009-10-10T09:53:31Z | 3,524,603 | <p>If you are OK with using def just to get a block, and decorators that immediately execute, you could use the function signature to get something more natural for the named case.</p>
<pre>
import sys
def with(func):
def decorated(body = func):
contexts = body.func_defaults
try:
exc = None, None, None
try:
for context in contexts:
context.__enter__()
body()
except:
exc = sys.exc_info()
raise
finally:
for context in reversed(contexts):
context.__exit__(*exc)
decorated()
class Context(object):
def __enter__(self):
print "Enter %s" % self
def __exit__(self, *args):
print "Exit %s(%s)" % (self, args)
x = Context()
@with
def _(it = x):
print "Body %s" % it
@with
def _(it = x):
print "Body before %s" % it
raise "Nothing"
print "Body after %s" % it
</pre>
| 1 | 2010-08-19T17:43:48Z | [
"python",
"with-statement"
] |
General printing raster and/or vector images | 1,547,621 | <p>I'm looking for some API for printing.</p>
<p>Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.).</p>
<p>What I think that would be minimum API is:</p>
<ul>
<li>printer devices list</li>
<li>printer buffer where I could send my in-memory pixmap (ex. like winXP printer tasks folder)</li>
<li>some API which would translate SI dimensions onto printer resolution, or according to previous - in memory pixmap (ex. 450x250) onto paper in appropriate resolution. </li>
</ul>
<p>What I was considering is postScript, but I've some old LPT drived laserjet which probably doesn't support *PS.</p>
<p>Currently I'm trying to find something interesting in Qt - QGraphicsView.</p>
<p><a href="http://doc.trolltech.com/4.2/qgraphicsview.html" rel="nofollow">http://doc.trolltech.com/4.2/qgraphicsview.html</a></p>
| 2 | 2009-10-10T10:43:22Z | 1,547,649 | <p>You might want to <a href="http://wiki.wxpython.org/Printing" rel="nofollow">investigate wx python for printing</a>. Learning the framework might be a bit of an overhead for you though! I've had success with that in the past, both on windows and linux.</p>
<p>I've also used <a href="http://www.reportlab.org/downloads.html" rel="nofollow">reportlab</a> to make PDFs which are pretty easy to print using the minimum of OS interaction.</p>
| 0 | 2009-10-10T10:58:03Z | [
"c++",
"python",
"c"
] |
General printing raster and/or vector images | 1,547,621 | <p>I'm looking for some API for printing.</p>
<p>Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.).</p>
<p>What I think that would be minimum API is:</p>
<ul>
<li>printer devices list</li>
<li>printer buffer where I could send my in-memory pixmap (ex. like winXP printer tasks folder)</li>
<li>some API which would translate SI dimensions onto printer resolution, or according to previous - in memory pixmap (ex. 450x250) onto paper in appropriate resolution. </li>
</ul>
<p>What I was considering is postScript, but I've some old LPT drived laserjet which probably doesn't support *PS.</p>
<p>Currently I'm trying to find something interesting in Qt - QGraphicsView.</p>
<p><a href="http://doc.trolltech.com/4.2/qgraphicsview.html" rel="nofollow">http://doc.trolltech.com/4.2/qgraphicsview.html</a></p>
| 2 | 2009-10-10T10:43:22Z | 1,547,655 | <p>I would use <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> to create a BMP file, and then just use the standard OS services to print that file. PIL will accept data in either raster or vector form.</p>
| 0 | 2009-10-10T10:59:18Z | [
"c++",
"python",
"c"
] |
General printing raster and/or vector images | 1,547,621 | <p>I'm looking for some API for printing.</p>
<p>Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.).</p>
<p>What I think that would be minimum API is:</p>
<ul>
<li>printer devices list</li>
<li>printer buffer where I could send my in-memory pixmap (ex. like winXP printer tasks folder)</li>
<li>some API which would translate SI dimensions onto printer resolution, or according to previous - in memory pixmap (ex. 450x250) onto paper in appropriate resolution. </li>
</ul>
<p>What I was considering is postScript, but I've some old LPT drived laserjet which probably doesn't support *PS.</p>
<p>Currently I'm trying to find something interesting in Qt - QGraphicsView.</p>
<p><a href="http://doc.trolltech.com/4.2/qgraphicsview.html" rel="nofollow">http://doc.trolltech.com/4.2/qgraphicsview.html</a></p>
| 2 | 2009-10-10T10:43:22Z | 1,547,656 | <p>Well you got close, look at <a href="http://doc.trolltech.com/4.5/printing.html" rel="nofollow">Printing in Qt</a>. There is the <a href="http://doc.trolltech.com/4.5/qprinter.html" rel="nofollow">QPrinter</a> class that implements some of what you are looking for. It is implmenetent as a <code>QPaintDevice</code>. This means that any widget that can render itself on the screen can be printed. This also mean you don't need to render to a bitmap to print, you can use Qt widgets or drawing functions for printing</p>
<p>On a side note, check the version number of the Qt documentation, the last release of Qt is 4.5, 4.6 is in beta. </p>
| 0 | 2009-10-10T10:59:31Z | [
"c++",
"python",
"c"
] |
How to sort this list in Python? | 1,547,733 | <p>[ {'time':33}, {'time':11}, {'time':66} ]</p>
<p>How to sort by the "time" element, DESC.</p>
| 5 | 2009-10-10T11:37:47Z | 1,547,739 | <p>Like this:</p>
<pre><code>from operator import itemgetter
l = sorted(l, key=itemgetter('time'), reverse=True)
</code></pre>
<p>Or:</p>
<pre><code>l = sorted(l, key=lambda a: a['time'], reverse=True)
</code></pre>
<p>output: </p>
<pre><code>[{'time': 66}, {'time': 33}, {'time': 11}]
</code></pre>
<p>If you don't want to keep the original order you can use <code>your_list.sort</code> which modifies the original list instead of creating a copy like <code>sorted(your_list)</code></p>
<pre><code>l.sort(key=lambda a: a['time'], reverse=True)
</code></pre>
| 27 | 2009-10-10T11:41:33Z | [
"python",
"list"
] |
Mini-languages in Python | 1,547,782 | <p>I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.</p>
<p>Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python? </p>
<p>I'm not going to give specific details of what I'm after because at the moment I'm just investigating how easy this whole field is in Python.</p>
<p>Thanks for your input!</p>
| 34 | 2009-10-10T12:06:18Z | 1,547,788 | <p>I have limited but positive experience with <a href="http://www.dabeaz.com/ply/">PLY</a> (Python Lex-Yacc). It combines <a href="http://dinosaur.compilertools.net/">Lex and Yacc</a> functionality in a single Python class. You may want to check it out.</p>
<p>Fellow Stackoverflow'er <a href="http://stackoverflow.com/users/14343/ned-batchelder">Ned Batchelder</a> has a <a href="http://nedbatchelder.com/text/python-parsers.html">nice overview</a> of available tools on his website. There's also an overview on the <a href="http://wiki.python.org/moin/LanguageParsing">Python website</a> itself.</p>
| 16 | 2009-10-10T12:12:23Z | [
"python",
"dsl"
] |
Mini-languages in Python | 1,547,782 | <p>I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.</p>
<p>Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python? </p>
<p>I'm not going to give specific details of what I'm after because at the moment I'm just investigating how easy this whole field is in Python.</p>
<p>Thanks for your input!</p>
| 34 | 2009-10-10T12:06:18Z | 1,547,789 | <p>In order to be productive, I'd always use a parser generator like <a href="http://pypi.python.org/pypi/CocoPy/" rel="nofollow">CocoPy</a> (<a href="http://www.ssw.uni-linz.ac.at/Coco/Tutorial/" rel="nofollow">Tutorial</a>) to have your grammar transformed into a (correct) parser (unless you want to implement the parser manually for the sake of learning). </p>
<p>The rest is writing the actual interpreter/compiler (Create stack-based byte code or memory AST to be interpreted and then evaluate it).</p>
| 2 | 2009-10-10T12:13:22Z | [
"python",
"dsl"
] |
Mini-languages in Python | 1,547,782 | <p>I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.</p>
<p>Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python? </p>
<p>I'm not going to give specific details of what I'm after because at the moment I'm just investigating how easy this whole field is in Python.</p>
<p>Thanks for your input!</p>
| 34 | 2009-10-10T12:06:18Z | 1,547,791 | <p>Python is such a wonderfully simple and extensible language that I'd suggest merely creating a comprehensive python module, and coding against that.</p>
<p>I see that while I typed up the above, <a href="http://www.dabeaz.com/ply/" rel="nofollow"><code>PLY</code></a> has already been mentioned.</p>
| 3 | 2009-10-10T12:14:43Z | [
"python",
"dsl"
] |
Mini-languages in Python | 1,547,782 | <p>I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.</p>
<p>Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python? </p>
<p>I'm not going to give specific details of what I'm after because at the moment I'm just investigating how easy this whole field is in Python.</p>
<p>Thanks for your input!</p>
| 34 | 2009-10-10T12:06:18Z | 1,548,368 | <p><a href="http://pyparsing.wikispaces.com/">Pyparsing</a> is handy for writing "little languages". I gave a <a href="http://www.ptmcg.com/geo/python/confs/pyCon2006%5Fpres2.html">presentation at PyCon'06</a> on writing a simple adventure game engine, in which the language being parsed and interpreted was the game command set ("inventory", "take sword", "drop book", etc.). (Source code <a href="http://www.ptmcg.com/geo/python/confs/adventureEngine.py.txt">here</a>.)</p>
<p>You can also find links to other pyparsing articles at the pyparsing wiki <a href="http://pyparsing.wikispaces.com/Publications">Publications page</a>.</p>
| 29 | 2009-10-10T16:20:32Z | [
"python",
"dsl"
] |
Mini-languages in Python | 1,547,782 | <p>I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.</p>
<p>Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python? </p>
<p>I'm not going to give specific details of what I'm after because at the moment I'm just investigating how easy this whole field is in Python.</p>
<p>Thanks for your input!</p>
| 34 | 2009-10-10T12:06:18Z | 1,548,393 | <p>I would recommend <a href="http://code.google.com/p/funcparserlib/"><code>funcparserlib</code></a>. It was written especially for parsing little languages and DSLs and it is faster and smaller than <code>pyparsing</code> (see stats on its homepage). Minimalists and functional programmers should like <code>funcparserlib</code>.</p>
<p>Edit: By the way, I'm the author of this library, so my opinion may be biased.</p>
| 14 | 2009-10-10T16:29:48Z | [
"python",
"dsl"
] |
Mini-languages in Python | 1,547,782 | <p>I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.</p>
<p>Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python? </p>
<p>I'm not going to give specific details of what I'm after because at the moment I'm just investigating how easy this whole field is in Python.</p>
<p>Thanks for your input!</p>
| 34 | 2009-10-10T12:06:18Z | 39,859,385 | <p>If you ask me this now, I would try the textx library for python. You can very easily create a dsl in that with python! Advantages are that it creates an AST for you, and lexing and parsing is combined.</p>
<p><a href="http://igordejanovic.net/textX/" rel="nofollow">http://igordejanovic.net/textX/</a></p>
| 1 | 2016-10-04T18:32:21Z | [
"python",
"dsl"
] |
Crazy python behaviour | 1,547,856 | <p>I have a little piece of python code in the server script for my website which looks a little bit like this:</p>
<pre><code>console.append([str(x) for x in data])
console.append(str(max(data)))
</code></pre>
<p>quite simple, you might think, however the result it's outputting is this:</p>
<pre><code>['3', '12', '3']
3
</code></pre>
<p>for some reason python thinks 3 is the max of [3,12,3]!</p>
<p>So am I doing something wrong? Or this is misbehaviour on the part of python?</p>
| 0 | 2009-10-10T12:45:38Z | 1,547,861 | <p>I know very little Python, but you are taking the max of strings, which means that <code>'3..'</code> is greater than <code>'1..'</code>.</p>
| 1 | 2009-10-10T12:49:46Z | [
"python",
"max"
] |
Crazy python behaviour | 1,547,856 | <p>I have a little piece of python code in the server script for my website which looks a little bit like this:</p>
<pre><code>console.append([str(x) for x in data])
console.append(str(max(data)))
</code></pre>
<p>quite simple, you might think, however the result it's outputting is this:</p>
<pre><code>['3', '12', '3']
3
</code></pre>
<p>for some reason python thinks 3 is the max of [3,12,3]!</p>
<p>So am I doing something wrong? Or this is misbehaviour on the part of python?</p>
| 0 | 2009-10-10T12:45:38Z | 1,547,868 | <p>Because the character <code>'3'</code> is higher in the ASCII table than <code>'1'</code>. You are comparing strings, not numbers. If you want to compare the numerically, you need to convert them to numbers. One way is <code>max(data, key=int)</code>, but you might want to actually store numbers in the list.</p>
| 8 | 2009-10-10T12:51:04Z | [
"python",
"max"
] |
How do I parse indents and dedents with pyparsing? | 1,547,944 | <p>Here is a subset of the Python grammar:</p>
<pre><code>single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: pass_stmt
pass_stmt: 'pass'
compound_stmt: if_stmt
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
</code></pre>
<p>(You can read the full grammar in the Python SVN repository: <a href="http://svn.python.org/view/%2Acheckout%2A/python/tags/r261/Grammar/Grammar">http://svn.python.org/.../Grammar</a>)</p>
<p>I am trying to use this grammar to generate a parser for Python, in Python. What I am having trouble with is how to express the <code>INDENT</code> and <code>DEDENT</code> tokens as pyparsing objects.</p>
<p>Here is how I have implemented the other terminals:</p>
<pre><code>import pyparsing as p
string_start = (p.Literal('"""') | "'''" | '"' | "'")
string_token = ('\\' + p.CharsNotIn("",exact=1) | p.CharsNotIn('\\',exact=1))
string_end = p.matchPreviousExpr(string_start)
terminals = {
'NEWLINE': p.Literal('\n').setWhitespaceChars(' \t')
.setName('NEWLINE').setParseAction(terminal_action('NEWLINE')),
'ENDMARKER': p.stringEnd.copy().setWhitespaceChars(' \t')
.setName('ENDMARKER').setParseAction(terminal_action('ENDMARKER')),
'NAME': (p.Word(p.alphas + "_", p.alphanums + "_", asKeyword=True))
.setName('NAME').setParseAction(terminal_action('NAME')),
'NUMBER': p.Combine(
p.Word(p.nums) + p.CaselessLiteral("l") |
(p.Word(p.nums) + p.Optional("." + p.Optional(p.Word(p.nums))) | "." + p.Word(p.nums)) +
p.Optional(p.CaselessLiteral("e") + p.Optional(p.Literal("+") | "-") + p.Word(p.nums)) +
p.Optional(p.CaselessLiteral("j"))
).setName('NUMBER').setParseAction(terminal_action('NUMBER')),
'STRING': p.Combine(
p.Optional(p.CaselessLiteral('u')) +
p.Optional(p.CaselessLiteral('r')) +
string_start + p.ZeroOrMore(~string_end + string_token) + string_end
).setName('STRING').setParseAction(terminal_action('STRING')),
# I can't find a good way of parsing indents/dedents.
# The Grammar just has the tokens NEWLINE, INDENT and DEDENT scattered accross the rules.
# A single NEWLINE would be translated to NEWLINE + PEER (from pyparsing.indentedBlock()), unless followed by INDENT or DEDENT
# That NEWLINE and IN/DEDENT could be spit across rule boundaries. (see the 'suite' rule)
'INDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('INDENT'),
'DEDENT': (p.LineStart() + p.Optional(p.Word(' '))).setName('DEDENT')
}
</code></pre>
<p><code>terminal_action</code> is a function that returns the corresponding parsing action, depending on its arguments.</p>
<p>I am aware of the <code>pyparsing.indentedBlock</code> helper function, but I am can't figure out how to adopt that to a grammar without the <code>PEER</code> token.</p>
<p>(Look at the <a href="http://crpppc19.epfl.ch/doc/python-pyparsing/htmldoc/pyparsing.pyparsing-pysrc.html#indentedBlock">pyparsing souce code</a> to see what I am talking about)</p>
<p>You can see my full source code here: <a href="http://pastebin.ca/1609860">http://pastebin.ca/1609860</a></p>
| 7 | 2009-10-10T13:27:37Z | 1,548,219 | <p>There are a couple of examples on the pyparsing wiki <a href="http://pyparsing.wikispaces.com/Examples">Examples page</a> that could give you some insights:</p>
<ul>
<li><a href="http://pyparsing.wikispaces.com/file/view/pythonGrammarParser.py">pythonGrammarParser.py</a></li>
<li><a href="http://pyparsing.wikispaces.com/file/view/indentedGrammarExample.py">indentedGrammarExample.py</a></li>
</ul>
<p>To use pyparsing's <code>indentedBlock</code>, I think you would define <code>suite</code> as:</p>
<pre><code>indentstack = [1]
suite = indentedBlock(stmt, indentstack, True)
</code></pre>
<p>Note that <code>indentedGrammarExample.py</code> pre-dates the inclusion of <code>indentedBlock</code> in pyparsing, so does its own implemention of indent parsing.</p>
| 9 | 2009-10-10T15:24:35Z | [
"python",
"indentation",
"parser-generator",
"pyparsing"
] |
Traffic shaping under Linux | 1,548,086 | <p>Where can I learn about controlling/interrogating the network interface under Linux? I'd like to get specific application upload/download speeds, and enforce a speed limit for a specific application. </p>
<p>I'd particularly like information that can help me write a traffic shaping application using Python.</p>
| 4 | 2009-10-10T14:24:27Z | 1,548,211 | <p>You want the iproute2 suite, in which you use the <a href="http://www.linuxfoundation.org/en/Net:Iproute2_examples" rel="nofollow">tc</a> command. tc commands look like</p>
<pre><code>tc class add dev eth2 parent 1: classid 1:1 htb rate 100Mbit ceil 100Mbit quantum 1600
</code></pre>
<p>Here's <a href="http://freenet.mcnabhosting.com/python/pyshaper/" rel="nofollow">an existing Python traffic-shaping application</a> that uses iproute2.</p>
| 5 | 2009-10-10T15:21:46Z | [
"python",
"linux",
"ubuntu",
"trafficshaping"
] |
Traffic shaping under Linux | 1,548,086 | <p>Where can I learn about controlling/interrogating the network interface under Linux? I'd like to get specific application upload/download speeds, and enforce a speed limit for a specific application. </p>
<p>I'd particularly like information that can help me write a traffic shaping application using Python.</p>
| 4 | 2009-10-10T14:24:27Z | 1,548,244 | <p>It is actually quite hard shaping per application using the linux kernel tools, unless the application uses specific ip addresses and/or ports you can match on.</p>
<p>Assuming that is the case then you'll need to read up on <code>iptables</code> and in particular fwmarks. You'll also need to read up on <code>tc</code>. In combination those two tools can do what you want. The <a href="http://lartc.org/">Linux Advanced Routing & Traffic Control</a> is a good place to start.</p>
<p>Assuming your application doesn't use a predictable set of ports/ip addresses then you'll need to use a userspace shaper like <a href="http://monkey.org/~marius/pages/?page=trickle">Trickle</a>. This inserts itself between the application and the kernel and shapes the traffic for that application in userspace.</p>
<p>I don't think there are any direct python bindings for any of those tools, but it would be simple to script them using python and just calling the executables directly.</p>
| 6 | 2009-10-10T15:34:28Z | [
"python",
"linux",
"ubuntu",
"trafficshaping"
] |
Traffic shaping under Linux | 1,548,086 | <p>Where can I learn about controlling/interrogating the network interface under Linux? I'd like to get specific application upload/download speeds, and enforce a speed limit for a specific application. </p>
<p>I'd particularly like information that can help me write a traffic shaping application using Python.</p>
| 4 | 2009-10-10T14:24:27Z | 1,548,761 | <p>Is there any reason you wish to use python? As mentioned, it will likely only hand-off to already developed tools for this purpose. However, if you look around, you can find things such as <code>Click! modular router</code>, <code>XORP</code>, and others that provide a drop-in for things you want to do - not to mention all the suggestions already provided (such as <code>iptables</code> and <code>tc</code>)</p>
| 0 | 2009-10-10T18:49:29Z | [
"python",
"linux",
"ubuntu",
"trafficshaping"
] |
Python library for syntax highlighting | 1,548,276 | <p>Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc.</p>
| 2 | 2009-10-10T15:48:40Z | 1,548,292 | <p>I've always heard <a href="http://pygments.org/" rel="nofollow">pygments</a> as the module for syntax highlighting. I have never used it myself, tho.</p>
| 2 | 2009-10-10T15:53:58Z | [
"python",
"syntax-highlighting",
"pygments"
] |
Python library for syntax highlighting | 1,548,276 | <p>Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc.</p>
| 2 | 2009-10-10T15:48:40Z | 1,548,295 | <p>I think <a href="http://pygments.org/">pygments</a> is the greatest choice. It supports a large number of languages and it's very mature.</p>
| 8 | 2009-10-10T15:54:19Z | [
"python",
"syntax-highlighting",
"pygments"
] |
Backporting float("inf") to Python 2.4 and 2.5 | 1,548,279 | <p>I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used <code>float("inf")</code>, and now I find it is unavailable on Python 2.5. Is there a backport of it?</p>
| 2 | 2009-10-10T15:49:11Z | 1,548,287 | <p>Spelling it either the long way or the short way works fine for me:</p>
<pre><code>$ python2.4 -c "print float('inf')+200"
inf
$ python2.5 -c "print float('inf')+200"
inf
$ python2.5 -c "print float('infinity')+200"
inf
$ python2.4 -c "print float('infinity')+200"
inf
</code></pre>
<p>The <code>-c</code> flag means "execute the following arguments as a Python command."</p>
<p><a href="http://www.python.org/dev/peps/pep-0754/" rel="nofollow">PEP754</a> (which was rejected) does mention your issue about special IEEE-754 values. It suggests using something like <code>1e300000</code> to generate a floating point overflow and create <code>inf</code>, but it does note that this is ugly and not guaranteed to be portable.</p>
| 4 | 2009-10-10T15:52:12Z | [
"python",
"infinity",
"backport"
] |
Backporting float("inf") to Python 2.4 and 2.5 | 1,548,279 | <p>I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used <code>float("inf")</code>, and now I find it is unavailable on Python 2.5. Is there a backport of it?</p>
| 2 | 2009-10-10T15:49:11Z | 1,548,409 | <p>You should be able to fake it up by giving Python a sufficiently large floating point constant instead. For instance:</p>
<pre><code>>>> 1e100000
inf
>>> float('inf') == 1e1000000
True
>>> float('inf') == 2e1000000
True
</code></pre>
| 2 | 2009-10-10T16:36:17Z | [
"python",
"infinity",
"backport"
] |
Backporting float("inf") to Python 2.4 and 2.5 | 1,548,279 | <p>I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used <code>float("inf")</code>, and now I find it is unavailable on Python 2.5. Is there a backport of it?</p>
| 2 | 2009-10-10T15:49:11Z | 5,131,423 | <p>The <a href="http://docs.python.org/library/decimal.html" rel="nofollow">decimal</a> module is available since Python 2.4 and supports positive or negative infinite decimals. It does not always behave like a float (eg. adding a decimal and a float is not supported) but does the right thing for comparison, which was good enough for me.</p>
<pre><code>>>> decimal.Decimal('Infinity') > 1e300
True
</code></pre>
| 1 | 2011-02-27T04:20:46Z | [
"python",
"infinity",
"backport"
] |
Backporting float("inf") to Python 2.4 and 2.5 | 1,548,279 | <p>I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used <code>float("inf")</code>, and now I find it is unavailable on Python 2.5. Is there a backport of it?</p>
| 2 | 2009-10-10T15:49:11Z | 5,141,374 | <p>I created a backport, tested on Python 2.5+, can probably be easily made to work on Python 2.4:</p>
<p><a href="https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/infinity.py" rel="nofollow">https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/infinity.py</a></p>
| 0 | 2011-02-28T11:30:30Z | [
"python",
"infinity",
"backport"
] |
Backporting float("inf") to Python 2.4 and 2.5 | 1,548,279 | <p>I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used <code>float("inf")</code>, and now I find it is unavailable on Python 2.5. Is there a backport of it?</p>
| 2 | 2009-10-10T15:49:11Z | 9,093,004 | <p>Borrowing NumPy for a few lines:</p>
<pre><code>import numpy as np
inf = float(np.inf)
</code></pre>
<p>Here, <code>inf</code> is a <a href="http://docs.python.org/release/2.5/lib/typesnumeric.html" rel="nofollow">regular python <code>float</code></a>, so you don't need to bother with NumPy any further.</p>
| 0 | 2012-02-01T08:46:56Z | [
"python",
"infinity",
"backport"
] |
Python way to do crc32b | 1,548,366 | <p>As i posted as title, there is a way to use the crc32b hash on python natively or through a library (i.e. chilkat)?</p>
<p>My intention is to "translate" a program from php to python, so output should be same as in php:</p>
<p>$hashedData= hash('crc32b',$data);</p>
<p>-> Edit: in a win32 system</p>
<p>Thanks to all ;)</p>
| 0 | 2009-10-10T16:20:06Z | 1,548,390 | <p><a href="http://labix.org/python-mhash" rel="nofollow">python-mhash</a> supplies many hashing functions including crc32b.</p>
| 1 | 2009-10-10T16:29:32Z | [
"python",
"hash",
"crc"
] |
Self contained classes with Qt | 1,548,370 | <p>I've been trying to make my classes completely self contained, but I'm having some problems, which are probably coming from my missing something that everybody else knew first off...</p>
<p>Anyway, take this example:</p>
<pre><code>class Main_Window (QtGui.QMainWindow):
def __init__ (self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_bookingSystemMain()
self.ui.setupUi(self)
# Connect slots
QtCore.QObject.connect(self.ui.submitRecord, QtCore.SIGNAL("clicked()"), self.__clickSubmitRecord)
QtCore.QObject.connect(self.ui.btnListBookings, QtCore.SIGNAL("clicked()"), self.__show_list)
def __clickSubmitRecord (self):
global bookings
name = self.ui.edtName.text()
event = str(self.ui.comEvent.currentText())
amount = self.ui.spinBox.value()
if name == '':
QtGui.QMessageBox.warning(self, "Error", "Please enter a name!")
elif amount == 0:
QtGui.QMessageBox.warning(self, "Error", "You can't reserve 0 tickets!")
elif event == '':
QtGui.QMessageBox.warning(self, "Error", "Please choose an event!")
else:
bookings.append(Booking(name, event, amount))
QtGui.QMessageBox.information(self, "Booking added", "Your booking for " + str(amount) + " ticket(s) to see " + event + " in the name of " + name + " was sucessful.")
self.__clear_widgets()
def __clear_widgets (self):
self.ui.edtName.clear()
self.ui.comEvent.setCurrentIndex(-1)
self.ui.spinBox.setValue(0)
def __show_list (self):
listdialog = List_Window(self)
listdialog.show()
</code></pre>
<p>Which implements a UI described in another module. The clickSubmitRecord() method uses the global 'booking' list and adds to it - now surely this class shouldn't have anything to do with anything other than that UI?</p>
<p>How would I implement this in a good ood way? As I said I'm probably missing some kind of technique or obvious design feature...</p>
<p>Thanks!</p>
| 0 | 2009-10-10T16:21:02Z | 1,548,447 | <p>I don't know Python so I can't give a good example here, but what I would probably do with Qt in C++ is define a signal of "bookingAdded" to your window object, and have one of your external objects (probably whichever invokes the UI) connect a slot to this signal, and then in your clickSubmitRecord you fire this signal and the new booking data is passed with the signal to your external object. </p>
<p>Then your UI object doesn't need to know about anything external, and all your external objects need to know about the UI is the signal that it exposes.</p>
<p>This can also help with thread safety if you use a queued connection to the signal.</p>
| 1 | 2009-10-10T16:48:08Z | [
"python",
"oop"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 1,548,501 | <p>HTML Generation is usually done with one of the infinite amounts of HTML templating languages available for Python. Personally I like <a href="http://debris.demon.nl/templess.txt" rel="nofollow">Templess</a>, but <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a> is probably the most popular. There are infinite amounts of them, there is a <a href="http://wiki.python.org/moin/Templating" rel="nofollow">list</a> which is highly likely to be incomplete.</p>
<p>Otherwise you might want to use <a href="http://lxml.de/" rel="nofollow">lxml</a>, where you can generate it in a more programmatically XML-ish way. Although I have a hard time seeing the benefit.</p>
| 5 | 2009-10-10T17:13:40Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 1,548,514 | <p>If you want programmatic generation rather than templating, Karrigell's <a href="http://karrigell.sourceforge.net/en/htmltags.html" rel="nofollow">HTMLTags</a> module is one possibility; it can include e.g. the <code>class</code> attribute (which would be a reserved word in Python) by the trick of uppercasing its initial, i.e., quoting the doc URL I just gave:</p>
<blockquote>
<p>Attributes with the same name as
Python keywords (class, type) must be
capitalized :</p>
<pre><code>print DIV('bar', Class="title") ==> <DIV class="title">bar</DIV>
</code></pre>
</blockquote>
| 6 | 2009-10-10T17:20:25Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 1,548,597 | <p>There's the venerable HTMLGen by Robin Friedrich, which is hard to find but still available <a href="http://www.python.org/ftp/python/contrib-09-Dec-1999/Network/HTMLgen.tar.gz">here</a> (dated 2001, but HTML hasn't changed much since then ;-). There's also <a href="http://www.livinglogic.de/Python/xist/">xist</a>. Of course nowadays HTML generation, as Lennart points out, is generally better done using templating systems such as <a href="http://jinja.pocoo.org/2/">Jinja</a> or <a href="http://www.makotemplates.org/">Mako</a>.</p>
| 5 | 2009-10-10T17:48:38Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 1,633,568 | <p>Actually you can add any attribute such as id and class to objects in HTML.py (<a href="http://www.decalage.info/python/html" rel="nofollow">http://www.decalage.info/python/html</a>). </p>
<p>attribs is an optional parameter of Table, TableRow and TableCell classes. It is a dictionary of additional attributes you would like to set. For example, the following code sets id and class for a table:</p>
<pre><code>import HTML
table_data = [
['Last name', 'First name', 'Age'],
['Smith', 'John', 30],
['Carpenter', 'Jack', 47],
['Johnson', 'Paul', 62],
]
htmlcode = HTML.table(table_data,
attribs={'id':'table1', 'class':'myclass'})
print htmlcode
</code></pre>
<p>The same parameter can be used with TableRow and TableCell objects to format rows and cells. It does not exist for columns yet, but should be easy to implement if needed.</p>
| 2 | 2009-10-27T20:49:03Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 2,612,236 | <p>I have made a simple module for doing this. It works and has the same idea as HTML.py. However its a bit different and maybe more customizable? It is very lightweight. The project is called HTMLpy (pronounced HTML pie). You can see more information at <a href="http://patx.me/htmlpy" rel="nofollow">http://patx.me/htmlpy</a>.</p>
| 0 | 2010-04-10T04:18:16Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 2,612,631 | <p>You might be interested in some of the Python HAML implementations. HAML is like HTML shorthand and only takes a few minutes to learn. There's a CSS version called SASS too.</p>
<p><a href="http://haml.hamptoncatlin.com/" rel="nofollow">http://haml.hamptoncatlin.com/</a></p>
<p>"<a href="http://stackoverflow.com/questions/519671/is-there-a-haml-implementation-for-use-with-python-and-django">Is there a HAML implementation for use with Python and Django</a>" talks about Python and HAML a bit more.</p>
<p>I'm using HAML as much as possible when I'm programming in Ruby. And, as a footnote, there's also been some work getting modules for Perl which work with the nice MVC Mojolicious:</p>
<p><a href="http://metacpan.org/pod/Text%3a%3aHaml" rel="nofollow">http://metacpan.org/pod/Text::Haml</a></p>
| 0 | 2010-04-10T07:35:22Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 6,715,824 | <p>This is one ultra-simple HTML generator I have written. I use it build-time to generate html. If one is generating html pages run-time then there are better options available</p>
<p>Here is the link</p>
<p><a href="http://pypi.python.org/pypi/sphc" rel="nofollow">http://pypi.python.org/pypi/sphc</a></p>
<p>And a quick example</p>
<pre><code>>> import sphw
>> tf = sphw.TagFactory()
>>> div = tf.DIV("Some Text here.", Class='content', id='foo')
>>> print(div)
<DIV Class="content", id="foo">Some Text here.</DIV>
</code></pre>
| 3 | 2011-07-16T06:38:49Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 25,540,947 | <p><a href="https://github.com/Knio/dominate" rel="nofollow">Dominate</a> is an HTML generation library that lets you easily create tags. In dominate, python reserved words are prefixed with an underscore, so it would look like this:</p>
<pre><code>from dominate.tags import *
t = div(table(_id="the_table"), _class="tbl")
print(t)
<div class="tbl">
<table id="the_table"></table>
</div>
</code></pre>
<p>Disclaimer: I am the author of dominate</p>
| 1 | 2014-08-28T04:51:45Z | [
"python",
"html",
"generator"
] |
python html generator | 1,548,474 | <p>I am looking for an easily implemented html generator for python. I found this one </p>
<pre><code>http://www.decalage.info/python/html
</code></pre>
<p>but there is no way to add css elements (id, class) for table.</p>
<p>thx</p>
| 15 | 2009-10-10T16:56:50Z | 37,395,547 | <p>Like the majority of the other posters - I too have written my own HTML generator. Mine is not a module though, it is a single function:</p>
<pre><code>self_closing = ["area", "base", "br", "col", "command", "embed", "hr", "img",
"input", "keygen", "link", "meta", "param", "source", "track",
"wbr"]
def tag(kind, *args, **kwargs):
"""Generic tag-producing function."""
kind = kind.lower()
result = list()
result.append("<{}".format(kind))
for key, val in kwargs.items():
if key in ('kind', '_type'):
key = 'type'
elif key in ('klass', 'cls'):
key = 'class'
result.append(" {}=\"{}\"".format(key, val))
if kind in self_closing:
result.append(" />")
else:
result.append(">{}</{}>\n".format("".join(args), kind))
return "".join(result)
</code></pre>
<p>It is meant to be used with <code>functools.partial</code> to build tag types, for example:</p>
<pre><code># Misc simple tags
style = partial(tag, 'style')
div = partial(tag, 'div')
span = partial(tag, 'span')
# Form related tags
label = partial(tag, 'label')
textbox = partial(tag, 'input', _type='text')
button = partial(tag, 'button', _type='button')
</code></pre>
<p>It is by no means a complete solution, and probably has plenty of room for improvement, but it is a quick and easy to understand solution IMO.</p>
<p>I wrote a <a href="http://kitsu.github.io/2016/05/18/functional-html/" rel="nofollow">rambling explanatory blog post</a> about it the other day too.</p>
| 0 | 2016-05-23T15:58:48Z | [
"python",
"html",
"generator"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,631 | <p><a href="http://www.diveintopython.net/" rel="nofollow">Dive into Python</a> is a good start. I wouldn't recommend to someone with no programming experience, but if you have coded in another language before, it will help you learn python idioms quickly.</p>
| 5 | 2009-10-10T17:59:16Z | [
"python"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,641 | <p>I started Python over a year ago too, also C++ background. </p>
<p>I've learned that everything is simpler in Python, you don't need to worry so much if you're doing it right, you probably are. Most of the things came natural.</p>
<p>I can't say I've read a book or anything, I usually pested the guys in #python on freenode a lot and looked at lots of other great code out there.</p>
<p>Good luck :)</p>
| 0 | 2009-10-10T18:03:05Z | [
"python"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,642 | <p>I second <a href="http://www.diveintopython.net/" rel="nofollow">Dive in to Python</a> as a resource. As for the main function, there isn't one. The "main" function is what you write in the script you run. </p>
<p>So a helloworld.py looks like this:</p>
<pre><code>print "Hello World"
</code></pre>
<p>and you run it with</p>
<pre><code>python helloworld.py
</code></pre>
<p>That's it!</p>
| 0 | 2009-10-10T18:03:10Z | [
"python"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,644 | <p>When you run a script through the Python interpreter (or import that script from another script), <strong>it actually executes all the code from beginning to end</strong> -- in <em>that</em> sense, <strong>there is no "entry point" to a Python script</strong>.</p>
<p>So to work around this, Python automatically creates a <code>__name__</code> variable and fills it with the value <code>"__main__"</code> when you are running a script by itself (as opposed to something else importing that script). That's why you'll see many scripts like:</p>
<pre><code>def foo():
print "Hello!"
if __name__ == "__main__":
foo()
</code></pre>
<p>where all the function/class definitions are at the top, and there is a similar if-statement as the last thing in the script. You are guaranteed that Python will start executing the script from top-to-bottom, so it will read all of your definitions there. If you wanted, you could intermingle actual functional code inside all the function definitions.</p>
<p>If this script was named <code>bar.py</code>, you could do <code>python bar.py</code> at the command line and you would see the script print out <code>"Hello!"</code>.</p>
<p>On the other hand, if you did <code>import bar</code> from another Python script, nothing would print out until you did <code>bar.foo()</code>, because <code>__name__</code> was no longer <code>"__main__"</code> and the if-statement failed, thus <code>foo</code> was never executed.</p>
| 11 | 2009-10-10T18:04:08Z | [
"python"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,654 | <p>If you are quite familiar with several languages like C++ and Java, you may find it easy to follow the official <a href="http://docs.python.org/tutorial/" rel="nofollow">Python Tutorial</a>. It is written in a classical language description bottom-up style from the lexical structure and syntax to more advanced concepts.</p>
<p>The already mentioned <a href="http://www.diveintopython.net/" rel="nofollow">Dive Into Python</a> takes a top-down approach in learning languages starting from a complete program that is obscure for a beginner and diving into its details.</p>
| 1 | 2009-10-10T18:09:01Z | [
"python"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,801 | <p>The pithiest comment I guess is that the entry point is the 1st line of your script that is not a function or a class. You don't necessarily need to use the if hack unless you want to and your script is meant to be imported.</p>
| 0 | 2009-10-10T19:05:08Z | [
"python"
] |
Python for C++ or Java Programmer | 1,548,620 | <p>I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.</p>
<p>OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.</p>
<p>Thanks to all</p>
| 4 | 2009-10-10T17:56:09Z | 1,548,871 | <p>Excellent answer, but none points out what I think is one key insight for programmers coming to Python with background in other languages such as Java or C++: <code>import</code>, <code>def</code> and <code>class</code> are not "instructions to the compiler", "declarations", or other kind of magical incantations: they're executable statements like any other. For example, the <code>def</code> statement:</p>
<pre><code>def f(x): return x + 23
</code></pre>
<p>is almost exactly equivalent to the assignment statement:</p>
<pre><code>f = lambda x: x + 23
</code></pre>
<p>(stylistically the <code>def</code> is preferable as it makes <code>f.__name__</code> meaningful -- that's the "almost" part; <code>lambda</code> is rather limited and should only ever be used when you're really keen to make an <em>anonymous</em> function rather than a normal named one). Similarly,</p>
<pre><code>class X(object): zap = 23
</code></pre>
<p>is equivalent to the assignment:</p>
<pre><code>X = type('X', (), {'zap': 23})
</code></pre>
<p>(again, stylistically, <code>class</code> is preferable, afford more generality, like <code>def</code> it allows decoration, etc, etc; the point I'm making is that there is <em>semantic</em> equivalence here).</p>
<p>So, when you run a <code>.py</code> file, or import it for the first time in a program's run, Python executes its top-level statements one after the other -- in normal good Python style, most will be assignments, <code>def</code>, <code>class</code>, or <code>import</code>, but at least one will be a call (normally to a function) to execute that function's <em>body</em> of code (<code>def</code>, like <code>lambda</code>, just <em>compiles</em> that code; the compiled code object only executes when the function or lambda is <em>called</em>). Other answers have already suggested practical considerations such as testing <code>__name__</code> in order to make a module that can either be run directly or imported, etc.</p>
<p>Finally, it's best to have all "significant" code in functions (or methods in classes), not just stylistically, but because code in a function executes significantly faster (since the Python compiler can then automatically optimize all accesses to local variables). For example, consider...:</p>
<pre><code>import time
lotsotimes = range(1000*1000)
start = time.time()
for x in lotsotimes:
x = x + x
stend = time.time()
print 'in module toplev: %.6f' % (stend - start)
def fun():
start = time.time()
for x in lotsotimes:
x = x + x
stend = time.time()
print 'in function body: %.6f' % (stend - start)
fun()
</code></pre>
<p>On my laptop, with Python 2.6, this emits:</p>
<pre><code>in module toplev: 0.405440
in function body: 0.123296
</code></pre>
<p>So, for code that does a lot of variable accesses and little else, running it in a function as opposed to running it as module top-level code could speed it up by more than 3 times.</p>
<p>The detailed explanation: at module-level, all variables are inevitably kept in a dictionary, so each variable access is a dict-access; local variables of a function get optimized into a special array, so access is faster (the difference is even more extreme than the 20% or so speed-up you'd see by accessing an item in a Python list vs one in a Python dict, since the local-variable optimization also saves hashing & other ancillary costs).</p>
| 6 | 2009-10-10T19:37:01Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 1,548,720 | <p>Try something like this:</p>
<pre><code>import os, re
def purge(dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
</code></pre>
<p>Then you would pass the directory containing the files and the pattern you wish to match.</p>
| 29 | 2009-10-10T18:38:01Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 1,548,788 | <p>If you need recursion into several subdirectories, you can use this method:</p>
<pre><code>import os, re, os.path
pattern = "^(?P<photo_id>\d+)[^\d].*jpg$"
mypath = "Photos"
for root, dirs, files in os.walk(mypath):
for file in filter(lambda x: re.match(pattern, x), files):
os.remove(os.path.join(root, file))
</code></pre>
<p>You can safely remove subdirectories on the fly from <code>dirs</code>, which contains the list of the subdirectories to visit at each node.</p>
<p>Note that if you are in a directory, you can also get files corresponding to a simple pattern expression with <code>glob.glob(pattern)</code>. In this case you would have to substract the set of files to keep from the whole set, so the code above is more efficient.</p>
| 7 | 2009-10-10T18:59:31Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 1,548,837 | <p>It's not clear to me that you actually want to do any named-group matching -- in the use you describe, the photoid is an <em>input</em> to the deletion function, and named groups' purpose is "output", i.e., extracting certain substrings from the matched string (and accessing them by name in the match object). So, I would recommend a simpler approach:</p>
<pre><code>import re
import os
def delete_thumbnails(photoid, photodirroot):
matcher = re.compile(r'^%s\d+\D.*jpg$' % photoid)
numdeleted = 0
for rootdir, subdirs, filenames in os.walk(photodirroot):
for name in filenames:
if not matcher.match(name):
continue
path = os.path.join(rootdir, name)
os.remove(path)
numdeleted += 1
return "Deleted %d thumbnails for %r" % (numdeleted, photoid)
</code></pre>
<p>You can pass the photoid as a normal string, or as a RE pattern piece if you need to remove several matchable IDs at once (e.g., <code>r'abc[def]</code> to remove abcd, abce, and abcf in a single call) -- that's the reason I'm inserting it literally in the RE pattern, rather than inserting the string <code>re.escape(photoid)</code> as would be normal practice. Certain parts such as counting the number of deletions and returning an informative message at the end are obviously frills which you should remove if they give you no added value in your use case. </p>
<p>Others, such as the "if not ... // continue" pattern, are highly recommended practice in Python (flat is better than nested: bailing out to the next leg of the loop as soon as you determine there is nothing to do on this one is better than nesting the actions to be done within an <code>if</code>), although of course other arrangements of the code would work too.</p>
| 2 | 2009-10-10T19:22:33Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 7,968,999 | <p>My recomendation:</p>
<pre><code>def purge(dir, pattern, inclusive=True):
regexObj = re.compile(pattern)
for root, dirs, files in os.walk(dir, topdown=False):
for name in files:
path = os.path.join(root, name)
if bool(regexObj.search(path)) == bool(inclusive):
os.remove(path)
for name in dirs:
path = os.path.join(root, name)
if len(os.listdir(path)) == 0:
os.rmdir(path)
</code></pre>
<p>This will recursively remove every file that matches the pattern by default, and every file that doesn't if inclusive is true. It will then remove any empty folders from the directory tree.</p>
| 2 | 2011-11-01T15:45:40Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 21,572,576 | <p>I find <code>Popen(["rm " + file_name + "*.ext"], shell=True, stdout=PIPE).communicate()</code> to be a much simpler solution to this problem. Although this is prone to injection attacks, I don't see any issues if your program is using this internally.</p>
| 0 | 2014-02-05T08:56:30Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 37,251,070 | <p>How about this?</p>
<pre><code>import glob, os
map(os.remove, glob.glob("P*.jpg"))
</code></pre>
<p>Mind you this does not do recursion and uses wildcards (not regex).</p>
| 6 | 2016-05-16T09:50:35Z | [
"python"
] |
Delete multiple files matching a pattern | 1,548,704 | <p>I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.</p>
<p>When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). </p>
<p>I <em>could</em> hard-code in the file-varients... But that's messy and if I change the way I do things, I'll need to revisit the code.</p>
<p>Ideally I'd like to do a regex-delete. In regex terms, all my originals are named like so:</p>
<pre><code>^(?P<photo_id>\d+)\.jpg$
</code></pre>
<p>So I want to delete:</p>
<pre><code>^(?P<photo_id>\d+)[^\d].*jpg$
</code></pre>
<p>(Where I replace <code>photo_id</code> with the ID I want to clean.)</p>
| 19 | 2009-10-10T18:32:43Z | 38,189,275 | <p>A variation on the glob approach, that will work with Python 3:</p>
<pre><code>import glob, os
for f in glob.glob("P*.jpg"):
os.remove(f)
</code></pre>
| 3 | 2016-07-04T16:45:14Z | [
"python"
] |
Efficient storage of and access to web pages with Python | 1,548,857 | <p>So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.). But of course performance wise I have some concerns especially with large objects/pages and high volumes of data. So that leads me to look at things like <a href="http://couchdb.apache.org/" rel="nofollow">CouchDB</a>/search engines/etc. So to summarize, my basic requirements are:</p>
<ol>
<li>It must be Python compatible (libraries/etc.)</li>
<li>Store meta data (URL, time retrieved, any GET/POST stuff I sent), response code, etc. of the page I requested.</li>
<li>Store a copy of the original web page as sent by the server (might be content, might be 404 search page, etc.).</li>
<li>Extract information from the web page and store it in a database.</li>
<li>Have the ability to do ad hoc queries on the existing corpus of original web pages (for example a new type of information I want to extract, or to see how many of the pages have the string "fizzbuzz" or whatever in them.</li>
<li>And of course it must be open source/Linux compatible, I have no interest in something I can't modify or fiddle with.</li>
</ol>
<p>So I'm thinking several broad options are:</p>
<ol>
<li>Toss everything into MySQL, use FULLTEXT, go nuts, shard the contact if needed.</li>
<li>Toss meta data into MySQL, store the data on the file system or something like CouchDB, write some custom search stuff.</li>
<li>Toss meta data into MySQL, store the data on a file system with a web server (maybe /YYYY/MM/DD/HH/MM/SS/URL/), make sure there is no default index.html/etc specified (directory index each directory in other words) and use some search engine like <a href="http://lucene.apache.org/" rel="nofollow">Lucene</a> or <a href="http://www.sphinxsearch.com/" rel="nofollow">Sphinx</a> index the content and use that to search. Biggest downside I see here is the inefficiency of repeatedly crawling the site.</li>
<li>Other solutions?</li>
</ol>
<p>When answering please include links to any technologies you mention and if possible what programming languages it has libraries for (i.e. if it's Scala only or whatever it's probably not that useful since this is a Python project). If this question has already been asked (I'm sure it must have been) please let me know (I searched, no luck). </p>
| 1 | 2009-10-10T19:29:56Z | 1,548,877 | <p>It sounds to me like you need a content management system. Check out <a href="http://plone.org/" rel="nofollow">Plone</a>. If that's not what you want maybe a web framework, like Grok, BFG, Django, Turbogears, or anything on <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">this list</a>. If that isn't good either, then I don't know what you are asking. :-)</p>
| 0 | 2009-10-10T19:43:04Z | [
"python",
"mysql",
"database"
] |
Efficient storage of and access to web pages with Python | 1,548,857 | <p>So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.). But of course performance wise I have some concerns especially with large objects/pages and high volumes of data. So that leads me to look at things like <a href="http://couchdb.apache.org/" rel="nofollow">CouchDB</a>/search engines/etc. So to summarize, my basic requirements are:</p>
<ol>
<li>It must be Python compatible (libraries/etc.)</li>
<li>Store meta data (URL, time retrieved, any GET/POST stuff I sent), response code, etc. of the page I requested.</li>
<li>Store a copy of the original web page as sent by the server (might be content, might be 404 search page, etc.).</li>
<li>Extract information from the web page and store it in a database.</li>
<li>Have the ability to do ad hoc queries on the existing corpus of original web pages (for example a new type of information I want to extract, or to see how many of the pages have the string "fizzbuzz" or whatever in them.</li>
<li>And of course it must be open source/Linux compatible, I have no interest in something I can't modify or fiddle with.</li>
</ol>
<p>So I'm thinking several broad options are:</p>
<ol>
<li>Toss everything into MySQL, use FULLTEXT, go nuts, shard the contact if needed.</li>
<li>Toss meta data into MySQL, store the data on the file system or something like CouchDB, write some custom search stuff.</li>
<li>Toss meta data into MySQL, store the data on a file system with a web server (maybe /YYYY/MM/DD/HH/MM/SS/URL/), make sure there is no default index.html/etc specified (directory index each directory in other words) and use some search engine like <a href="http://lucene.apache.org/" rel="nofollow">Lucene</a> or <a href="http://www.sphinxsearch.com/" rel="nofollow">Sphinx</a> index the content and use that to search. Biggest downside I see here is the inefficiency of repeatedly crawling the site.</li>
<li>Other solutions?</li>
</ol>
<p>When answering please include links to any technologies you mention and if possible what programming languages it has libraries for (i.e. if it's Scala only or whatever it's probably not that useful since this is a Python project). If this question has already been asked (I'm sure it must have been) please let me know (I searched, no luck). </p>
| 1 | 2009-10-10T19:29:56Z | 1,548,896 | <p>You may be trying to achieve too much with the storage of the html (and supporting files). It seems you wish this repository would both</p>
<ul>
<li>allow to display a particular page as it was in its original site</li>
<li>provide indexing for locating pages relevant to a particular search criteria</li>
</ul>
<p>The html underlying a web page once looked a bit akin to a self-standing document, but the pages crawled off the net nowadays are much messier: javascript, ajax snippets, advertisement sections, image blocks etc.<br>
This reality may cause you to rethink the one storage for all html approach. (And also the parsing / pre-processing of the material crawled, but that's another story...)</p>
<p>On the other hand, the distinction between <em>metadata</em> and the <em>true text content</em> associated with the page doesn't need to be so marked. By "true text content", I mean [possibly partially marked-up] text from the web pages that is otherwise free of all other "Web 2.0 noise") Many search engines, including <a href="http://lucene.apache.org/solr/" rel="nofollow"><strong>Solr</strong></a> (since you mentioned Lucene) now allow mixing the two genres, in the form of semi-structured data. For operational purposes (eg to task the crawlers etc.), you may keep a relational store with management related metadata, but the idea is that for search purposes, fielded and free-text info can coexist nicely (at the cost of pre-processing much of the input data).</p>
| 1 | 2009-10-10T19:52:25Z | [
"python",
"mysql",
"database"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.