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 |
|---|---|---|---|---|---|---|---|---|---|
Telnet automation / scripting | 1,491,494 | <p>I have already checked <a href="http://stackoverflow.com/questions/709801/creating-a-script-for-a-telnet-session">This Question</a> but could not find what i'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server.</p>
<p>Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then return when done.</p>
<p>What's the best approach?</p>
| 5 | 2009-09-29T09:29:42Z | 1,491,566 | <p>I've never used it myself, but maybe <a href="http://pypi.python.org/pypi/pexpect" rel="nofollow">pexpect</a> is what you need?</p>
<blockquote>
<p>"Pexpect can be used for automating
interactive applications such as ssh,
ftp, passwd, telnet, etc."</p>
</blockquote>
| 0 | 2009-09-29T09:44:36Z | [
"python",
"windows",
"scripting",
"automation",
"telnet"
] |
Telnet automation / scripting | 1,491,494 | <p>I have already checked <a href="http://stackoverflow.com/questions/709801/creating-a-script-for-a-telnet-session">This Question</a> but could not find what i'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server.</p>
<p>Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then return when done.</p>
<p>What's the best approach?</p>
| 5 | 2009-09-29T09:29:42Z | 2,184,149 | <p>You may want to consider <a href="http://wiki.github.com/knipknap/exscript/" rel="nofollow">Exscript</a> as well. It simplifies some of the easy tasks but for more complicated there is additional level of abstraction (Exscript is a scripting language in itself). Either way - worth checking out.</p>
| 3 | 2010-02-02T12:59:55Z | [
"python",
"windows",
"scripting",
"automation",
"telnet"
] |
Telnet automation / scripting | 1,491,494 | <p>I have already checked <a href="http://stackoverflow.com/questions/709801/creating-a-script-for-a-telnet-session">This Question</a> but could not find what i'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server.</p>
<p>Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then return when done.</p>
<p>What's the best approach?</p>
| 5 | 2009-09-29T09:29:42Z | 5,316,604 | <p>This thread is old but I thought I'd go ahead and post anyway. There is a prog called AutoMate that would most likely suit your needs well. It runs on Windows and is pretty easy to use. </p>
<p>More info on telnet automation - <a href="http://www.networkautomation.com/sales/terminal-emulation-automation/" rel="nofollow">http://www.networkautomation.com/sales/terminal-emulation-automation/</a> </p>
| 0 | 2011-03-15T19:00:04Z | [
"python",
"windows",
"scripting",
"automation",
"telnet"
] |
a better way to do ajax in django | 1,491,618 | <p>The other day I wrote some AJAX for a Django app that i have been working on.</p>
<p>I come from Ruby on Rails, so I haven't done much in the way of raw JS.</p>
<p>So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:</p>
<p>1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)</p>
<pre><code> function updateTable(){
new Ajax.Updater('tablediv',url {params: params....etc
</code></pre>
<p>2) django view that got new data to populate the table with:</p>
<pre><code> def ajaxTable
objects = Objects.object.all...
return render_to_response('ajaxtable.html',objects)
</code></pre>
<p>3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <code><table></code> <code></table></code> ...:</p>
<pre><code> <th>{{object.data}}</th>
<td>{{object.moredata}}</td>
</code></pre>
<p>so to my actual question:</p>
<p>This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.</p>
<p>Is this the way it's done? It works fine, I just don't know enough to know, you know?</p>
| 5 | 2009-09-29T09:59:44Z | 1,491,640 | <p>What exactly seems hacky about it? Seems like a perfectly valid way of doing something.</p>
<p>I guess an alternative would be <a href="http://docs.djangoproject.com/en/dev/topics/serialization/" rel="nofollow">serialising</a> to json and sending it back to a javascript <a href="http://plugins.jquery.com/project/tempest" rel="nofollow">templating</a> snippet. </p>
| 1 | 2009-09-29T10:04:58Z | [
"javascript",
"python",
"ajax",
"django"
] |
a better way to do ajax in django | 1,491,618 | <p>The other day I wrote some AJAX for a Django app that i have been working on.</p>
<p>I come from Ruby on Rails, so I haven't done much in the way of raw JS.</p>
<p>So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:</p>
<p>1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)</p>
<pre><code> function updateTable(){
new Ajax.Updater('tablediv',url {params: params....etc
</code></pre>
<p>2) django view that got new data to populate the table with:</p>
<pre><code> def ajaxTable
objects = Objects.object.all...
return render_to_response('ajaxtable.html',objects)
</code></pre>
<p>3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <code><table></code> <code></table></code> ...:</p>
<pre><code> <th>{{object.data}}</th>
<td>{{object.moredata}}</td>
</code></pre>
<p>so to my actual question:</p>
<p>This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.</p>
<p>Is this the way it's done? It works fine, I just don't know enough to know, you know?</p>
| 5 | 2009-09-29T09:59:44Z | 1,491,654 | <p><em>No matter what</em>, you're going to need at least two things:</p>
<ol>
<li><p>Your javascript code to make the call (you have this)</p></li>
<li><p>Server side code to handle the request (this is your view and url-config)</p></li>
</ol>
<p>There is absolutely nothing "hacky" about this.</p>
<p>The third thing, your template file, is optional - but is generally good practice. You want to separate your markup from the code, for many reasons.</p>
<p>So I think you've got the right idea. Carry on.</p>
| 2 | 2009-09-29T10:08:12Z | [
"javascript",
"python",
"ajax",
"django"
] |
a better way to do ajax in django | 1,491,618 | <p>The other day I wrote some AJAX for a Django app that i have been working on.</p>
<p>I come from Ruby on Rails, so I haven't done much in the way of raw JS.</p>
<p>So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:</p>
<p>1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)</p>
<pre><code> function updateTable(){
new Ajax.Updater('tablediv',url {params: params....etc
</code></pre>
<p>2) django view that got new data to populate the table with:</p>
<pre><code> def ajaxTable
objects = Objects.object.all...
return render_to_response('ajaxtable.html',objects)
</code></pre>
<p>3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <code><table></code> <code></table></code> ...:</p>
<pre><code> <th>{{object.data}}</th>
<td>{{object.moredata}}</td>
</code></pre>
<p>so to my actual question:</p>
<p>This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.</p>
<p>Is this the way it's done? It works fine, I just don't know enough to know, you know?</p>
| 5 | 2009-09-29T09:59:44Z | 1,491,693 | <p>It kinda depends what you want to do I think. Ajax being quite a wide range of scenarios from Google Maps to a simple auto-complete varys greatly in complexity and the best approach.</p>
<p>However, there are some useful things you can do that help.</p>
<p>1) Template level</p>
<p>Make sure you have "django.core.context_processors.request" in your TEMPLATE_CONTEXT_PROCESSORS setting. Then you can do this;</p>
<pre><code>{% if not request.is_ajax %}
<html>
<head>
...
</head>
<body>
...
{% endif %}
actual content
{% if not request.is_ajax %}
</body>
</html>
{% endif %}
</code></pre>
<p>Basically then say this page is /test/ you can do a browser request and get the full content or a request via JavaScript and just get the content. There is a blogpost somewhere that explains this in more detail but I can't find it at the moment.</p>
<p>2) In the view</p>
<p>In the template we are just accessing the request object in the template. In the view you can do very similar things.</p>
<pre><code>def my_view(request):
if requst.is_ajax():
# handle for Ajax requests
# otherwise handle 'normal' requests
return HttpResponse('Hello world')
</code></pre>
<p>The above methods don't really do it differently than you do but allow you to re-use views and write it bit more concisely. I wouldn't really say what you are doing is wrong or hacky but you could write it to make it more concise and re-use the templates and views.</p>
<p>say for example you could have just one template and if its a Ajax request have it only return the section that will need to be updated. In your case it would be the tables views.</p>
| 5 | 2009-09-29T10:18:30Z | [
"javascript",
"python",
"ajax",
"django"
] |
a better way to do ajax in django | 1,491,618 | <p>The other day I wrote some AJAX for a Django app that i have been working on.</p>
<p>I come from Ruby on Rails, so I haven't done much in the way of raw JS.</p>
<p>So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:</p>
<p>1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)</p>
<pre><code> function updateTable(){
new Ajax.Updater('tablediv',url {params: params....etc
</code></pre>
<p>2) django view that got new data to populate the table with:</p>
<pre><code> def ajaxTable
objects = Objects.object.all...
return render_to_response('ajaxtable.html',objects)
</code></pre>
<p>3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <code><table></code> <code></table></code> ...:</p>
<pre><code> <th>{{object.data}}</th>
<td>{{object.moredata}}</td>
</code></pre>
<p>so to my actual question:</p>
<p>This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.</p>
<p>Is this the way it's done? It works fine, I just don't know enough to know, you know?</p>
| 5 | 2009-09-29T09:59:44Z | 1,732,118 | <p>I am quite late, but I want to document how to combine and adapt the solutions presented by <a href="http://stackoverflow.com/questions/1491618/a-better-way-to-do-ajax-in-django/1491693#1491693">d0ugal</a>
in a way, that it will resolve a much cleaner template-code.</p>
<p>I have a model representing contact persons. </p>
<p>The (generic) view to get one ContactPerson looks like this:</p>
<pre><code>def contcactperson_detail_view(request, name):
try:
person = ContactPerson.objects.get(slug=name)
except:
raise Http404
if request.is_ajax():
return contcactperson_detail_view_ajax(request, person)
return list_detail.object_detail(
request,
queryset = ContactPerson.objects.all(),
object_id = person.id,
template_object_name = "contactperson",
)
@render_to('cms/contactperson_detail_ajax.html')
def contcactperson_detail_view_ajax(request, person):
return {'contactperson':person, 'is_ajax':True}
</code></pre>
<p>The template to render the view that handles one ContactPerson is called <code>contcactperson_detail_view.html</code>:</p>
<pre><code>{% extends "index.html" %}
{% block textpane %}
<h1 id="mainheader">{{ contactperson.first_name }} {{ contactperson.family_name }} </h1>
<div class="indentation">&nbsp;</div>
{% include 'cms/contactperson_detail_photo.html' %}
<div id="text_pane">
{% include 'cms/contactperson_detail_textpane.html' %}
</div>
{% endblock %}
</code></pre>
<p>It includes two sub-templates</p>
<pre><code>contactperson_detail_textpane.html
<p>{{ contactperson.description }}</p>
<ul>
<li>
<dl>
<dt>Email</dt>
<dd>
{{ contactperson.mail }}
</dd>
</dl>
</li>
<li>
<dl>
<dt>Contact Person for</dt>
<dd>
<ul>
{% for c in contactperson.categories.all %}
<li><a href="{% url category-view c.slug %}">{{ c }}</a></li>
{% endfor %}
</ul>
</dd>
</dl>
</li>
</ul>
</code></pre>
<p>and <code>contactperson_detail_photo.html</code></p>
<pre><code>{% with contactperson.photo.detailphoto as pic %}
{% with pic.url as pic_url %}
<div {% if not is_ajax %}id='imageContainer'{% endif %} style="float: right;padding-right:0.5em;
padding-bottom: 1em; padding-left:0.5em;clear:both;
width:{{ pic.width }}px">
<div style="width:{{ pic.width}}px">
<img style="clear:both" src="{{ pic_url }}" alt="{{ i.name }}"/>
</div>
</div>
{% endwith %}
{% endwith %}
</code></pre>
<p>this 3 templates will be used, if the request isn't ajax.</p>
<p>But if the request is ajax, <code>contcactperson_detail_view</code> will return the view <code>contcactperson_detail_view_ajax</code>, that uses the template <code>contactperson_detail_ajax.html</code> for rendering. And this template looks like this:</p>
<pre><code><h1>{{ contactperson.first_name }} {{ contactperson.family_name }}</h1>
{% include 'cms/contactperson_detail_photo.html' %}
{% include 'cms/contactperson_detail_textpane.html' %}
</code></pre>
<p>So it uses the same sub-templates but isn't extending anything, therefore only the needed markup delivered. As the ajax view passes <code>is_ajax = True</code> to the template, it can be used to adjust minor things, like setting correct id-attributes.</p>
<p>No context-processor or additional url-conf needed.</p>
<p>Finally the Javascript code:</p>
<pre><code>$("#contact_person_portlet a").click(function(event){
event.preventDefault();
$.ajax({
type: "GET",
url: event.target.getAttribute('href'),
success: function(msg){
overlay(msg);
}
});
});
</code></pre>
<p>Hope that it will be useful for some people. If so, please leave a comment!</p>
| 4 | 2009-11-13T21:45:04Z | [
"javascript",
"python",
"ajax",
"django"
] |
get the exit code for python program | 1,491,796 | <p>I'm running a python program on windowsXP, how can i obtain the exit code after my program ends ?</p>
<p>Thanks.</p>
| 5 | 2009-09-29T10:40:30Z | 1,491,834 | <p>From a Windows command line you can use:</p>
<pre><code>echo %ERRORLEVEL%
</code></pre>
<p>For example:</p>
<pre><code>C:\work>python helloworld.py
Hello World!
C:\work>echo %ERRORLEVEL%
0
</code></pre>
| 5 | 2009-09-29T10:47:15Z | [
"python"
] |
get the exit code for python program | 1,491,796 | <p>I'm running a python program on windowsXP, how can i obtain the exit code after my program ends ?</p>
<p>Thanks.</p>
| 5 | 2009-09-29T10:40:30Z | 1,491,844 | <p>How do you run the program?</p>
<p>Exit in python with sys.exit(1)</p>
<p>If you're in CMD or a BAT file you can access the variable %ERRORLEVEL% to obtain the exit code.</p>
<p>For example (batch file):</p>
<pre><code>IF ERRORLEVEL 1 GOTO LABEL
</code></pre>
| 4 | 2009-09-29T10:51:07Z | [
"python"
] |
get the exit code for python program | 1,491,796 | <p>I'm running a python program on windowsXP, how can i obtain the exit code after my program ends ?</p>
<p>Thanks.</p>
| 5 | 2009-09-29T10:40:30Z | 1,491,863 | <p>You can also use python to start your python-program</p>
<pre><code>import subprocess
import sys
retcode = subprocess.call([sys.executable, "myscript.py"])
print retcode
</code></pre>
| 3 | 2009-09-29T10:57:16Z | [
"python"
] |
get the exit code for python program | 1,491,796 | <p>I'm running a python program on windowsXP, how can i obtain the exit code after my program ends ?</p>
<p>Thanks.</p>
| 5 | 2009-09-29T10:40:30Z | 1,491,864 | <p>If you want to use ERRORLEVEL (as opposed to %ERRORLEVEL%) to <a href="http://support.microsoft.com/kb/69576" rel="nofollow">check for a specific exit value</a> use</p>
<pre><code>IF ERRORLEVEL <N> IF NOT ERRORLEVEL <N+1> <COMMAND>
</code></pre>
<p>For example </p>
<pre><code>IF ERRORLEVEL 3 IF NOT ERRORLEVEL 4 GOTO LABEL
</code></pre>
| 1 | 2009-09-29T10:57:22Z | [
"python"
] |
get the exit code for python program | 1,491,796 | <p>I'm running a python program on windowsXP, how can i obtain the exit code after my program ends ?</p>
<p>Thanks.</p>
| 5 | 2009-09-29T10:40:30Z | 2,028,050 | <p>I got the following in a script:</p>
<pre><code>set ERRORLEVEL=17
python.exe -c "import sys; sys.exit(1)"
echo %ERRORLEVEL%
</code></pre>
<p>==> <strong>17</strong></p>
| 1 | 2010-01-08T14:06:02Z | [
"python"
] |
Testing for an empty iterator in a Python for... loop | 1,491,957 | <p>The code below is based on <a href="http://code.activestate.com/recipes/413614/" rel="nofollow">this recipe</a>. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways:</p>
<ol>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is skipped, rather than being selected on the next iteration.</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are less than two items left in the iterator, <strong>my_func()</strong> returns None.</li>
</ol>
<p>How can I ensure that:</p>
<ul>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is <em>not</em> skipped?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there is one item left in the iterator, <strong>my_func()</strong> prints it and calls <strong>get_yes_no_answer()</strong>?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are no items left in the iterator, the <strong>except StopIteration</strong> clause is triggered?</li>
</ul>
<p>Here's the code:</p>
<pre><code>def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
else:
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice.group()
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
else:
# Check if iterator is empty. If so, quit; if not, do something else.
try:
next_choice = choice_iterator.next()
except StopIteration:
print "No matches. Exiting..."
sys.exit()
else:
choice_iterator = itertools.chain([next_choice], choice_iterator)
</code></pre>
| 1 | 2009-09-29T11:27:15Z | 1,492,039 | <p>why are you doing it this way at all? why not just:</p>
<pre><code>def get_choice(pattern, inpt):
choices = pattern.finditer(inpt, re.M)
if not choices:
sys.exit('No choices')
for choice in choices:
print(choice.group(0))
if get_yes_no_answer():
return choice
sys.exit('No matches')
</code></pre>
<p>I don't know what your is the length of your input but I doubt it's worth the trouble.</p>
| 3 | 2009-09-29T11:43:03Z | [
"python",
"exception",
"iterator",
"conditional"
] |
Testing for an empty iterator in a Python for... loop | 1,491,957 | <p>The code below is based on <a href="http://code.activestate.com/recipes/413614/" rel="nofollow">this recipe</a>. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways:</p>
<ol>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is skipped, rather than being selected on the next iteration.</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are less than two items left in the iterator, <strong>my_func()</strong> returns None.</li>
</ol>
<p>How can I ensure that:</p>
<ul>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is <em>not</em> skipped?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there is one item left in the iterator, <strong>my_func()</strong> prints it and calls <strong>get_yes_no_answer()</strong>?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are no items left in the iterator, the <strong>except StopIteration</strong> clause is triggered?</li>
</ul>
<p>Here's the code:</p>
<pre><code>def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
else:
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice.group()
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
else:
# Check if iterator is empty. If so, quit; if not, do something else.
try:
next_choice = choice_iterator.next()
except StopIteration:
print "No matches. Exiting..."
sys.exit()
else:
choice_iterator = itertools.chain([next_choice], choice_iterator)
</code></pre>
| 1 | 2009-09-29T11:27:15Z | 1,492,102 | <p>See the pairwise iterator from <a href="http://stackoverflow.com/questions/914715/python-looping-through-all-but-the-last-item-of-a-list/914786#914786">this question</a>. You can then check for last item like this:</p>
<pre><code>MISSING = object()
for choice, next_choice in pairwise(chain(choice_iterator, [MISSING])):
print(choice.group())
if get_yes_no_answer():
return choice.group()
if next_choice is MISSING:
print("No matches. Exiting...")
sys.exit()
</code></pre>
<p>In the example you showed this doesn't seem to be necessary. You don't need to check if finditer returned an iterator because it always does. And you can just fall through the for loop if you don't find what you want:</p>
<pre><code>def my_func(choice_pattern, input):
"""Search in input for some things to choose from."""
for choice in choice_pattern.finditer(input, re.M):
print(choice.group())
if get_yes_no_answer():
return choice.group()
else:
print("No choices. Exiting...")
sys.exit()
</code></pre>
| 0 | 2009-09-29T11:58:44Z | [
"python",
"exception",
"iterator",
"conditional"
] |
Testing for an empty iterator in a Python for... loop | 1,491,957 | <p>The code below is based on <a href="http://code.activestate.com/recipes/413614/" rel="nofollow">this recipe</a>. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways:</p>
<ol>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is skipped, rather than being selected on the next iteration.</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are less than two items left in the iterator, <strong>my_func()</strong> returns None.</li>
</ol>
<p>How can I ensure that:</p>
<ul>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is <em>not</em> skipped?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there is one item left in the iterator, <strong>my_func()</strong> prints it and calls <strong>get_yes_no_answer()</strong>?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are no items left in the iterator, the <strong>except StopIteration</strong> clause is triggered?</li>
</ul>
<p>Here's the code:</p>
<pre><code>def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
else:
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice.group()
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
else:
# Check if iterator is empty. If so, quit; if not, do something else.
try:
next_choice = choice_iterator.next()
except StopIteration:
print "No matches. Exiting..."
sys.exit()
else:
choice_iterator = itertools.chain([next_choice], choice_iterator)
</code></pre>
| 1 | 2009-09-29T11:27:15Z | 1,492,111 | <p>Why so complex approach?</p>
<p>I think this should do pretty much the same:</p>
<pre><code>def my_func(pattern, data):
choices = pattern.findall(data, re.M)
while(len(choices)>1):
choice = choices.pop(0)
if get_yes_no_answer():
return choice
else:
choices.pop(0)
else:
return None
</code></pre>
| 0 | 2009-09-29T12:00:30Z | [
"python",
"exception",
"iterator",
"conditional"
] |
Testing for an empty iterator in a Python for... loop | 1,491,957 | <p>The code below is based on <a href="http://code.activestate.com/recipes/413614/" rel="nofollow">this recipe</a>. However, the key point of the recipe - that it provides a way to break out of the iteration on an iterator if the iterator is empty - doesn't seem to work here, instead behaving in the following undesired ways:</p>
<ol>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is skipped, rather than being selected on the next iteration.</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are less than two items left in the iterator, <strong>my_func()</strong> returns None.</li>
</ol>
<p>How can I ensure that:</p>
<ul>
<li>If <strong>get_yes_no_answer() == False</strong> and there are two or more items left in the iterator, <strong>next_choice</strong> is <em>not</em> skipped?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there is one item left in the iterator, <strong>my_func()</strong> prints it and calls <strong>get_yes_no_answer()</strong>?</li>
<li>If <strong>get_yes_no_answer() == False</strong> and there are no items left in the iterator, the <strong>except StopIteration</strong> clause is triggered?</li>
</ul>
<p>Here's the code:</p>
<pre><code>def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
else:
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice.group()
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
else:
# Check if iterator is empty. If so, quit; if not, do something else.
try:
next_choice = choice_iterator.next()
except StopIteration:
print "No matches. Exiting..."
sys.exit()
else:
choice_iterator = itertools.chain([next_choice], choice_iterator)
</code></pre>
| 1 | 2009-09-29T11:27:15Z | 1,492,146 | <p>You don't need to check if the iterator is empty. The for loop will do that for you, and stop when the iterator is empty. It's as simple as that.</p>
<p>Also, you don't need the <code>else</code> after the sys.exit() or the return.</p>
<p>That done, your code looks like this:</p>
<pre><code>def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
# Loop exited without matches.
print "No matches. Exiting..."
sys.exit()
</code></pre>
<p>That's it!</p>
<p>What happens is that you in the loop, <em>also</em> gets the next item. The result is that you in fact only show every second answer.</p>
<p>In fact, you can simplify it even more:</p>
<pre><code>def my_func(choice_pattern, input):
choice_iterator = choice_pattern.finditer(input, re.M)
if choice_iterator:
for choice in choice_iterator:
print choice
if get_yes_no_answer():
return choice
# If there is no choices or no matches, you end up here:
print "No matches. Exiting..."
sys.exit()
</code></pre>
<p>Iterators are used pretty much as any sequence type. You don't need to treat it differently from a list.</p>
| 1 | 2009-09-29T12:06:53Z | [
"python",
"exception",
"iterator",
"conditional"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 1,492,033 | <p>You can have a look at the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing package</a> which avoid the GIL lock problem.</p>
| 0 | 2009-09-29T11:42:23Z | [
"python",
"concurrent-processing"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 1,492,076 | <p>Don't worry about GIL. In your case it doesn't matter.</p>
<p>Easiest way to do what you want is to create thread pool, using <em>threading</em> module and one of thread pool implementations from <a href="http://code.activestate.com/recipes/langs/python/tags/pool/" rel="nofollow">ASPN</a>. Each thread from that pool can use <em>httplib</em> to download your web pages.</p>
<p>Another option is to use <a href="http://pycurl.cvs.sourceforge.net/" rel="nofollow">PyCURL</a> module -- it supports parallel downlaods natively, so you don't have to implement it yourself.</p>
| 9 | 2009-09-29T11:52:32Z | [
"python",
"concurrent-processing"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 1,492,094 | <p>Downloading is IO, which may be done asynchronously using non-blocking sockets or twisted. Both of these solutions will be much more efficient than threading or multiprocessing.</p>
| 0 | 2009-09-29T11:57:11Z | [
"python",
"concurrent-processing"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 1,492,194 | <p>GIL prevents you from effectively doing processor load balancing with threads. As this is not processor loads balancing but preventing one IO wait from stopping the whole download, the GIL is not relevant here. *)</p>
<p>So all you need to do is create several processes that download at the same time. You can do that with the threading module or the multiprocessing module.</p>
<p>*) Well... unless you have Gigabit connections and your problem is really that your processor gets overloaded before your net does. But that's obviously not the case here.</p>
| 7 | 2009-09-29T12:17:17Z | [
"python",
"concurrent-processing"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 1,492,284 | <p>I recently solved this same problem. One thing to consider is that some people don't take kindly to having their servers bogged down and will block an IP address that does so. The standard courtesy that I've heard is about 3 seconds between page requests, but this is flexible.</p>
<p>If you are downloading from multiple websites you can group your URLs by domain and create one thread per. Then in your thread you can do something like this:</p>
<pre><code>for url in urls:
timer = time.time()
# ... get your content ...
# perhaps put content in a queue to be written back to
# your database if it doesn't allow concurrent writes.
while time.time() - timer < 3.0:
time.sleep(0.5)
</code></pre>
<p>Sometimes just getting your response will take the full 3 seconds and you don't have to worry about it.</p>
<p>Granted, this won't help you at all if you're only downloading from one site, but it may keep you from getting blocked.</p>
<p>My machine handles about 200 threads before the overhead of managing them slowed the process down. I ended up at something like 40-50 pages per second.</p>
| 2 | 2009-09-29T12:38:07Z | [
"python",
"concurrent-processing"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 1,493,005 | <p><a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> & <a href="http://docs.python.org/library/threading.html#module-threading" rel="nofollow">threading</a> (or <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing" rel="nofollow">multiprocessing</a>) packages has all you need to do the "spider" you need.</p>
<p>What you have to do is get urls from DB, and for each url start a thread or process that
grabs the url. </p>
<p>just as example (misses Data Base urls retrieving):</p>
<pre><code>#!/usr/bin/env python
import Queue
import threading
import urllib2
import time
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
"http://ibm.com", "http://apple.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(1024)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(5):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
#populate queue with data
for host in hosts:
queue.put(host)
#wait on the queue until everything has been processed
queue.join()
main()
print "Elapsed Time: %s" % (time.time() - start)
</code></pre>
| 1 | 2009-09-29T14:43:24Z | [
"python",
"concurrent-processing"
] |
Download multiple pages concurrently? | 1,491,993 | <p>I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.</p>
<p>According to <a href="http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once">this thread</a>, Python doesn't allow this because of something called <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a> that prevents lauching the same script multiple times.</p>
<p>Before investing time learning the Twisted framework, I'd like to make sure there isn't an easier way to do what I need to do above.</p>
<p>Thank you for any tip.</p>
| 2 | 2009-09-29T11:35:11Z | 9,016,152 | <p>Nowadays there are excellent Python libs that do this for you - <a href="http://urllib3.readthedocs.org/" rel="nofollow">urllib3</a> and <a href="http://docs.python-requests.org/" rel="nofollow">requests</a></p>
| 1 | 2012-01-26T09:37:52Z | [
"python",
"concurrent-processing"
] |
Python: can you tell the name of the calling shell? | 1,492,508 | <p>I have a python script that is always called from a shell, which can be either zsh or bash. </p>
<p>How can I tell which one called the script?</p>
| 1 | 2009-09-29T13:22:00Z | 1,492,532 | <p>os.system("echo $0")</p>
<p>This works flawlessly on my system:</p>
<pre><code>cat shell.py:
#!/ms/dist/python/PROJ/core/2.5/bin/python
import os
print os.system("echo $0")
</code></pre>
<p><br></p>
<pre><code>bash-2.05b$ uname -a
Linux pi929c1n10 2.4.21-32.0.1.EL.msdwhugemem #1 SMP Mon Dec 5 21:32:44 EST 2005 i686 athlon i386 GNU/Linux
pi929c1n10 /ms/user/h/hirscst 8$ ./shell.py
/bin/ksh
pi929c1n10 /ms/user/h/hirscst 9$ bash
bash-2.05b$ ./shell.py
/bin/ksh
bash-2.05b$
</code></pre>
| -2 | 2009-09-29T13:24:08Z | [
"python",
"shell"
] |
Python: can you tell the name of the calling shell? | 1,492,508 | <p>I have a python script that is always called from a shell, which can be either zsh or bash. </p>
<p>How can I tell which one called the script?</p>
| 1 | 2009-09-29T13:22:00Z | 1,492,602 | <p>You can't do this in a reliable automated way.</p>
<ul>
<li><p>Environment variables can be misleading (a user can maliciously switch them). Most automatic shell variables aren't "leaky", i.e. they are only visible in the shell process, and not for child processes.</p></li>
<li><p>You could figure out your parent PID and then search the list of processes for that ID. Doesn't work if you're run in the background (in this case PPID is always 1).</p></li>
<li><p>A user could start your program from within a script. Which is the correct shell in this case? The one in which the script was started or the script's shell?</p></li>
<li><p>Other programs can use system calls to run your script. In this case, you'd get either their shell or nothing.</p></li>
</ul>
<p>If you have absolute control over the user's environment, then put a variable in their profile (check the manuals for BASH and ZSH for a file which is <em>always</em> read at startup. IIRC, it's <code>.profile</code> for BASH).</p>
<p>[EDIT] Create an alias which is invoked for both shells. In the alias, use</p>
<pre><code>env SHELL_HINT="x$BASH_VERSION" your_script.py
</code></pre>
<p>That should evaluate to "x" for zsh and to something else for bash.</p>
| 0 | 2009-09-29T13:35:18Z | [
"python",
"shell"
] |
Python: can you tell the name of the calling shell? | 1,492,508 | <p>I have a python script that is always called from a shell, which can be either zsh or bash. </p>
<p>How can I tell which one called the script?</p>
| 1 | 2009-09-29T13:22:00Z | 1,492,649 | <pre><code>import os
shell = os.getenv('SHELL')
</code></pre>
| 0 | 2009-09-29T13:42:20Z | [
"python",
"shell"
] |
Python: can you tell the name of the calling shell? | 1,492,508 | <p>I have a python script that is always called from a shell, which can be either zsh or bash. </p>
<p>How can I tell which one called the script?</p>
| 1 | 2009-09-29T13:22:00Z | 1,492,667 | <p>In Linux you can use procfs:</p>
<pre><code>>>> os.readlink('/proc/%d/exe' % os.getppid())
'/bin/bash'
</code></pre>
<p><code>os.getppid()</code> returns the PID of parent process. This is portable. But obtaining process name can't be done in portable way. You can parse <code>ps</code> output which is available on all unices, e.g. with <a href="http://code.google.com/p/psutil/" rel="nofollow">psutil</a>. </p>
| 6 | 2009-09-29T13:44:54Z | [
"python",
"shell"
] |
How to shutdown cherrypy from within? | 1,492,699 | <p>I am developing on cherrypy, I start it from a python script.</p>
<p>For better development I wonder what is the correct way to stop cherrypy from within the main process (and not from the outside with ctrl-c or SIGTERM).</p>
<p>I assume I have to register a callback function from the main application to be able to stop the cherrypy main process from a worker thread. </p>
<p>But how do I stop the main process from within?</p>
| 0 | 2009-09-29T13:49:19Z | 1,492,746 | <pre><code>import sys
class MyCherryPyApplication(object):
def default(self):
sys.exit()
default.exposed = True
cherrypy.quickstart(MyCherryPyApplication())
</code></pre>
<p>Putting a sys.exit() in any request handler exits the whole server</p>
<p>I would have expected this only terminates the current thread, but it terminates the whole server. That's what I wanted.</p>
| 5 | 2009-09-29T14:02:06Z | [
"python",
"cherrypy"
] |
Rhythmbox: how do I access the 'rating' field of a track through Python script? | 1,492,849 | <p>I would like the capability to get/set the rating associated with a specific track through a Python. How do I achieve this?</p>
| 2 | 2009-09-29T14:18:47Z | 1,493,522 | <p>You can use Rhythmbox' D-Bus interface. I have written a small script that can get/set the rating and displays a notification, all acting on the currently playing song.</p>
<p>The script is here: <a href="http://kaizer.se/wiki/code/rhrating.py" rel="nofollow">http://kaizer.se/wiki/code/rhrating.py</a></p>
<p>Addendum one: I promise I write more beautiful Python when it's not a throwaway script!<br />
Addendum two: The missing Usage string is <code>./rhrating.py [NEWRATING 0..5]</code></p>
<p>Addendum three: If I filter the script and take out the parts that exactly set the rating of a song at filesystem location <code>uri</code>, it's this:</p>
<pre><code>import dbus
bus = dbus.Bus()
service_name = "org.gnome.Rhythmbox"
sobj_name = "/org/gnome/Rhythmbox/Shell"
siface_name = "org.gnome.Rhythmbox.Shell"
def set_rating(uri, rating):
searchobj = bus.get_object(service_name, sobj_name)
shell = dbus.Interface(searchobj, siface_name)
shell.setSongProperty(uri, "rating", float(rating))
</code></pre>
| 3 | 2009-09-29T16:07:23Z | [
"python",
"linux",
"rhythmbox"
] |
Creating a news archive in Django | 1,492,866 | <p>I looking to build a news archive in python/django, I have no idea where to start with it though. I need the view to pull out all the news articles with I have done I then need to divide them in months and years so e.g.</p>
<p>Sept 09
Oct 09</p>
<p>I then need in the view to some every time a new news article is created for a new month it needs to output the new month, so if a news article was written in November the archive would then be, </p>
<p>Sept 09
Oct 09
Nov 09</p>
<p>Any one help?</p>
| 2 | 2009-09-29T14:21:55Z | 1,493,485 | <p>It seems like you are trying to make a single view that pulls out of of the data and then try to order them by dates ect. I don't think that would be the best way to go about this.</p>
<p>Instead what you could do is to make a view to display each month's articles. I don't know your models but something like:</p>
<pre><code>articles = ArticleModel.objects.filter(date__month=month, date__year=year)
</code></pre>
<p>the month and year you would get from your url, fx archive/2009/9.</p>
<p>If you want to make sure that you only display your links to archives that has content, an easy solution would be to get all the articles and flag the months that has content. There should be a better way to do that, but if you put it inside a middleware and cache it, it shouldn't be a problem though.</p>
| 0 | 2009-09-29T16:01:25Z | [
"python",
"django",
"django-models",
"mysql",
"django-templates"
] |
Creating a news archive in Django | 1,492,866 | <p>I looking to build a news archive in python/django, I have no idea where to start with it though. I need the view to pull out all the news articles with I have done I then need to divide them in months and years so e.g.</p>
<p>Sept 09
Oct 09</p>
<p>I then need in the view to some every time a new news article is created for a new month it needs to output the new month, so if a news article was written in November the archive would then be, </p>
<p>Sept 09
Oct 09
Nov 09</p>
<p>Any one help?</p>
| 2 | 2009-09-29T14:21:55Z | 1,493,543 | <p>An excellent place to start is the book <a href="http://www.apress.com/book/view/9781430219385" rel="nofollow">Practical Django Projects</a> by James Bennett. Among other things, it guides you through the development of a web blog with multiple time-based views (by month, etc) that should serve you well as the basis for your application.</p>
| 3 | 2009-09-29T16:11:23Z | [
"python",
"django",
"django-models",
"mysql",
"django-templates"
] |
Creating a news archive in Django | 1,492,866 | <p>I looking to build a news archive in python/django, I have no idea where to start with it though. I need the view to pull out all the news articles with I have done I then need to divide them in months and years so e.g.</p>
<p>Sept 09
Oct 09</p>
<p>I then need in the view to some every time a new news article is created for a new month it needs to output the new month, so if a news article was written in November the archive would then be, </p>
<p>Sept 09
Oct 09
Nov 09</p>
<p>Any one help?</p>
| 2 | 2009-09-29T14:21:55Z | 1,493,824 | <p>One option you can try is to create a custom manager for your model that provides a way to pull out the archives. Here's code that I use:</p>
<pre><code>from django.db import models, connection
import datetime
class EntryManager(models.Manager):
def get_archives(self, level=0):
query = """
SELECT
YEAR(`date_posted`) AS `year`,
MONTH(`date_posted`) AS `month`,
count(*) AS `num_entries`
FROM
`blog_entry`
WHERE
`date_posted` <= %s
GROUP BY
YEAR(`date_posted`),
MONTH(`date_posted`)
ORDER BY
`year` DESC,
`month` DESC
"""
months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
cursor = connection.cursor()
cursor.execute(query, [datetime.datetime.now()])
return [{'year': row[0], 'month': row[1], 'month_name': months[int(row[1])-1], 'num_entries': row[2]} for row in cursor.fetchall()]
</code></pre>
<p>You'll of course need to attach it to the model with:</p>
<pre><code>objects = EntryManager()
</code></pre>
<p>This returns a list of dictionaries that contains the year, the numerical month, the month name, and the number of entries. You call it as such:</p>
<pre><code>archives = Entry.objects.get_archives()
</code></pre>
| 3 | 2009-09-29T17:08:07Z | [
"python",
"django",
"django-models",
"mysql",
"django-templates"
] |
Identical string return FALSE with '==' in Python, why? | 1,493,007 | <p>The data string is receive through a socket connexion. When receiving the first example where action variable would = 'IDENTIFY', it works. But when receiving the second example where action variable would = 'MSG' it does not compare.</p>
<p>And the most bizarre thing, when I use Telnet instead of my socket client both are being compare successfully. But the string are the same... Is there a possibility that the string are not encode in the same way? How can I know?</p>
<p>data example:</p>
<pre><code>data = 'IDENTIFY 54143'
or
data = 'MSG allo'
action = data.partition(' ')[0]
if action == "MSG":
self.sendMessage(data)
elif action == "IDENTIFY":
self.sendIdentify(data)
else:
print "false"
</code></pre>
| 1 | 2009-09-29T14:44:03Z | 1,493,039 | <p>Can't reproduce your problem. To debug it, print or log the <code>repr()</code> of <code>data</code> and <code>action</code>: this will likely show you the cause (probably some non-visible binary byte has snuck into <code>data</code>, based on how you obtained it [[which you don't show us]] and hence into <code>action</code>).</p>
| 5 | 2009-09-29T14:50:26Z | [
"python",
"string-comparison"
] |
Program new functionality for zoom button on Microsoft Natural Ergonomic Desktop 7000 | 1,493,202 | <p>I just bought a new keyboard and mouse (Microsoft Natural Ergonomic Desktop 7000) and it has a neat little zoom lever in the middle of the keyboard. What I'd like to do is write a little program (in C# or Python, for use on Windows Vista) which makes the zoom button act like a scroll button instead.</p>
<p>I have no idea where to start. Where do I start? :)</p>
| 1 | 2009-09-29T15:13:15Z | 1,493,412 | <p>This web page en comments should help you out a bit: <a href="http://oliiscool.blogspot.com/2006/11/hacking-microsoft-natural-ergonomic.html" rel="nofollow">Icool blog</a></p>
| 1 | 2009-09-29T15:47:44Z | [
"c#",
"python",
"keyboard",
"driver"
] |
Subclass of webapp.RequestHandler doesn't have a response attribute | 1,493,467 | <p>Using the below code, my template loads fine until I submit the from, then I get the following error:</p>
<pre><code>e = AttributeError("'ToDo' object has no attribute 'response'",)
</code></pre>
<p>Why doesn't my <code>ToDo</code> object not have a <code>response</code> attribute? It works the first time it's called.</p>
<pre><code>import cgi
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
class Task(db.Model):
description = db.StringProperty(required=True)
complete = db.BooleanProperty()
class ToDo(webapp.RequestHandler):
def get(self):
todo_query = Task.all()
todos = todo_query.fetch(10)
template_values = { 'todos': todos }
self.renderPage('index.html', template_values)
def renderPage(self, filename, values):
path = os.path.join(os.path.dirname(__file__), filename)
self.response.out.write(template.render(path, values))
class UpdateList(webapp.RequestHandler):
def post(self):
todo = ToDo()
todo.description = self.request.get('description')
todo.put()
self.redirect('/')
application = webapp.WSGIApplication(
[('/', ToDo),
('/add', UpdateList)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
</code></pre>
<p>Here's the template code so far, I'm just listing the descriptions for now.</p>
<pre><code><!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>ToDo tutorial</title>
</head>
<body>
<div>
{% for todo in todos %}
<em>{{ todo.description|escape }}</em>
{% endfor %}
</div>
<h3>Add item</h3>
<form action="/add" method="post">
<label for="description">Description:</label>
<input type="text" id="description" name="description" />
<input type="submit" value="Add Item" />
</form>
</body>
</html>
</code></pre>
| 0 | 2009-09-29T15:58:17Z | 1,493,607 | <p>why do you do what you do in <code>post</code>? it should be:</p>
<pre><code>def post(self):
task = Task() # not ToDo()
task.description = self.request.get('description')
task.put()
self.redirect('/')
</code></pre>
<p><code>put</code> called on a subclass of <code>webapp.RequestHandler</code> will <a href="http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html#RequestHandler%5Fput" rel="nofollow">try to handle PUT request, according to docs</a>.</p>
| 3 | 2009-09-29T16:24:22Z | [
"python",
"google-app-engine",
"post-redirect-get"
] |
Cannot access django app through ip address while accessing it through localhost | 1,493,479 | <p>I have a django app on my local computer. I can access the application from a browser by using the url: <a href="http://localhost:8000/myapp/">http://localhost:8000/myapp/</a></p>
<p>But I cannot access the application by using the ip of the host computer: <a href="http://193.140.209.49:8000/myapp/">http://193.140.209.49:8000/myapp/</a> I get a 404 error.</p>
<p>What should I do? Any suggestions?</p>
| 13 | 2009-09-29T16:00:31Z | 1,493,598 | <p>I assume you're using the development server. If so, then you need to specifically bind to your external IP for the server to be available there. Try this command:</p>
<pre><code>./manage.py runserver 193.140.209.49:8000
</code></pre>
| 47 | 2009-09-29T16:22:37Z | [
"python",
"django",
"networking"
] |
Embeddable Workflow/BPM Library For Python? | 1,493,550 | <p>Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world?</p>
| 7 | 2009-09-29T16:12:20Z | 1,493,731 | <p>Oh yes, tons. But most of them depend on a specific framework. DCWorkflow is integrated with Zopes CMF, for example. hurry.workflow is for Zope 3, etc. SpiffWorkflow presumes sql-alchemy, etc. This is because you need to have something to apply the workflow to, and that means you need to make some basic assumptions on the objects you use.</p>
<p>Hurry.workflow is probably one of the more independent ones, but it still assumes both that you use the Persistence library (and therefore in practice ZODB), and zope3's security model.</p>
<p>So you probably need to expand a bit on your requirements here...</p>
| 2 | 2009-09-29T16:50:21Z | [
"python",
"workflow",
"bpm"
] |
Embeddable Workflow/BPM Library For Python? | 1,493,550 | <p>Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world?</p>
| 7 | 2009-09-29T16:12:20Z | 1,927,875 | <p>Have you looked at this? <a href="http://code.djangoproject.com/wiki/GoFlow" rel="nofollow">http://code.djangoproject.com/wiki/GoFlow</a></p>
| 1 | 2009-12-18T12:12:08Z | [
"python",
"workflow",
"bpm"
] |
Regex find non digit and/or end of string | 1,493,871 | <p>How do I include an end-of-string and one non-digit characters in a python 2.6 regular expression set for searching?</p>
<p>I want to find 10-digit numbers with a non-digit at the beginning and a non-digit or end-of-string at the end. It is a 10-digit ISBN number and 'X' is valid for the final digit.</p>
<p>The following do not work:</p>
<pre><code>is10 = re.compile(r'\D(\d{9}[\d|X|x])[$|\D]')
is10 = re.compile(r'\D(\d{9}[\d|X|x])[\$|\D]')
is10 = re.compile(r'\D(\d{9}[\d|X|x])[\Z|\D]')
</code></pre>
<p>The problem arises with the last set: [\$|\D] to match a non-digit or end-of-string.</p>
<p>Test with:</p>
<pre><code>line = "abcd0123456789"
m = is10.search(line)
print m.group(1)
line = "abcd0123456789efg"
m = is10.search(line)
print m.group(1)
</code></pre>
| 2 | 2009-09-29T17:18:10Z | 1,493,900 | <p>You have to group the alternatives with parenthesis, not brackets:</p>
<pre><code>r'\D(\d{9}[\dXx])($|\D)'
</code></pre>
<p><code>|</code> is a different construct than <code>[]</code>. It marks an alternative between two patterns, while <code>[]</code> matches one of the contained characters. So <code>|</code> should only be used inside of <code>[]</code> if you want to match the actual character <code>|</code>. Grouping of parts of patterns is done with parenthesis, so these should be used to restrict the scope of the alternative marked by <code>|</code>.</p>
<p>If you want to avoid that this creates match groups, you can use <code>(?: )</code> instead:</p>
<pre><code>r'\D(\d{9}[\dXx])(?:$|\D)'
</code></pre>
| 4 | 2009-09-29T17:22:41Z | [
"python",
"regex"
] |
Regex find non digit and/or end of string | 1,493,871 | <p>How do I include an end-of-string and one non-digit characters in a python 2.6 regular expression set for searching?</p>
<p>I want to find 10-digit numbers with a non-digit at the beginning and a non-digit or end-of-string at the end. It is a 10-digit ISBN number and 'X' is valid for the final digit.</p>
<p>The following do not work:</p>
<pre><code>is10 = re.compile(r'\D(\d{9}[\d|X|x])[$|\D]')
is10 = re.compile(r'\D(\d{9}[\d|X|x])[\$|\D]')
is10 = re.compile(r'\D(\d{9}[\d|X|x])[\Z|\D]')
</code></pre>
<p>The problem arises with the last set: [\$|\D] to match a non-digit or end-of-string.</p>
<p>Test with:</p>
<pre><code>line = "abcd0123456789"
m = is10.search(line)
print m.group(1)
line = "abcd0123456789efg"
m = is10.search(line)
print m.group(1)
</code></pre>
| 2 | 2009-09-29T17:18:10Z | 1,493,929 | <pre><code>\D(\d{10})(?:\Z|\D)
</code></pre>
<p>find non-digit followed by 10 digits, and a single non-digit or a end-of-string. Captures only digits. While I see that you're searching for nine digit followed by digit or <code>X</code> or <code>x</code>, I don't see same thing in your requirements.</p>
| 0 | 2009-09-29T17:26:54Z | [
"python",
"regex"
] |
Django - accessing the RequestContext from within a custom filter | 1,493,874 | <p>I've got a filter <code>currency</code>, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take <code>RequestContext</code>, so I can't grab it straight from there.</p>
<p>Is there a better way than passing the relevant session element into the template, and from the template into the filter as an argument? Whilst this approach is working, it seems fairly horrible, and I'm likely to end up passing the currency to (almost) every template.</p>
<p>My filter currently looks something like this:</p>
<pre><code>def currency(value, currency):
if currency == 'usd':
val = '$%.2f' % value
return mark_safe(val)
d = Decimal(value)
val = '&pound;%.2f' % (d*Decimal('0.63'))
return mark_safe(val)
</code></pre>
| 14 | 2009-09-29T17:18:29Z | 1,494,009 | <p>If you create a template tag instead of a filter, you are given the context to work with (which contains the request). <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags">http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags</a></p>
| 7 | 2009-09-29T17:45:22Z | [
"python",
"django",
"django-templates"
] |
Django - accessing the RequestContext from within a custom filter | 1,493,874 | <p>I've got a filter <code>currency</code>, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take <code>RequestContext</code>, so I can't grab it straight from there.</p>
<p>Is there a better way than passing the relevant session element into the template, and from the template into the filter as an argument? Whilst this approach is working, it seems fairly horrible, and I'm likely to end up passing the currency to (almost) every template.</p>
<p>My filter currently looks something like this:</p>
<pre><code>def currency(value, currency):
if currency == 'usd':
val = '$%.2f' % value
return mark_safe(val)
d = Decimal(value)
val = '&pound;%.2f' % (d*Decimal('0.63'))
return mark_safe(val)
</code></pre>
| 14 | 2009-09-29T17:18:29Z | 1,511,457 | <p>This can be done using a filter. First make sure that you have <code>"django.core.context_processors.request"</code> in you <code>TEMPLATE_CONTEXT_PROCESSORS</code>. If you don't, you can add this to your settings.py file:</p>
<pre><code>TEMPLATE_CONTEXT_PROCESSORS += (
"django.core.context_processors.request"
)
</code></pre>
<p>Then in your template, your filter will look like this (assuming your session variable is named 'currency_type'):</p>
<pre><code>{{value|currency:request.session.currency_type}}
</code></pre>
<p>Or is something like this what you are considering fairly horrible?</p>
| 3 | 2009-10-02T19:49:20Z | [
"python",
"django",
"django-templates"
] |
Django - accessing the RequestContext from within a custom filter | 1,493,874 | <p>I've got a filter <code>currency</code>, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take <code>RequestContext</code>, so I can't grab it straight from there.</p>
<p>Is there a better way than passing the relevant session element into the template, and from the template into the filter as an argument? Whilst this approach is working, it seems fairly horrible, and I'm likely to end up passing the currency to (almost) every template.</p>
<p>My filter currently looks something like this:</p>
<pre><code>def currency(value, currency):
if currency == 'usd':
val = '$%.2f' % value
return mark_safe(val)
d = Decimal(value)
val = '&pound;%.2f' % (d*Decimal('0.63'))
return mark_safe(val)
</code></pre>
| 14 | 2009-09-29T17:18:29Z | 28,098,279 | <p>I would have to agree with Adam that migrating the code to a custom tag is the best way.</p>
<p>However, a client needed to record the use of certain filters only when a page was published and had a HUGE inventory of templates that used the existing filter syntax. It would have been a costly undertaking to rewrite all the templates. So, I came up with this simple function that extracts the context from the call stack:</p>
<p><a href="https://gist.github.com/drhoden/e05292e52fd5fc92cc3b" rel="nofollow">https://gist.github.com/drhoden/e05292e52fd5fc92cc3b</a></p>
<pre><code>def get_context(max_depth=4):
import inspect
stack = inspect.stack()[2:max_depth]
context = {}
for frame_info in stack:
frame = frame_info[0]
arg_info = inspect.getargvalues(frame)
if 'context' in arg_info.locals:
context = arg_info.locals['context']
break
return context
</code></pre>
<p>Be sure to read my warnings, but this DOES give standard filters access to the context (when it is available) WITHOUT having to turn your filter into a tag.</p>
| 0 | 2015-01-22T20:40:22Z | [
"python",
"django",
"django-templates"
] |
Django - accessing the RequestContext from within a custom filter | 1,493,874 | <p>I've got a filter <code>currency</code>, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take <code>RequestContext</code>, so I can't grab it straight from there.</p>
<p>Is there a better way than passing the relevant session element into the template, and from the template into the filter as an argument? Whilst this approach is working, it seems fairly horrible, and I'm likely to end up passing the currency to (almost) every template.</p>
<p>My filter currently looks something like this:</p>
<pre><code>def currency(value, currency):
if currency == 'usd':
val = '$%.2f' % value
return mark_safe(val)
d = Decimal(value)
val = '&pound;%.2f' % (d*Decimal('0.63'))
return mark_safe(val)
</code></pre>
| 14 | 2009-09-29T17:18:29Z | 28,581,108 | <p>A somehow less hacky solution to Daniel Rhoden's proposal is, to use <code>threading.local()</code>. Define a middleware class, which stores your <code>request</code> as a global object inside your local thread, and add that class to your <code>MIDDLEWARE_CLASSES</code>.</p>
<p>Now a template filter can easily access that request object.</p>
| 0 | 2015-02-18T10:20:15Z | [
"python",
"django",
"django-templates"
] |
Is there any Python XML parser that was designed with humans in mind? | 1,493,899 | <p>I like Python, but I don't want to write 10 lines just to get an attribute from an element. Maybe it's just me, but <code>minidom</code> isn't that <code>mini</code>. The code I have to write in order to parse something using it looks a lot like Java code.</p>
<p>Is there something that is more <code>user-friendly</code> ? Something with overloaded operators, and which maps elements to objects? </p>
<p>I'd like to be able to access this :</p>
<pre><code>
<root>
<node value="30">text</node>
</root>
</code></pre>
<p>as something like this :</p>
<pre><code>
obj = parse(xml_string)
print obj.node.value
</code></pre>
<p>and not using <code>getChildren</code> or some other methods like that. </p>
| 23 | 2009-09-29T17:22:34Z | 1,493,970 | <p>You should take a look at <a href="http://effbot.org/zone/element-index.htm">ElementTree</a>. It's not doing exactly what you want but it's a lot better then minidom. If I remember correctly, starting from python 2.4, it's included in the standard libraries. For more speed use cElementTree. For more more speed (and more features) you can use <a href="http://codespeak.net/lxml/">lxml</a> (check the objectify API for your needs/approach).</p>
<p>I should add that <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> do partly what you want. There's also <a href="http://uche.ogbuji.net/tech/4suite/amara/">Amara</a> that have this approach.</p>
| 22 | 2009-09-29T17:35:42Z | [
"python",
"xml",
"user-friendly"
] |
Is there any Python XML parser that was designed with humans in mind? | 1,493,899 | <p>I like Python, but I don't want to write 10 lines just to get an attribute from an element. Maybe it's just me, but <code>minidom</code> isn't that <code>mini</code>. The code I have to write in order to parse something using it looks a lot like Java code.</p>
<p>Is there something that is more <code>user-friendly</code> ? Something with overloaded operators, and which maps elements to objects? </p>
<p>I'd like to be able to access this :</p>
<pre><code>
<root>
<node value="30">text</node>
</root>
</code></pre>
<p>as something like this :</p>
<pre><code>
obj = parse(xml_string)
print obj.node.value
</code></pre>
<p>and not using <code>getChildren</code> or some other methods like that. </p>
| 23 | 2009-09-29T17:22:34Z | 1,494,188 | <p>I actually wrote a library that does things exactly the way you imagined it. The library is called "xe" and you can get it from: <a href="http://home.avvanta.com/~steveha/xe.html" rel="nofollow">http://home.avvanta.com/~steveha/xe.html</a></p>
<p>xe can import XML to let you work with the data in an object-oriented way. It actually uses xml.dom.minidom to do the parsing, but then it walks over the resulting tree and packs the data into xe objects.</p>
<p>EDIT: Okay, I went ahead and implemented your example in xe, so you can see how it works. Here are classes to implement the XML you showed:</p>
<pre><code>import xe
class Node(xe.TextElement):
def __init__(self, text="", value=None):
xe.TextElement.__init__(self, "node", text)
if value is not None:
self.attrs["value"] = value
class Root(xe.NestElement):
def __init__(self):
xe.NestElement.__init__(self, "root")
self.node = Node()
</code></pre>
<p>And here is an example of using the above. I put your sample XML into a file called "example.xml", but you could also just put it into a string and pass the string.</p>
<pre><code>>>> root = Root()
>>> print root
<root/>
>>> root.import_xml("example.xml")
<Root object at 0xb7e0c52c>
>>> print root
<root>
<node value="30">text</node>
</root>
>>> print root.node.attrs["value"]
30
>>>
</code></pre>
<p>Note that in this example, the type of "value" will be a string. If you really need attributes of another type, that's possible too with a little bit of work, but I didn't bother for this example. (If you look at PyFeed, there is a class for OPML that has an attribute that isn't text.)</p>
| 3 | 2009-09-29T18:32:14Z | [
"python",
"xml",
"user-friendly"
] |
Is there any Python XML parser that was designed with humans in mind? | 1,493,899 | <p>I like Python, but I don't want to write 10 lines just to get an attribute from an element. Maybe it's just me, but <code>minidom</code> isn't that <code>mini</code>. The code I have to write in order to parse something using it looks a lot like Java code.</p>
<p>Is there something that is more <code>user-friendly</code> ? Something with overloaded operators, and which maps elements to objects? </p>
<p>I'd like to be able to access this :</p>
<pre><code>
<root>
<node value="30">text</node>
</root>
</code></pre>
<p>as something like this :</p>
<pre><code>
obj = parse(xml_string)
print obj.node.value
</code></pre>
<p>and not using <code>getChildren</code> or some other methods like that. </p>
| 23 | 2009-09-29T17:22:34Z | 12,743,457 | <p>I had same need for simple xml parser and after a long time spent on checking different libraries I found <a href="http://www.aaronsw.com/2002/xmltramp/" rel="nofollow">xmltramp</a>.</p>
<p>Based on your example xml:
</p>
<pre><code>import xmltramp
xml_string = """<root>
<node value="30">text</node>
</root>"""
obj = xmltramp.parse(xml_string)
print obj.node('value') # 30
print str(obj.node) # text
</code></pre>
<p>I didn't found anything more user-friendly.</p>
| 2 | 2012-10-05T09:33:23Z | [
"python",
"xml",
"user-friendly"
] |
Is there any Python XML parser that was designed with humans in mind? | 1,493,899 | <p>I like Python, but I don't want to write 10 lines just to get an attribute from an element. Maybe it's just me, but <code>minidom</code> isn't that <code>mini</code>. The code I have to write in order to parse something using it looks a lot like Java code.</p>
<p>Is there something that is more <code>user-friendly</code> ? Something with overloaded operators, and which maps elements to objects? </p>
<p>I'd like to be able to access this :</p>
<pre><code>
<root>
<node value="30">text</node>
</root>
</code></pre>
<p>as something like this :</p>
<pre><code>
obj = parse(xml_string)
print obj.node.value
</code></pre>
<p>and not using <code>getChildren</code> or some other methods like that. </p>
| 23 | 2009-09-29T17:22:34Z | 20,976,225 | <p>I spent a fair bit of time going through the examples provided above and through the repositories listed on pip.</p>
<p>The easiest (and most Pythonic) way of parsing XML that I have found so far has been XMLToDict - <a href="https://github.com/martinblech/xmltodict" rel="nofollow">https://github.com/martinblech/xmltodict</a></p>
<p>The example from the documentation available at GitHub above is copy-pasted below; It's made life VERY simple and EASY for me a LOT of times;</p>
<pre><code>>>> doc = xmltodict.parse("""
... <mydocument has="an attribute">
... <and>
... <many>elements</many>
... <many>more elements</many>
... </and>
... <plus a="complex">
... element as well
... </plus>
... </mydocument>
... """)
>>>
>>> doc['mydocument']['@has']
u'an attribute'
>>> doc['mydocument']['and']['many']
[u'elements', u'more elements']
>>> doc['mydocument']['plus']['@a']
u'complex'
>>> doc['mydocument']['plus']['#text']
u'element as well'
</code></pre>
<p>It works really well and gave me just what I was looking for. However, if you're looking at reverse transformations, that is an entirely different matter altogether.</p>
| 0 | 2014-01-07T16:00:25Z | [
"python",
"xml",
"user-friendly"
] |
POSTing a complex JSON object using Prototype | 1,494,039 | <p>I'm using Prototype 1.6.1 to create an application under IIS, using ASP and Python.</p>
<p>The python is generating a complex JSON object. I want to pass this object to another page via an AJAX request, but the Prototype documentation is a little too cunning for me.</p>
<p>Can someone show me an example of how to create an Prototype AJAX.Request that POSTs a JSON object, and then just prints out "Ok, I got it" or something like that?</p>
<p>Vielen dank!</p>
| 1 | 2009-09-29T17:54:50Z | 1,494,095 | <pre><code>new Ajax.Request('/some_url',
{
method:"post",
postBody:"{'some':'json'}",
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
</code></pre>
| 7 | 2009-09-29T18:08:08Z | [
"javascript",
"python",
"iis",
"prototypejs"
] |
How to define [] for class in Python? | 1,494,146 | <p>I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to <code>def []=()</code> construct in ruby, so that calling Python <code>obj['foo']</code> would actually call some <code>[](self, what)</code> method. How can I do that?</p>
| 3 | 2009-09-29T18:22:17Z | 1,494,160 | <p>It's all in the docs: <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetitem%5F%5F" rel="nofollow"><code>__getitem__</code></a>.</p>
| 11 | 2009-09-29T18:25:51Z | [
"python"
] |
How to define [] for class in Python? | 1,494,146 | <p>I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to <code>def []=()</code> construct in ruby, so that calling Python <code>obj['foo']</code> would actually call some <code>[](self, what)</code> method. How can I do that?</p>
| 3 | 2009-09-29T18:22:17Z | 1,494,161 | <p>This is done with <code>__getitem___</code> in Python.</p>
<p>Here is a list of all the operators:
<a href="http://docs.python.org/library/operator.html" rel="nofollow">http://docs.python.org/library/operator.html</a></p>
| 7 | 2009-09-29T18:26:39Z | [
"python"
] |
How to define [] for class in Python? | 1,494,146 | <p>I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to <code>def []=()</code> construct in ruby, so that calling Python <code>obj['foo']</code> would actually call some <code>[](self, what)</code> method. How can I do that?</p>
| 3 | 2009-09-29T18:22:17Z | 1,494,172 | <p>define a method in your class with <code>__getitem__(key)</code> and <code>__setitem__(key, value)</code></p>
| 5 | 2009-09-29T18:28:13Z | [
"python"
] |
How to define [] for class in Python? | 1,494,146 | <p>I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to <code>def []=()</code> construct in ruby, so that calling Python <code>obj['foo']</code> would actually call some <code>[](self, what)</code> method. How can I do that?</p>
| 3 | 2009-09-29T18:22:17Z | 1,494,177 | <p><a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a></p>
<p>Section 3.4 in the above link shows you all or most of the operators you can overload in Python. The one you want to overload is</p>
<pre><code>__getitem__()
</code></pre>
| 4 | 2009-09-29T18:29:13Z | [
"python"
] |
How to get a timestamp older than 1901 | 1,494,231 | <p>I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).</p>
<p>Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?</p>
| 3 | 2009-09-29T18:41:33Z | 1,494,267 | <p>In python, there's the <a href="http://docs.python.org/library/datetime.html#date-objects" rel="nofollow">datetime module</a>. Specifically, the date class will help.</p>
<pre><code>from datetime import date
print date(1850, 1, 1).weekday() # 1, which is Tuesday
# (Mon is 0)
</code></pre>
<p><strong>Edit</strong></p>
<p>Or, to your specific problem, working with timedelta will help out.</p>
<pre><code>from datetime import datetime
td = datetime.now() - datetime(1850, 1, 1)
print (86400*td.days)+td.seconds # seconds since then till now
</code></pre>
| 4 | 2009-09-29T18:48:34Z | [
"javascript",
"c++",
"python",
"timestamp"
] |
How to get a timestamp older than 1901 | 1,494,231 | <p>I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).</p>
<p>Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?</p>
| 3 | 2009-09-29T18:41:33Z | 1,494,286 | <p>The portable, language-agnostic approach:</p>
<p>Step 1. Count the number of seconds between 01/01/1850 00:00 and 01/01/1901 00:00. Save this number somewhere (call it M)</p>
<p>Step 2. Use available language functionality to count the number of seconds between 01/01/1901 00:00 and whatever other date and time you want.</p>
<p>Step 3. Return the result from Step 2 + M. Remember to cast the result as a long integer if necessary.</p>
| 3 | 2009-09-29T18:52:09Z | [
"javascript",
"c++",
"python",
"timestamp"
] |
How to get a timestamp older than 1901 | 1,494,231 | <p>I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).</p>
<p>Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?</p>
| 3 | 2009-09-29T18:41:33Z | 1,494,464 | <p>Under WIN32, you can use <strong>SystemTimeToFileTime</strong>.</p>
<p><strong>FILETIME</strong> is a 64-bit unsigned integer that counts the number of 100-nanosecond intervals since January 1, 1601 (UTC).</p>
<p>You can convert two timestamps to FILETIME. You can convert it to ULARGE_INTEGER (t.dwLowDateTime + t.dwHighDateTime << 32), and do regular arithmetics to measure the interval.</p>
| 1 | 2009-09-29T19:27:34Z | [
"javascript",
"c++",
"python",
"timestamp"
] |
How to get a timestamp older than 1901 | 1,494,231 | <p>I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).</p>
<p>Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?</p>
| 3 | 2009-09-29T18:41:33Z | 1,495,334 | <p>Why not use <strong>Date</strong> objects instead of integers, at least to get a starting point.</p>
<pre><code>function secondsSince(D){
D= new Date(Date.parse(D));
D.setUTCHours(0,0,0,0);
return Math.floor((new Date()-D)/1000);
}
</code></pre>
<p>//test with a date</p>
<p>var daystring='Jan 1, 1850',
ss= secondsSince(daystring),
diff= ss/(60*60*24*365.25);</p>
<p>alert('It has been '+ ss +
' seconds since 00:00:00 (GMT) on ' + daystring +
'\n\nThat is about '+diff.toFixed(2)+' years.');</p>
| 0 | 2009-09-29T22:40:58Z | [
"javascript",
"c++",
"python",
"timestamp"
] |
How to get a timestamp older than 1901 | 1,494,231 | <p>I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).</p>
<p>Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?</p>
| 3 | 2009-09-29T18:41:33Z | 1,495,736 | <p>The egenix datetime is also worth looking at
<a href="http://www.egenix.com/products/python/mxBase/mxDateTime/" rel="nofollow">http://www.egenix.com/products/python/mxBase/mxDateTime/</a></p>
| 0 | 2009-09-30T01:33:41Z | [
"javascript",
"c++",
"python",
"timestamp"
] |
asn.1 parser in C/Python | 1,494,372 | <p>I am looking for a solution to parse asn.1 spec files and generate a decoder from those.</p>
<p>Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.</p>
<p>In the past I have been using pyasn1 and building everything by hand but that has become too unwieldly. </p>
<p>I have also looked superficially to libtasn1 and asn1c. The first one had problems parsing even the simplest of files. The second has a good parser but generating C code for decoding seems too complex; the solution worked well with straightforward specs but choked on complex ones. </p>
<p>Any other good alternatives I may have overlooked?</p>
| 10 | 2009-09-29T19:06:56Z | 1,494,480 | <p>There is an <a href="http://www.antlr.org/grammar/1231433381400/ASN.g" rel="nofollow">ANTLR ASN.1 grammar</a>; using ANTLR, you should be able to make an ASN.1 parser out of it. Generating code for pyasn1 is left as an exercise to the poster :-)</p>
| 2 | 2009-09-29T19:30:35Z | [
"python",
"c",
"parsing",
"asn.1"
] |
asn.1 parser in C/Python | 1,494,372 | <p>I am looking for a solution to parse asn.1 spec files and generate a decoder from those.</p>
<p>Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.</p>
<p>In the past I have been using pyasn1 and building everything by hand but that has become too unwieldly. </p>
<p>I have also looked superficially to libtasn1 and asn1c. The first one had problems parsing even the simplest of files. The second has a good parser but generating C code for decoding seems too complex; the solution worked well with straightforward specs but choked on complex ones. </p>
<p>Any other good alternatives I may have overlooked?</p>
| 10 | 2009-09-29T19:06:56Z | 1,494,811 | <p>Never tried them but:</p>
<ul>
<li><a href="http://asn1c.sourceforge.net/" rel="nofollow">asn1c</a></li>
<li><a href="http://svn.debian.org/wsvn/collab-maint/deb-maint/snacc/" rel="nofollow">snacc</a></li>
</ul>
<p>Both seems to do what you want (C, not Python).</p>
| 4 | 2009-09-29T20:40:49Z | [
"python",
"c",
"parsing",
"asn.1"
] |
asn.1 parser in C/Python | 1,494,372 | <p>I am looking for a solution to parse asn.1 spec files and generate a decoder from those.</p>
<p>Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.</p>
<p>In the past I have been using pyasn1 and building everything by hand but that has become too unwieldly. </p>
<p>I have also looked superficially to libtasn1 and asn1c. The first one had problems parsing even the simplest of files. The second has a good parser but generating C code for decoding seems too complex; the solution worked well with straightforward specs but choked on complex ones. </p>
<p>Any other good alternatives I may have overlooked?</p>
| 10 | 2009-09-29T19:06:56Z | 1,495,428 | <p>I have done a similar job using asn1c and building around it a Pyrex extension. The wrapped structure is described in <a href="http://www.3gpp.org/ftp/Specs/html-info/32401.htm" rel="nofollow">3GPP TS 32.401</a>.</p>
<p>With Pyrex you can write a wrapper thick enough to convert between native Python data types and the correct ASN.1 representations (wrapper generators, such SWIG, tend to not perform complex operations on the type). The wrapper I wrote also tracked the ownership of the underlying C data structures (e.g. accessing to a sub-structure, a Python object was returned, but there was no copy of the underlying data, only reference sharing).</p>
<p>The wrapper was eventually written in a kind of semi-automatic way, but because that has been my only job with ASN.1 I never did the step of completely automatize the code generation.</p>
<p>You can try to use other Python-C wrappers and perform a completely automatic conversion: the job would be less, but then you would move complexity (and repetitive error-prone operations) to the structure users: for this reason I preferred the Pyrex way. asn1c was definitely a good choice.</p>
| 1 | 2009-09-29T23:18:32Z | [
"python",
"c",
"parsing",
"asn.1"
] |
asn.1 parser in C/Python | 1,494,372 | <p>I am looking for a solution to parse asn.1 spec files and generate a decoder from those.</p>
<p>Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.</p>
<p>In the past I have been using pyasn1 and building everything by hand but that has become too unwieldly. </p>
<p>I have also looked superficially to libtasn1 and asn1c. The first one had problems parsing even the simplest of files. The second has a good parser but generating C code for decoding seems too complex; the solution worked well with straightforward specs but choked on complex ones. </p>
<p>Any other good alternatives I may have overlooked?</p>
| 10 | 2009-09-29T19:06:56Z | 1,496,061 | <p>I have experience with <a href="http://pyasn1.sourceforge.net/" rel="nofollow">pyasn1</a> and it's enough to parse quite complex grammars. A grammar is expressed with python structure, so no need to run code generator.</p>
| 2 | 2009-09-30T04:00:19Z | [
"python",
"c",
"parsing",
"asn.1"
] |
asn.1 parser in C/Python | 1,494,372 | <p>I am looking for a solution to parse asn.1 spec files and generate a decoder from those.</p>
<p>Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.</p>
<p>In the past I have been using pyasn1 and building everything by hand but that has become too unwieldly. </p>
<p>I have also looked superficially to libtasn1 and asn1c. The first one had problems parsing even the simplest of files. The second has a good parser but generating C code for decoding seems too complex; the solution worked well with straightforward specs but choked on complex ones. </p>
<p>Any other good alternatives I may have overlooked?</p>
| 10 | 2009-09-29T19:06:56Z | 1,497,694 | <p>I'm the author of LEPL, a parser written in Python, and what you want to do is one of the things on my "TODO" list.</p>
<p>I will not be doing this soon, but you might consider using LEPL to construct your solution because:</p>
<p>1 - it's a pure Python solution (which makes life simpler)</p>
<p>2 - it can already parse binary data as well as text, so you would only need to use a single tool - the same parser that you would use to parse the ASN1 spec would then be used to parse the binary data</p>
<p>The main downsides are that:</p>
<p>1 - it's a fairly new package, so it may be buggier than some, and the support community is not that large</p>
<p>2 - it is restricted to Python 2.6 and up (and the binary parser only works with Python 3 and up).</p>
<p>For more information, please see <a href="http://www.acooke.org/lepl" rel="nofollow">http://www.acooke.org/lepl</a> - in particular,for binary parsing see the relevant section of the manual (I cannot link directly to that as Stack Overflow seems to think I am spamming)</p>
<p>Andrew</p>
<p>PS The main reason this is not something I have already started is that the ASN 1 specs are not freely available, as far as I know. If you have access to them, and it is not illegal(!), a copy would be greatly appreciated (unfortunately I am currently working on another project, so this would still take time to implement, but it would help me get this working sooner...).</p>
| 2 | 2009-09-30T12:01:58Z | [
"python",
"c",
"parsing",
"asn.1"
] |
asn.1 parser in C/Python | 1,494,372 | <p>I am looking for a solution to parse asn.1 spec files and generate a decoder from those.</p>
<p>Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.</p>
<p>In the past I have been using pyasn1 and building everything by hand but that has become too unwieldly. </p>
<p>I have also looked superficially to libtasn1 and asn1c. The first one had problems parsing even the simplest of files. The second has a good parser but generating C code for decoding seems too complex; the solution worked well with straightforward specs but choked on complex ones. </p>
<p>Any other good alternatives I may have overlooked?</p>
| 10 | 2009-09-29T19:06:56Z | 3,006,715 | <p>I wrote such parser a few years ago. It generates python classes for pyasn1 library. I used in on ericsson doc to make parser for their CDRs.</p>
<p>I'll try posting the code here now.</p>
<pre><code>import sys
from pyparsing import *
OpenBracket = Regex("[({]").suppress()
CloseBracket = Regex("[)}]").suppress()
def Enclose(val):
return OpenBracket + val + CloseBracket
def SetDefType(typekw):
def f(a, b, c):
c["defType"] = typekw
return f
def NoDashes(a, b, c):
return c[0].replace("-", "_")
def DefineTypeDef(typekw, typename, typedef):
return typename.addParseAction(SetDefType(typekw)).setResultsName("definitionType") - \
Optional(Enclose(typedef).setResultsName("definition"))
SizeConstraintBodyOpt = Word(nums).setResultsName("minSize") - \
Optional(Suppress(Literal("..")) - Word(nums + "n").setResultsName("maxSize"))
SizeConstraint = Group(Keyword("SIZE").suppress() - Enclose(SizeConstraintBodyOpt)).setResultsName("sizeConstraint")
Constraints = Group(delimitedList(SizeConstraint)).setResultsName("constraints")
DefinitionBody = Forward()
TagPrefix = Enclose(Word(nums).setResultsName("tagID")) - Keyword("IMPLICIT").setResultsName("tagFormat")
OptionalSuffix = Optional(Keyword("OPTIONAL").setResultsName("isOptional"))
JunkPrefix = Optional("--F--").suppress()
AName = Word(alphanums + "-").setParseAction(NoDashes).setResultsName("name")
SingleElement = Group(JunkPrefix - AName - Optional(TagPrefix) - DefinitionBody.setResultsName("typedef") - OptionalSuffix)
NamedTypes = Dict(delimitedList(SingleElement)).setResultsName("namedTypes")
SetBody = DefineTypeDef("Set", Keyword("SET"), NamedTypes)
SequenceBody = DefineTypeDef("Sequence", Keyword("SEQUENCE"), NamedTypes)
ChoiceBody = DefineTypeDef("Choice", Keyword("CHOICE"), NamedTypes)
SetOfBody = (Keyword("SET") + Optional(SizeConstraint) + Keyword("OF")).setParseAction(SetDefType("SetOf")) + Group(DefinitionBody).setResultsName("typedef")
SequenceOfBody = (Keyword("SEQUENCE") + Optional(SizeConstraint) + Keyword("OF")).setParseAction(SetDefType("SequenceOf")) + Group(DefinitionBody).setResultsName("typedef")
CustomBody = DefineTypeDef("constructed", Word(alphanums + "-").setParseAction(NoDashes), Constraints)
NullBody = DefineTypeDef("Null", Keyword("NULL"), Constraints)
OctetStringBody = DefineTypeDef("OctetString", Regex("OCTET STRING"), Constraints)
IA5StringBody = DefineTypeDef("IA5String", Keyword("IA5STRING"), Constraints)
EnumElement = Group(Word(printables).setResultsName("name") - Enclose(Word(nums).setResultsName("value")))
NamedValues = Dict(delimitedList(EnumElement)).setResultsName("namedValues")
EnumBody = DefineTypeDef("Enum", Keyword("ENUMERATED"), NamedValues)
BitStringBody = DefineTypeDef("BitString", Keyword("BIT") + Keyword("STRING"), NamedValues)
DefinitionBody << (OctetStringBody | SetOfBody | SetBody | ChoiceBody | SequenceOfBody | SequenceBody | EnumBody | BitStringBody | IA5StringBody | NullBody | CustomBody)
Definition = AName - Literal("::=").suppress() - Optional(TagPrefix) - DefinitionBody
Definitions = Dict(ZeroOrMore(Group(Definition)))
pf = Definitions.parseFile(sys.argv[1])
TypeDeps = {}
TypeDefs = {}
def SizeConstraintHelper(size):
s2 = s1 = size.get("minSize")
s2 = size.get("maxSize", s2)
try:
return("constraint.ValueSizeConstraint(%s, %s)" % (int(s1), int(s2)))
except ValueError:
pass
ConstraintMap = {
'sizeConstraint' : SizeConstraintHelper,
}
def ConstraintHelper(c):
result = []
for key, value in c.items():
r = ConstraintMap[key](value)
if r:
result.append(r)
return result
def GenerateConstraints(c, ancestor, element, level=1):
result = ConstraintHelper(c)
if result:
return [ "subtypeSpec = %s" % " + ".join(["%s.subtypeSpec" % ancestor] + result) ]
return []
def GenerateNamedValues(definitions, ancestor, element, level=1):
result = [ "namedValues = namedval.NamedValues(" ]
for kw in definitions:
result.append(" ('%s', %s)," % (kw["name"], kw["value"]))
result.append(")")
return result
OptMap = {
False: "",
True: "Optional",
}
def GenerateNamedTypesList(definitions, element, level=1):
result = []
for val in definitions:
name = val["name"]
typename = None
isOptional = bool(val.get("isOptional"))
subtype = []
constraints = val.get("constraints")
if constraints:
cg = ConstraintHelper(constraints)
subtype.append("subtypeSpec=%s" % " + ".join(cg))
tagId = val.get("tagID")
if tagId:
subtype.append("implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, %s)" % tagId)
if subtype:
subtype = ".subtype(%s)" % ", ".join(subtype)
else:
subtype = ""
cbody = []
if val["defType"] == "constructed":
typename = val["typedef"]
element["_d"].append(typename)
elif val["defType"] == "Null":
typename = "univ.Null"
elif val["defType"] == "SequenceOf":
typename = "univ.SequenceOf"
print val.items()
cbody = [ " componentType=%s()" % val["typedef"]["definitionType"] ]
elif val["defType"] == "Choice":
typename = "univ.Choice"
indef = val.get("definition")
if indef:
cbody = [ " %s" % x for x in GenerateClassDefinition(indef, name, typename, element) ]
construct = [ "namedtype.%sNamedType('%s', %s(" % (OptMap[isOptional], name, typename), ")%s)," % subtype ]
if not cbody:
result.append("%s%s%s" % (" " * level, construct[0], construct[1]))
else:
result.append(" %s" % construct[0])
result.extend(cbody)
result.append(" %s" % construct[1])
return result
def GenerateNamedTypes(definitions, ancestor, element, level=1):
result = [ "componentType = namedtype.NamedTypes(" ]
result.extend(GenerateNamedTypesList(definitions, element))
result.append(")")
return result
defmap = {
'constraints' : GenerateConstraints,
'namedValues' : GenerateNamedValues,
'namedTypes' : GenerateNamedTypes,
}
def GenerateClassDefinition(definition, name, ancestor, element, level=1):
result = []
for defkey, defval in definition.items():
if defval:
fn = defmap.get(defkey)
if fn:
result.extend(fn(defval, ancestor, element, level))
return [" %s" % x for x in result]
def GenerateClass(element, ancestor):
name = element["name"]
top = "class %s(%s):" % (name, ancestor)
definition = element.get("definition")
body = []
if definition:
body = GenerateClassDefinition(definition, name, ancestor, element)
else:
typedef = element.get("typedef")
if typedef:
element["_d"].append(typedef["definitionType"])
body.append(" componentType = %s()" % typedef["definitionType"])
szc = element.get('sizeConstraint')
if szc:
body.extend(GenerateConstraints({ 'sizeConstraint' : szc }, ancestor, element))
if not body:
body.append(" pass")
TypeDeps[name] = list(frozenset(element["_d"]))
return "\n".join([top] + body)
StaticMap = {
"Null" : "univ.Null",
"Enum" : "univ.Enumerated",
"OctetString" : "univ.OctetString",
"IA5String" : "char.IA5String",
"Set" : "univ.Set",
"Sequence" : "univ.Sequence",
"Choice" : "univ.Choice",
"SetOf" : "univ.SetOf",
"BitString" : "univ.BitString",
"SequenceOf" : "univ.SequenceOf",
}
def StaticConstructor(x):
x["_d"] = []
if x["defType"] == "constructed":
dt = x["definitionType"]
x["_d"].append(dt)
else:
dt = StaticMap[x["defType"]]
return GenerateClass(x, dt)
for element in pf:
TypeDefs[element["name"]] = StaticConstructor(element)
while TypeDefs:
ready = [ k for k, v in TypeDeps.items() if len(v) == 0 ]
if not ready:
x = list()
for a in TypeDeps.values():
x.extend(a)
x = frozenset(x) - frozenset(TypeDeps.keys())
print TypeDefs
raise ValueError, sorted(x)
for t in ready:
for v in TypeDeps.values():
try:
v.remove(t)
except ValueError:
pass
del TypeDeps[t]
print TypeDefs[t]
print
print
del TypeDefs[t]
</code></pre>
<p>This will take a file with syntax, similar to this one:</p>
<pre><code>CarrierInfo ::= OCTET STRING (SIZE(2..3))
ChargeAreaCode ::= OCTET STRING (SIZE(3))
ChargeInformation ::= OCTET STRING (SIZE(2..33))
ChargedParty ::= ENUMERATED
(chargingOfCallingSubscriber (0),
chargingOfCalledSubscriber (1),
noCharging (2))
ChargingOrigin ::= OCTET STRING (SIZE(1))
Counter ::= OCTET STRING (SIZE(1..4))
Date ::= OCTET STRING (SIZE(3..4))
</code></pre>
<p>You will need to add this line on top of the generated file:</p>
<pre><code>from pyasn1.type import univ, namedtype, namedval, constraint, tag, char
</code></pre>
<p>And name the result defs.py. Then, I attached a bunch of prettyprinters to the defs (if you don't have just skip it)</p>
<pre><code>import defs, parsers
def rplPrettyOut(self, value):
return repr(self.decval(value))
for name in dir(parsers):
if (not name.startswith("_")) and hasattr(defs, name):
target = getattr(defs, name)
target.prettyOut = rplPrettyOut
target.decval = getattr(parsers, name)
</code></pre>
<p>Then, it's down to:</p>
<pre><code> def ParseBlock(self, block):
while block and block[0] != '\x00':
result, block = pyasn1.codec.ber.decoder.decode(block, asn1Spec=parserimp.defs.CallDataRecord())
yield result
</code></pre>
<p>If you're still interested I'll put the code somewhere. In fact, I'll put it somewhere in any case - but if you're interested just let me know and I'll point you there.</p>
| 11 | 2010-06-09T14:20:12Z | [
"python",
"c",
"parsing",
"asn.1"
] |
General Command pattern and Command Dispatch pattern in Python | 1,494,442 | <p>I was looking for a <em>Command</em> pattern implementation in Python...
(According to <a href="http://en.wikipedia.org/wiki/Command%5Fpattern">Wikipedia</a>, </p>
<blockquote>
<p>the command pattern is a design
pattern in which an object is used to
represent and encapsulate all the
information needed to call a method at
a later time.</p>
</blockquote>
<p>)</p>
<p>The only thing I found was Command Dispatch <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#command-dispatch-pattern">pattern</a>:</p>
<pre><code>class Dispatcher:
def do_get(self): ...
def do_put(self): ...
def error(self): ...
def dispatch(self, command):
mname = 'do_' + command
if hasattr(self, mname):
method = getattr(self, mname)
method()
else:
self.error()
</code></pre>
<p>May be I'm wrong, but it looks like these are two different concepts, which accidentally have similar names.</p>
<p>Am i missing something?</p>
| 19 | 2009-09-29T19:23:23Z | 1,494,455 | <p>Yes, you do miss something: the command pattern is only necessary in languages that don't have function pointers (or functions as first class objects), such as Java. In languages with functions-as-objects, you can use the function itself; no need to have a separate command object (which then should have a "doit" method).</p>
<p>In the example could you quote, the <code>getattr()</code> call gives you the "command object" (i.e. the bound method); adding parenthesis after it "invokes" (i.e. calls) the command object.</p>
| 2 | 2009-09-29T19:26:13Z | [
"python",
"design-patterns",
"oop"
] |
General Command pattern and Command Dispatch pattern in Python | 1,494,442 | <p>I was looking for a <em>Command</em> pattern implementation in Python...
(According to <a href="http://en.wikipedia.org/wiki/Command%5Fpattern">Wikipedia</a>, </p>
<blockquote>
<p>the command pattern is a design
pattern in which an object is used to
represent and encapsulate all the
information needed to call a method at
a later time.</p>
</blockquote>
<p>)</p>
<p>The only thing I found was Command Dispatch <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#command-dispatch-pattern">pattern</a>:</p>
<pre><code>class Dispatcher:
def do_get(self): ...
def do_put(self): ...
def error(self): ...
def dispatch(self, command):
mname = 'do_' + command
if hasattr(self, mname):
method = getattr(self, mname)
method()
else:
self.error()
</code></pre>
<p>May be I'm wrong, but it looks like these are two different concepts, which accidentally have similar names.</p>
<p>Am i missing something?</p>
| 19 | 2009-09-29T19:23:23Z | 1,494,501 | <p>Did some searching and found this. It appears to do the job of encapsulating an action.</p>
<pre><code>def demo(a,b,c):
print 'a:',a
print 'b:',b
print 'c:',c
class Command:
def __init__(self, cmd, *args):
self._cmd=cmd
self._args=args
def __call__(self, *args):
return apply(self._cmd, self._args+args)
cmd=Command(dir,__builtins__)
print cmd()
cmd=Command(demo,1,2)
cmd(3)
</code></pre>
| 3 | 2009-09-29T19:36:45Z | [
"python",
"design-patterns",
"oop"
] |
General Command pattern and Command Dispatch pattern in Python | 1,494,442 | <p>I was looking for a <em>Command</em> pattern implementation in Python...
(According to <a href="http://en.wikipedia.org/wiki/Command%5Fpattern">Wikipedia</a>, </p>
<blockquote>
<p>the command pattern is a design
pattern in which an object is used to
represent and encapsulate all the
information needed to call a method at
a later time.</p>
</blockquote>
<p>)</p>
<p>The only thing I found was Command Dispatch <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#command-dispatch-pattern">pattern</a>:</p>
<pre><code>class Dispatcher:
def do_get(self): ...
def do_put(self): ...
def error(self): ...
def dispatch(self, command):
mname = 'do_' + command
if hasattr(self, mname):
method = getattr(self, mname)
method()
else:
self.error()
</code></pre>
<p>May be I'm wrong, but it looks like these are two different concepts, which accidentally have similar names.</p>
<p>Am i missing something?</p>
| 19 | 2009-09-29T19:23:23Z | 1,494,510 | <p>If I recall the gang of four correctly, the Command pattern is about commands like "File - Save", not commands like "svn commit", which is what your code is good for.</p>
<p>Martin suggests the Command pattern is unneeded because functions as first class objects take its place, but the Command pattern is richer than just <code>doit()</code>, having, for example, also <code>undo()</code>, <code>is_enabled()</code>, etc.</p>
| 2 | 2009-09-29T19:39:20Z | [
"python",
"design-patterns",
"oop"
] |
General Command pattern and Command Dispatch pattern in Python | 1,494,442 | <p>I was looking for a <em>Command</em> pattern implementation in Python...
(According to <a href="http://en.wikipedia.org/wiki/Command%5Fpattern">Wikipedia</a>, </p>
<blockquote>
<p>the command pattern is a design
pattern in which an object is used to
represent and encapsulate all the
information needed to call a method at
a later time.</p>
</blockquote>
<p>)</p>
<p>The only thing I found was Command Dispatch <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#command-dispatch-pattern">pattern</a>:</p>
<pre><code>class Dispatcher:
def do_get(self): ...
def do_put(self): ...
def error(self): ...
def dispatch(self, command):
mname = 'do_' + command
if hasattr(self, mname):
method = getattr(self, mname)
method()
else:
self.error()
</code></pre>
<p>May be I'm wrong, but it looks like these are two different concepts, which accidentally have similar names.</p>
<p>Am i missing something?</p>
| 19 | 2009-09-29T19:23:23Z | 1,494,532 | <p>The simplest command pattern is already built into Python, simply use a callable:</p>
<pre><code>def greet(who):
print "Hello %s" % who
greet_command = lambda: greet("World")
# pass the callable around, and invoke it later
greet_command()
</code></pre>
<p>The command pattern as an object oriented design pattern makes more sense if your commands need to be able to do more than just be invoked. Common usecase is when you need to be able to undo/redo your actions. Then a command class is a good way to couple the forward and backwards actions together. For example:</p>
<pre><code>class MoveFileCommand(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
os.rename(self.src, self.dest)
def undo(self):
os.rename(self.dest, self.src)
undo_stack = []
undo_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
undo_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))
# foo.txt is now renamed to baz.txt
undo_stack.pop().undo() # Now it's bar.txt
undo_stack.pop().undo() # and back to foo.txt
</code></pre>
| 47 | 2009-09-29T19:44:04Z | [
"python",
"design-patterns",
"oop"
] |
Separate Admin/User authentication system in Django | 1,494,524 | <p>I've recently started learning/using django; I'm trying to figure out a way to have two separate authentications systems for administrators and users. Rather than create a whole new auth system, I'd like to leverage django's built-in functionality (i.e. session management, @login_required decorator, etc.). </p>
<p>Specifically, I want to have <strong>two separate login tables</strong> - one for admins, one for users. The admin login table should be the default table that django generates with its default fields (ie. <code>id, username, email, is_staff, etc.</code>). The user table, on the other hand, I want to have <strong>only 5 fields</strong> - <code>id, email, password, first_name, last_name</code>. Furthermore, I want to use django built-in session management for both login tables and the @login_required decorator for their respective views. Lastly, I want two separate and distinct login forms for admins and users. </p>
<p>Anyone have any suggestions on how I can achieve my goal or know of any articles/examples that could help me along?</p>
| 5 | 2009-09-29T19:41:26Z | 1,494,572 | <p>Modify things slightly so that users have a category prefix on their username? You haven't given us much info on what you want to do, it's possible that your needs might be met by using the sites framework, or simply two separate django installs.</p>
<p>If what you're trying to do is make the user login page and the admin login page separate, just use the built in framework as detailed in the docs to create a "user" login page and leave the admin one alone. If you're worried that users will somehow start editing admin login stuff, don't be, they won't unless you let them. </p>
| 0 | 2009-09-29T19:53:29Z | [
"python",
"django",
"authentication"
] |
Separate Admin/User authentication system in Django | 1,494,524 | <p>I've recently started learning/using django; I'm trying to figure out a way to have two separate authentications systems for administrators and users. Rather than create a whole new auth system, I'd like to leverage django's built-in functionality (i.e. session management, @login_required decorator, etc.). </p>
<p>Specifically, I want to have <strong>two separate login tables</strong> - one for admins, one for users. The admin login table should be the default table that django generates with its default fields (ie. <code>id, username, email, is_staff, etc.</code>). The user table, on the other hand, I want to have <strong>only 5 fields</strong> - <code>id, email, password, first_name, last_name</code>. Furthermore, I want to use django built-in session management for both login tables and the @login_required decorator for their respective views. Lastly, I want two separate and distinct login forms for admins and users. </p>
<p>Anyone have any suggestions on how I can achieve my goal or know of any articles/examples that could help me along?</p>
| 5 | 2009-09-29T19:41:26Z | 1,494,779 | <p>You could potentially write one or more custom authentication backends. This is documented <a href="http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend" rel="nofollow">here</a>. I have written a custom backend to authenticate against an LDAP server, for example.</p>
| 1 | 2009-09-29T20:33:29Z | [
"python",
"django",
"authentication"
] |
Separate Admin/User authentication system in Django | 1,494,524 | <p>I've recently started learning/using django; I'm trying to figure out a way to have two separate authentications systems for administrators and users. Rather than create a whole new auth system, I'd like to leverage django's built-in functionality (i.e. session management, @login_required decorator, etc.). </p>
<p>Specifically, I want to have <strong>two separate login tables</strong> - one for admins, one for users. The admin login table should be the default table that django generates with its default fields (ie. <code>id, username, email, is_staff, etc.</code>). The user table, on the other hand, I want to have <strong>only 5 fields</strong> - <code>id, email, password, first_name, last_name</code>. Furthermore, I want to use django built-in session management for both login tables and the @login_required decorator for their respective views. Lastly, I want two separate and distinct login forms for admins and users. </p>
<p>Anyone have any suggestions on how I can achieve my goal or know of any articles/examples that could help me along?</p>
| 5 | 2009-09-29T19:41:26Z | 1,494,848 | <p>If I understand your question correctly (and perhaps I don't), I think you're asking how to create a separate login form for non-admin users, while still using the standard Django authentication mechanisms, <code>User</code> model, etc. This is supported natively by Django through views in <code>django.contrib.auth.views</code>.</p>
<p>You want to start with <code>django.contrib.auth.views.login</code>. Add a line to your urlconf like so:</p>
<pre><code>(r'^/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'})
</code></pre>
<p>The <code>login</code> generic view accepts the <code>template_name</code> parameter, which is the path to your custom login template (there is a generic one you can use as well, provided by <code>django.contrib.auth</code>).</p>
<p>Full documentation on the <code>login</code>, <code>logout</code>, <code>password_change</code>, and other generic views are available in the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login" rel="nofollow">Django Authentication Docs</a>.</p>
| 1 | 2009-09-29T20:46:42Z | [
"python",
"django",
"authentication"
] |
Are Python's bools passed by value? | 1,494,696 | <p>I sent a reference to a bool object, and I modified it within a method. After the method finished it's execution, the value of the bool outside the method was unchanged.</p>
<p>This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way?</p>
| 5 | 2009-09-29T20:17:19Z | 1,494,722 | <p>It depends on whether the object is mutable or immutable. Immutable objects behave like you saw with the bool, whereas mutable objects will change.</p>
<p>For reference: <a href="http://www.testingreflections.com/node/view/5126" rel="nofollow">http://www.testingreflections.com/node/view/5126</a></p>
<blockquote>
<p>Python passes references-to-objects by value (like Java), and everything in Python is an object. This sounds simple, but then you will notice that some data types seem to exhibit pass-by-value characteristics, while others seem to act like pass-by-reference... what's the deal?</p>
<p>It is important to understand mutable and immutable objects. Some objects, like strings, tuples, and numbers, are immutable. Altering them inside a function/method will create a new instance and the original instance outside the function/method is not changed. Other objects, like lists and dictionaries are mutable, which means you can change the object in-place. Therefore, altering an object inside a function/method will also change the original object outside. </p>
</blockquote>
| 1 | 2009-09-29T20:22:06Z | [
"python",
"boolean",
"pass-by-value"
] |
Are Python's bools passed by value? | 1,494,696 | <p>I sent a reference to a bool object, and I modified it within a method. After the method finished it's execution, the value of the bool outside the method was unchanged.</p>
<p>This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way?</p>
| 5 | 2009-09-29T20:17:19Z | 1,494,728 | <p>Python variables are not "references" in the C++ sense. Rather, they are simply local names bound to an object at some arbitrary location in memory. If that object is itself mutable, changes to it will be visible in other scopes that have bound a name to the object. Many primitive types (including <code>bool</code>, <code>int</code>, <code>str</code>, and <code>tuple</code>) are <em>immutable</em> however. You cannot change their value in-place; rather, you assign a new value to the same name in your local scope.</p>
<p>In fact, almost any time* you see code of the form <code>foo = X</code>, it means that the name <code>foo</code> is being assigned a new value (<code>X</code>) within your current local namespace, not that a location in memory named by <code>foo</code> is having its internal pointer updated to refer instead to the location of <code>X</code>.</p>
<p>*- the only exception to this in Python is setter methods for properties, which may allow you to write <code>obj.foo = X</code> and have it rewritten in the background to instead call a method like <code>obj.setFoo(X)</code>.</p>
| 12 | 2009-09-29T20:23:48Z | [
"python",
"boolean",
"pass-by-value"
] |
Are Python's bools passed by value? | 1,494,696 | <p>I sent a reference to a bool object, and I modified it within a method. After the method finished it's execution, the value of the bool outside the method was unchanged.</p>
<p>This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way?</p>
| 5 | 2009-09-29T20:17:19Z | 1,494,730 | <p>In short, <em>there are no variables in Python</em>; there are objects (Like True and False, the bools happen to be immutable), and names. Names are what you call variables, but names belong to a scope, you can't normally change names other than the local names.</p>
| 0 | 2009-09-29T20:24:08Z | [
"python",
"boolean",
"pass-by-value"
] |
Are Python's bools passed by value? | 1,494,696 | <p>I sent a reference to a bool object, and I modified it within a method. After the method finished it's execution, the value of the bool outside the method was unchanged.</p>
<p>This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way?</p>
| 5 | 2009-09-29T20:17:19Z | 1,495,889 | <p>The thing to remember is that there is <em>no</em> way in Python for a function or a method to rebind a name in the calling namespace. When you write "I sent a reference to a bool object, and I modified it within a method", what you actually did (I am guessing) was to rebind the parameter name (to which the bool value was bound by the call) inside the method body.</p>
| 1 | 2009-09-30T02:51:58Z | [
"python",
"boolean",
"pass-by-value"
] |
Percentage with variable precision | 1,494,708 | <p>I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters.</p>
<p>How can I write this in Python? The <code>"%.8f"</code> string formatting works decently, but I need to keep the last three characters after the last string of nines.</p>
<p>So:<br />
54.8213% -> 54.821%<br />
95.42332% -> 95.423%<br />
99.9932983% -> 99.99330%<br />
99.99999999992318 -> 99.9999999999232%</p>
| 0 | 2009-09-29T20:19:32Z | 1,494,759 | <p>Try this:</p>
<pre><code>def print_percent(p):
for i in range(30):
if p <= 100. - 10.**(-i):
print ("%." + str(max(3,3+i-1)) + "f") % p
return
</code></pre>
<p>or this if you just want to retrieve the string</p>
<pre><code>def print_percent(p):
for i in range(20):
if p <= 100. - 10.**(-i):
return ("%." + str(max(3,3+i-1)) + "f") % p
</code></pre>
| 0 | 2009-09-29T20:29:03Z | [
"python",
"algorithm",
"precision"
] |
Percentage with variable precision | 1,494,708 | <p>I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters.</p>
<p>How can I write this in Python? The <code>"%.8f"</code> string formatting works decently, but I need to keep the last three characters after the last string of nines.</p>
<p>So:<br />
54.8213% -> 54.821%<br />
95.42332% -> 95.423%<br />
99.9932983% -> 99.99330%<br />
99.99999999992318 -> 99.9999999999232%</p>
| 0 | 2009-09-29T20:19:32Z | 1,494,770 | <p>I am quite confident that this is not possible with standard formating. I suggest to use something like the following (C# like pseudo code). Especially I suggest to rely on string operations and not to use math code because of many possible precision and rounding problems.</p>
<pre><code>string numberString = number.ToStringWithFullPrecision();
int index = numberString.IndexOf('.');
while ((index < numberString.Length - 1) && (numberString[index + 1] == '9'))
{
index++;
}
WriteLine(number.PadRightWithThreeZeros().SubString(0, index + 4));
</code></pre>
<p>If you like regular expression, you can use them to. Take the following expression and match it against the full precision number string padded with three zeros and you are done.</p>
<pre><code>^([0-9]|[1-9][0-9]|100)\.(9*)([0-8][0-9]{2})
</code></pre>
<p><hr /></p>
<p>I just realized that both suggestion may cause rounding errors. <code>99.91238123</code> becomes <code>99.9123</code> when it should become <code>99.9124</code> - so the last digits requires additional correction. Easy to do, but makes my suggestion even uglier. This is far away from an elegant and smart algorithm.</p>
| 0 | 2009-09-29T20:31:52Z | [
"python",
"algorithm",
"precision"
] |
Percentage with variable precision | 1,494,708 | <p>I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters.</p>
<p>How can I write this in Python? The <code>"%.8f"</code> string formatting works decently, but I need to keep the last three characters after the last string of nines.</p>
<p>So:<br />
54.8213% -> 54.821%<br />
95.42332% -> 95.423%<br />
99.9932983% -> 99.99330%<br />
99.99999999992318 -> 99.9999999999232%</p>
| 0 | 2009-09-29T20:19:32Z | 1,494,778 | <pre><code>def ceilpowerof10(x):
return math.pow(10, math.ceil(math.log10(x)))
def nines(x):
return -int(math.log10(ceilpowerof10(x) - x))
def threeplaces(x):
return ('%.' + str(nines(x) + 3) + 'f') % x
</code></pre>
<p>Note that nines() throws an error on numbers that are a power of 10 to begin with, it would take a little more work to make it safe for all input. There are probably some issues with negative numbers as well.</p>
| 1 | 2009-09-29T20:32:52Z | [
"python",
"algorithm",
"precision"
] |
Percentage with variable precision | 1,494,708 | <p>I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters.</p>
<p>How can I write this in Python? The <code>"%.8f"</code> string formatting works decently, but I need to keep the last three characters after the last string of nines.</p>
<p>So:<br />
54.8213% -> 54.821%<br />
95.42332% -> 95.423%<br />
99.9932983% -> 99.99330%<br />
99.99999999992318 -> 99.9999999999232%</p>
| 0 | 2009-09-29T20:19:32Z | 1,494,850 | <p>Try this:</p>
<pre><code>import math
def format_percentage(x, precision=3):
return ("%%.%df%%%%" % (precision - min(0,math.log10(100-x)))) % x
</code></pre>
| 3 | 2009-09-29T20:47:25Z | [
"python",
"algorithm",
"precision"
] |
Percentage with variable precision | 1,494,708 | <p>I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters.</p>
<p>How can I write this in Python? The <code>"%.8f"</code> string formatting works decently, but I need to keep the last three characters after the last string of nines.</p>
<p>So:<br />
54.8213% -> 54.821%<br />
95.42332% -> 95.423%<br />
99.9932983% -> 99.99330%<br />
99.99999999992318 -> 99.9999999999232%</p>
| 0 | 2009-09-29T20:19:32Z | 1,495,094 | <pre><code> def ilike9s(f):
return re.sub(r"(\d*\.9*\d\d\d)\d*",r"\1","%.17f" % f)
</code></pre>
<p><hr /></p>
<p>So...</p>
<pre><code>>>> ilike9s(1.0)
'1.000'
>>> ilike9s(12.9999991232132132)
'12.999999123'
>>> ilike9s(12.345678901234)
'12.345'
</code></pre>
<p>And don't forget to <code>import re</code></p>
| 0 | 2009-09-29T21:35:57Z | [
"python",
"algorithm",
"precision"
] |
Percentage with variable precision | 1,494,708 | <p>I would like to display a percentage with three decimal places unless it's greater than 99%. Then, I'd like to display the number with all the available nines plus 3 non-nine characters.</p>
<p>How can I write this in Python? The <code>"%.8f"</code> string formatting works decently, but I need to keep the last three characters after the last string of nines.</p>
<p>So:<br />
54.8213% -> 54.821%<br />
95.42332% -> 95.423%<br />
99.9932983% -> 99.99330%<br />
99.99999999992318 -> 99.9999999999232%</p>
| 0 | 2009-09-29T20:19:32Z | 1,495,175 | <p>Mark Ransom's answer is a beautiful thing. With a little bit of work, it can solve the problem for any inputs. I went ahead and did the little bit of work.</p>
<p>You just need to add some code to nines():</p>
<pre><code>def nines(x):
x = abs(x) # avoid exception caused if x is negative
x -= int(x) # keep fractional part of x only
cx = ceilpowerof10(x) - x
if 0 == cx:
return 0 # if x is a power of 10, it doesn't have a string of 9's!
return -int(math.log10(cx))
</code></pre>
<p>Then threeplaces() works for anything. Here are a few test cases:</p>
<pre><code>>>> threeplaces(0.9999357)
'0.9999357'
>>> threeplaces(1000.9999357)
'1000.9999357'
>>> threeplaces(-1000.9999357)
'-1000.9999357'
>>> threeplaces(0.9900357)
'0.99004'
>>> threeplaces(1000.9900357)
'1000.99004'
>>> threeplaces(-1000.9900357)
'-1000.99004'
</code></pre>
| 2 | 2009-09-29T21:58:24Z | [
"python",
"algorithm",
"precision"
] |
http checks python | 1,495,367 | <p>learning python here, I want to check if anybody is running a web server on my local
network, using this code, but it gives me a lot of error in the concole.</p>
<pre><code>#!/usr/bin/env python
import httplib
last = 1
while last <> 255:
url = "10.1.1." + "last"
connection = httplib.HTTPConnection("url", 80)
connection.request("GET","/")
response = connection.getresponse()
print (response.status)
last = last + 1
</code></pre>
| 3 | 2009-09-29T22:52:31Z | 1,495,378 | <p>Remove the quotes from the variable names <code>last</code> and <code>url</code>. Python is interpreting them as strings rather than variables. Try this:</p>
<pre><code>#!/usr/bin/env python
import httplib
last = 1
while last <> 255:
url = "10.1.1.%d" % last
connection = httplib.HTTPConnection(url, 80)
connection.request("GET","/")
response = connection.getresponse()
print (response.status)
last = last + 1
</code></pre>
| 1 | 2009-09-29T22:59:52Z | [
"python",
"http"
] |
http checks python | 1,495,367 | <p>learning python here, I want to check if anybody is running a web server on my local
network, using this code, but it gives me a lot of error in the concole.</p>
<pre><code>#!/usr/bin/env python
import httplib
last = 1
while last <> 255:
url = "10.1.1." + "last"
connection = httplib.HTTPConnection("url", 80)
connection.request("GET","/")
response = connection.getresponse()
print (response.status)
last = last + 1
</code></pre>
| 3 | 2009-09-29T22:52:31Z | 1,495,379 | <p>You're trying to connect to an url that is <strong>literally</strong> the string <code>'url'</code>: that's what the quotes you're using in </p>
<pre><code> connection = httplib.HTTPConnection("url", 80)
</code></pre>
<p><strong>mean</strong>. Once you remedy that (by removing those quotes) you'll be trying to connect to "10.1.1.last", given the quotes in the <em>previous</em> line. Set that line to</p>
<pre><code> url = "10.1.1." + str(last)
</code></pre>
<p>and it could work!-)</p>
| 1 | 2009-09-29T23:00:17Z | [
"python",
"http"
] |
http checks python | 1,495,367 | <p>learning python here, I want to check if anybody is running a web server on my local
network, using this code, but it gives me a lot of error in the concole.</p>
<pre><code>#!/usr/bin/env python
import httplib
last = 1
while last <> 255:
url = "10.1.1." + "last"
connection = httplib.HTTPConnection("url", 80)
connection.request("GET","/")
response = connection.getresponse()
print (response.status)
last = last + 1
</code></pre>
| 3 | 2009-09-29T22:52:31Z | 1,495,480 | <p>I do suggest changing the while loop to the more idiomatic for loop, and handling exceptions:</p>
<pre><code>#!/usr/bin/env python
import httplib
import socket
for i in range(1, 256):
try:
url = "10.1.1.%d" % i
connection = httplib.HTTPConnection(url, 80)
connection.request("GET","/")
response = connection.getresponse()
print url + ":", response.status
except socket.error:
print url + ":", "error!"
</code></pre>
<p>To see how to add a timeout to this, so it doesn't take so long to check each server, see <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/ff84e7340988c168/">here</a>.</p>
| 5 | 2009-09-29T23:39:05Z | [
"python",
"http"
] |
http checks python | 1,495,367 | <p>learning python here, I want to check if anybody is running a web server on my local
network, using this code, but it gives me a lot of error in the concole.</p>
<pre><code>#!/usr/bin/env python
import httplib
last = 1
while last <> 255:
url = "10.1.1." + "last"
connection = httplib.HTTPConnection("url", 80)
connection.request("GET","/")
response = connection.getresponse()
print (response.status)
last = last + 1
</code></pre>
| 3 | 2009-09-29T22:52:31Z | 1,500,046 | <p>as pointed out, you have some basic
quotation issues. but more fundamentally:</p>
<ol>
<li>you're not using Pythonesque
constructs to handle things but
you're coding them as simple
imperative code. that's fine, of course, but below are examples of funner (and better) ways to express things</li>
<li>you need to explicitly set timeouts or it'll
take forever</li>
<li>you need to multithread or it'll take forever</li>
<li>you need to handle various common exception types or your code will crash: connections will fail (including
time out) under numerous conditions
against real web servers</li>
<li>10.1.1.* is only one possible set of "local" servers. RFC 1918 spells out that
the "local" ranges are 10.0.0.0 - 10.255.255.255, 172.16.0.0 - 172.31.255.255, and
192.168.0.0 - 192.168.255.255. the problem of
generic detection of responders in
your "local" network is a hard one</li>
<li>web servers (especially local
ones) often run on other ports than
80 (notably on 8000, 8001, or 8080)</li>
<li>the complexity of general
web servers, dns, etc is such that
you can get various timeout
behaviors at different times (and affected by recent operations)</li>
</ol>
<p>below, some sample code to get you started, that pretty much addresses all of
the above problems except (5), which i'll assume is (well) beyond
the scope of the question.</p>
<p>btw i'm printing the size of the returned web page, since it's a simple
"signature" of what the page is. the sample IPs return various Yahoo
assets.</p>
<pre><code>import urllib
import threading
import socket
def t_run(thread_list, chunks):
t_count = len(thread_list)
print "Running %s jobs in groups of %s threads" % (t_count, chunks)
for x in range(t_count / chunks + 1):
i = x * chunks
i_c = min(i + chunks, t_count)
c = len([t.start() for t in thread_list[i:i_c]])
print "Started %s threads for jobs %s...%s" % (c, i, i_c - 1)
c = len([t.join() for t in thread_list[i:i_c]])
print "Finished %s threads for job index %s" % (c, i)
def url_scan(ip_base, timeout=5):
socket.setdefaulttimeout(timeout)
def f(url):
# print "-- Trying (%s)" % url
try:
# the print will only complete if there's a server there
r = urllib.urlopen(url)
if r:
print "## (%s) got %s bytes" % (url, len(r.read()))
else:
print "## (%s) failed to connect" % url
except IOError, msg:
# these are just the common cases
if str(msg)=="[Errno socket error] timed out":
return
if str(msg)=="[Errno socket error] (10061, 'Connection refused')":
return
print "## (%s) got error '%s'" % (url, msg)
# you might want 8000 and 8001, too
return [threading.Thread(target=f,
args=("http://" + ip_base + str(x) + ":" + str(p),))
for x in range(255) for p in [80, 8080]]
# run them (increase chunk size depending on your memory)
# also, try different timeouts
t_run(url_scan("209.131.36."), 100)
t_run(url_scan("209.131.36.", 30), 100)
</code></pre>
| 2 | 2009-09-30T19:01:05Z | [
"python",
"http"
] |
Is there any python library for parsing dates and times from a natural language? | 1,495,487 | <p>What I'm looking for is something that can translate 'tomorrow at 6am' or 'next moday at noon' to the appropriate datetime objects.</p>
| 26 | 2009-09-29T23:43:41Z | 1,495,548 | <p><a href="https://github.com/bear/parsedatetime">parsedatetime</a> - <em>Python module that is able to parse 'human readable' date/time expressions.</em></p>
<pre><code>#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime
cal = pdt.Calendar()
now = datetime.now()
print("now: %s" % now)
for time_string in ["tomorrow at 6am", "next moday at noon",
"2 min ago", "3 weeks ago", "1 month ago"]:
print("%s:\t%s" % (time_string, cal.parseDT(time_string, now)[0]))
</code></pre>
<h3>Output</h3>
<pre><code>now: 2015-10-18 13:55:29.732131
tomorrow at 6am: 2015-10-19 06:00:00
next moday at noon: 2015-10-18 12:00:00
2 min ago: 2015-10-18 13:53:29
3 weeks ago: 2015-09-27 13:55:29
1 month ago: 2015-09-18 13:55:29
</code></pre>
| 34 | 2009-09-30T00:06:17Z | [
"python",
"parsing"
] |
Is there any python library for parsing dates and times from a natural language? | 1,495,487 | <p>What I'm looking for is something that can translate 'tomorrow at 6am' or 'next moday at noon' to the appropriate datetime objects.</p>
| 26 | 2009-09-29T23:43:41Z | 1,496,032 | <p>See what you think of <a href="http://pyparsing.wikispaces.com/UnderDevelopment#toc0">this example</a> from the pyparsing wiki. It handles the following test cases:</p>
<pre><code>today
tomorrow
yesterday
in a couple of days
a couple of days from now
a couple of days from today
in a day
3 days ago
3 days from now
a day ago
now
10 minutes ago
10 minutes from now
in 10 minutes
in a minute
in a couple of minutes
20 seconds ago
in 30 seconds
20 seconds before noon
20 seconds before noon tomorrow
noon
midnight
noon tomorrow
6am tomorrow
0800 yesterday
12:15 AM today
3pm 2 days from today
a week from today
a week from now
3 weeks ago
noon next Sunday
noon Sunday
noon last Sunday
</code></pre>
| 10 | 2009-09-30T03:48:08Z | [
"python",
"parsing"
] |
Combining Dictionaries Of Lists In Python | 1,495,510 | <p>I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.</p>
<p>Example: </p>
<pre><code>Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
</code></pre>
<p>Furthermore, I would like to efficiently combine these dictionaries.</p>
<p>Example: </p>
<pre><code>Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
</code></pre>
<p>These operations reside within an inner loop, so I would prefer that they be as fast as possible.</p>
<p>Thanks in advance</p>
| 10 | 2009-09-29T23:54:01Z | 1,495,552 | <p>defaltdict to the rescue (as usual)</p>
<pre><code>from collections import defaultdict
my_dict = defaultdict(list)
for key,value in original_list:
my_dict[key].append(value)
</code></pre>
<p>Combining the two dicts can be done like this (note that duplicates will be preserved):</p>
<pre><code>for key,value in orig_dict:
new_dict[key].extend(value)
</code></pre>
| 3 | 2009-09-30T00:09:15Z | [
"python",
"list",
"dictionary"
] |
Combining Dictionaries Of Lists In Python | 1,495,510 | <p>I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.</p>
<p>Example: </p>
<pre><code>Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
</code></pre>
<p>Furthermore, I would like to efficiently combine these dictionaries.</p>
<p>Example: </p>
<pre><code>Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
</code></pre>
<p>These operations reside within an inner loop, so I would prefer that they be as fast as possible.</p>
<p>Thanks in advance</p>
| 10 | 2009-09-29T23:54:01Z | 1,495,562 | <p><a href="http://docs.python.org/3.1/library/collections.html#defaultdict-objects" rel="nofollow"><code>collections.defaultdict</code></a> works like this:</p>
<pre><code>from collections import defaultdict
dic = defaultdict(list)
for i, j in tuples:
dic[i].append(j)
</code></pre>
<p>similar for the dicts:</p>
<pre><code>a, b = {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
de = defaultdict(list, a)
for i, j in b.items():
de[i].extend(j)
</code></pre>
| 3 | 2009-09-30T00:12:36Z | [
"python",
"list",
"dictionary"
] |
Combining Dictionaries Of Lists In Python | 1,495,510 | <p>I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.</p>
<p>Example: </p>
<pre><code>Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
</code></pre>
<p>Furthermore, I would like to efficiently combine these dictionaries.</p>
<p>Example: </p>
<pre><code>Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
</code></pre>
<p>These operations reside within an inner loop, so I would prefer that they be as fast as possible.</p>
<p>Thanks in advance</p>
| 10 | 2009-09-29T23:54:01Z | 1,495,730 | <p>Here is the iterator style of doing it</p>
<pre>
>>> mylist=[(1, 2), (1, 3), (2, 3)]
>>> from itertools import groupby
>>> from operator import itemgetter
>>> mylist=[(1, 2), (1, 3), (2, 3)]
>>> groupby(mylist,itemgetter(0))
>>> list(_)
[(1, <itertools._grouper object at 0xb7d402ec>), (2, <itertools._grouper object at 0xb7c716ec>)]
</pre>
| 0 | 2009-09-30T01:29:55Z | [
"python",
"list",
"dictionary"
] |
Combining Dictionaries Of Lists In Python | 1,495,510 | <p>I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.</p>
<p>Example: </p>
<pre><code>Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
</code></pre>
<p>Furthermore, I would like to efficiently combine these dictionaries.</p>
<p>Example: </p>
<pre><code>Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
</code></pre>
<p>These operations reside within an inner loop, so I would prefer that they be as fast as possible.</p>
<p>Thanks in advance</p>
| 10 | 2009-09-29T23:54:01Z | 1,495,821 | <p>If the list of tuples is sorted, <code>itertools.groupby</code>, as suggested by @gnibbler, is not a bad alternative to <code>defaultdict</code>, but it needs to be used differently than he suggested:</p>
<pre><code>import itertools
import operator
def lot_to_dict(lot):
key = operator.itemgetter(0)
# if lot's not sorted, you also need...:
# lot = sorted(lot, key=key)
# NOT in-place lot.sort to avoid changing it!
grob = itertools.groupby(lot, key)
return dict((k, [v[1] for v in itr]) for k, itr in grob)
</code></pre>
<p>For "merging" dicts of lists into a new d.o.l...:</p>
<pre><code>def merge_dols(dol1, dol2):
keys = set(dol1).union(dol2)
no = []
return dict((k, dol1.get(k, no) + dol2.get(k, no)) for k in keys)
</code></pre>
<p>I'm giving <code>[]</code> a nickname <code>no</code> to avoid uselessly constructing a lot of empty lists, given that performance is important. If the sets of the dols' keys overlap only modestly, faster would be:</p>
<pre><code>def merge_dols(dol1, dol2):
result = dict(dol1, **dol2)
result.update((k, dol1[k] + dol2[k])
for k in set(dol1).intersection(dol2))
return result
</code></pre>
<p>since this uses list-catenation only for overlapping keys -- so, if those are few, it will be faster.</p>
| 9 | 2009-09-30T02:17:58Z | [
"python",
"list",
"dictionary"
] |
Combining Dictionaries Of Lists In Python | 1,495,510 | <p>I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.</p>
<p>Example: </p>
<pre><code>Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
</code></pre>
<p>Furthermore, I would like to efficiently combine these dictionaries.</p>
<p>Example: </p>
<pre><code>Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
</code></pre>
<p>These operations reside within an inner loop, so I would prefer that they be as fast as possible.</p>
<p>Thanks in advance</p>
| 10 | 2009-09-29T23:54:01Z | 1,496,094 | <p>I wanted these done in <strong>one line</strong> just for fun:</p>
<pre><code>>>> from itertools import groupby
>>> t=(1, 2), (1, 3), (2, 3)
>>> [(i,[x for _,x in list(f)]) for i,f in groupby(sorted(t),lambda t: t[0])]
[(1, [2, 3]), (2, [3])]
>>> b={1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
>>> dict([(key,sum([i[1::][0] for i in elements],[])) for key,elements in groupby(sorted(b[0].items()+b[1].items()),lambda t: t[0])])
{1: [2, 3, 4], 2: [3], 3: [1]}
</code></pre>
| 0 | 2009-09-30T04:18:17Z | [
"python",
"list",
"dictionary"
] |
Combining Dictionaries Of Lists In Python | 1,495,510 | <p>I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.</p>
<p>Example: </p>
<pre><code>Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
</code></pre>
<p>Furthermore, I would like to efficiently combine these dictionaries.</p>
<p>Example: </p>
<pre><code>Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}
</code></pre>
<p>These operations reside within an inner loop, so I would prefer that they be as fast as possible.</p>
<p>Thanks in advance</p>
| 10 | 2009-09-29T23:54:01Z | 9,815,938 | <p>This is how I do it in Python 2.7:</p>
<pre><code>combined = {}
combined.update(d1)
combined.update(d2)
</code></pre>
<p>It is good to define a utility function to do this:</p>
<pre><code>def merge(d1, d2):
''' Merge two dictionaries. '''
merged = {}
merged.update(d1)
merged.update(d2)
return merged
</code></pre>
| 0 | 2012-03-22T03:15:08Z | [
"python",
"list",
"dictionary"
] |
How to download any(!) webpage with correct charset in python? | 1,495,627 | <h1>Problem</h1>
<p><strong>When screen-scraping a webpage using python one has to know the character encoding of the page.</strong> If you get the character encoding wrong than your output will be messed up.</p>
<p>People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an <a href="http://chardet.feedparser.org/">encoding detector</a> (which does not care about meta tags or headers).
By using only one these techniques, sometimes you will not get the same result as you would in a browser.</p>
<p>Browsers do it this way:</p>
<ul>
<li>Meta tags always takes precedence (or xml definition)</li>
<li>Encoding defined in the header is used when there is no charset defined in a meta tag</li>
<li>If the encoding is not defined at all, than it is time for encoding detection.</li>
</ul>
<p>(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)</p>
<p><strong>What I'm looking for is a library that can decide the character set of a page the way a browser would.</strong> I'm sure I'm not the first who needs a proper solution to this problem.</p>
<h1>Solution <em>(I have not tried it yet...)</em></h1>
<p>According to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup's documentation</a>.</p>
<p>Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:</p>
<ul>
<li>An encoding you pass in as the
fromEncoding argument to the soup
constructor.</li>
<li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li>
<li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected
at this stage, it will be one of the
UTF-* encodings, EBCDIC, or ASCII.</li>
<li>An
encoding sniffed by the chardet
library, if you have it installed.</li>
<li>UTF-8</li>
<li>Windows-1252</li>
</ul>
| 28 | 2009-09-30T00:41:59Z | 1,495,631 | <p>Use the <a href="http://pypi.python.org/pypi/chardet">Universal Encoding Detector</a>:</p>
<pre><code>>>> import chardet
>>> chardet.detect(urlread("http://google.cn/"))
{'encoding': 'GB2312', 'confidence': 0.99}
</code></pre>
<p>The other option would be to just use wget:</p>
<pre><code> import os
h = os.popen('wget -q -O foo1.txt http://foo.html')
h.close()
s = open('foo1.txt').read()
</code></pre>
| 13 | 2009-09-30T00:44:15Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] |
How to download any(!) webpage with correct charset in python? | 1,495,627 | <h1>Problem</h1>
<p><strong>When screen-scraping a webpage using python one has to know the character encoding of the page.</strong> If you get the character encoding wrong than your output will be messed up.</p>
<p>People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an <a href="http://chardet.feedparser.org/">encoding detector</a> (which does not care about meta tags or headers).
By using only one these techniques, sometimes you will not get the same result as you would in a browser.</p>
<p>Browsers do it this way:</p>
<ul>
<li>Meta tags always takes precedence (or xml definition)</li>
<li>Encoding defined in the header is used when there is no charset defined in a meta tag</li>
<li>If the encoding is not defined at all, than it is time for encoding detection.</li>
</ul>
<p>(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)</p>
<p><strong>What I'm looking for is a library that can decide the character set of a page the way a browser would.</strong> I'm sure I'm not the first who needs a proper solution to this problem.</p>
<h1>Solution <em>(I have not tried it yet...)</em></h1>
<p>According to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup's documentation</a>.</p>
<p>Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:</p>
<ul>
<li>An encoding you pass in as the
fromEncoding argument to the soup
constructor.</li>
<li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li>
<li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected
at this stage, it will be one of the
UTF-* encodings, EBCDIC, or ASCII.</li>
<li>An
encoding sniffed by the chardet
library, if you have it installed.</li>
<li>UTF-8</li>
<li>Windows-1252</li>
</ul>
| 28 | 2009-09-30T00:41:59Z | 1,495,675 | <p>When you download a file with urllib or urllib2, you can find out whether a charset header was transmitted:</p>
<pre><code>fp = urllib2.urlopen(request)
charset = fp.headers.getparam('charset')
</code></pre>
<p>You can use BeautifulSoup to locate a meta element in the HTML:</p>
<pre><code>soup = BeatifulSoup.BeautifulSoup(data)
meta = soup.findAll('meta', {'http-equiv':lambda v:v.lower()=='content-type'})
</code></pre>
<p>If neither is available, browsers typically fall back to user configuration, combined with auto-detection. As rajax proposes, you could use the chardet module. If you have user configuration available telling you that the page should be Chinese (say), you may be able to do better.</p>
| 32 | 2009-09-30T01:04:36Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] |
How to download any(!) webpage with correct charset in python? | 1,495,627 | <h1>Problem</h1>
<p><strong>When screen-scraping a webpage using python one has to know the character encoding of the page.</strong> If you get the character encoding wrong than your output will be messed up.</p>
<p>People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an <a href="http://chardet.feedparser.org/">encoding detector</a> (which does not care about meta tags or headers).
By using only one these techniques, sometimes you will not get the same result as you would in a browser.</p>
<p>Browsers do it this way:</p>
<ul>
<li>Meta tags always takes precedence (or xml definition)</li>
<li>Encoding defined in the header is used when there is no charset defined in a meta tag</li>
<li>If the encoding is not defined at all, than it is time for encoding detection.</li>
</ul>
<p>(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)</p>
<p><strong>What I'm looking for is a library that can decide the character set of a page the way a browser would.</strong> I'm sure I'm not the first who needs a proper solution to this problem.</p>
<h1>Solution <em>(I have not tried it yet...)</em></h1>
<p>According to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup's documentation</a>.</p>
<p>Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:</p>
<ul>
<li>An encoding you pass in as the
fromEncoding argument to the soup
constructor.</li>
<li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li>
<li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected
at this stage, it will be one of the
UTF-* encodings, EBCDIC, or ASCII.</li>
<li>An
encoding sniffed by the chardet
library, if you have it installed.</li>
<li>UTF-8</li>
<li>Windows-1252</li>
</ul>
| 28 | 2009-09-30T00:41:59Z | 1,499,920 | <p>instead of trying to get a page then figuring out the charset the browser would use, why not just use a browser to fetch the page and check what charset it uses.. </p>
<pre><code>from win32com.client import DispatchWithEvents
import threading
stopEvent=threading.Event()
class EventHandler(object):
def OnDownloadBegin(self):
pass
def waitUntilReady(ie):
"""
copypasted from
http://mail.python.org/pipermail/python-win32/2004-June/002040.html
"""
if ie.ReadyState!=4:
while 1:
print "waiting"
pythoncom.PumpWaitingMessages()
stopEvent.wait(.2)
if stopEvent.isSet() or ie.ReadyState==4:
stopEvent.clear()
break;
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://kskky.info')
waitUntilReady(ie)
d = ie.Document
print d.CharSet
</code></pre>
| 1 | 2009-09-30T18:37:16Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] |
How to download any(!) webpage with correct charset in python? | 1,495,627 | <h1>Problem</h1>
<p><strong>When screen-scraping a webpage using python one has to know the character encoding of the page.</strong> If you get the character encoding wrong than your output will be messed up.</p>
<p>People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an <a href="http://chardet.feedparser.org/">encoding detector</a> (which does not care about meta tags or headers).
By using only one these techniques, sometimes you will not get the same result as you would in a browser.</p>
<p>Browsers do it this way:</p>
<ul>
<li>Meta tags always takes precedence (or xml definition)</li>
<li>Encoding defined in the header is used when there is no charset defined in a meta tag</li>
<li>If the encoding is not defined at all, than it is time for encoding detection.</li>
</ul>
<p>(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)</p>
<p><strong>What I'm looking for is a library that can decide the character set of a page the way a browser would.</strong> I'm sure I'm not the first who needs a proper solution to this problem.</p>
<h1>Solution <em>(I have not tried it yet...)</em></h1>
<p>According to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup's documentation</a>.</p>
<p>Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:</p>
<ul>
<li>An encoding you pass in as the
fromEncoding argument to the soup
constructor.</li>
<li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li>
<li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected
at this stage, it will be one of the
UTF-* encodings, EBCDIC, or ASCII.</li>
<li>An
encoding sniffed by the chardet
library, if you have it installed.</li>
<li>UTF-8</li>
<li>Windows-1252</li>
</ul>
| 28 | 2009-09-30T00:41:59Z | 1,544,836 | <p>It seems like you need a hybrid of the answers presented:</p>
<ol>
<li>Fetch the page using urllib</li>
<li>Find <code><meta></code> tags using beautiful soup or other method</li>
<li>If no meta tags exist, check the headers returned by urllib</li>
<li>If that still doesn't give you an answer, use the universal encoding detector.</li>
</ol>
<p>I honestly don't believe you're going to find anything better than that. </p>
<p>In fact if you read further into the FAQ you linked to in the comments on the other answer, that's what the author of detector library advocates.</p>
<p>If you believe the FAQ, this is what the browsers do (as requested in your original question) as the detector is a port of the firefox sniffing code.</p>
| 3 | 2009-10-09T16:34:22Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] |
How to download any(!) webpage with correct charset in python? | 1,495,627 | <h1>Problem</h1>
<p><strong>When screen-scraping a webpage using python one has to know the character encoding of the page.</strong> If you get the character encoding wrong than your output will be messed up.</p>
<p>People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an <a href="http://chardet.feedparser.org/">encoding detector</a> (which does not care about meta tags or headers).
By using only one these techniques, sometimes you will not get the same result as you would in a browser.</p>
<p>Browsers do it this way:</p>
<ul>
<li>Meta tags always takes precedence (or xml definition)</li>
<li>Encoding defined in the header is used when there is no charset defined in a meta tag</li>
<li>If the encoding is not defined at all, than it is time for encoding detection.</li>
</ul>
<p>(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)</p>
<p><strong>What I'm looking for is a library that can decide the character set of a page the way a browser would.</strong> I'm sure I'm not the first who needs a proper solution to this problem.</p>
<h1>Solution <em>(I have not tried it yet...)</em></h1>
<p>According to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup's documentation</a>.</p>
<p>Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:</p>
<ul>
<li>An encoding you pass in as the
fromEncoding argument to the soup
constructor.</li>
<li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li>
<li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected
at this stage, it will be one of the
UTF-* encodings, EBCDIC, or ASCII.</li>
<li>An
encoding sniffed by the chardet
library, if you have it installed.</li>
<li>UTF-8</li>
<li>Windows-1252</li>
</ul>
| 28 | 2009-09-30T00:41:59Z | 9,756,911 | <p>BeautifulSoup dose this with UnicodeDammit : <a href="http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit" rel="nofollow">Unicode, Dammit</a></p>
| 1 | 2012-03-18T08:05:33Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] |
How to download any(!) webpage with correct charset in python? | 1,495,627 | <h1>Problem</h1>
<p><strong>When screen-scraping a webpage using python one has to know the character encoding of the page.</strong> If you get the character encoding wrong than your output will be messed up.</p>
<p>People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an <a href="http://chardet.feedparser.org/">encoding detector</a> (which does not care about meta tags or headers).
By using only one these techniques, sometimes you will not get the same result as you would in a browser.</p>
<p>Browsers do it this way:</p>
<ul>
<li>Meta tags always takes precedence (or xml definition)</li>
<li>Encoding defined in the header is used when there is no charset defined in a meta tag</li>
<li>If the encoding is not defined at all, than it is time for encoding detection.</li>
</ul>
<p>(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)</p>
<p><strong>What I'm looking for is a library that can decide the character set of a page the way a browser would.</strong> I'm sure I'm not the first who needs a proper solution to this problem.</p>
<h1>Solution <em>(I have not tried it yet...)</em></h1>
<p>According to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup's documentation</a>.</p>
<p>Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:</p>
<ul>
<li>An encoding you pass in as the
fromEncoding argument to the soup
constructor.</li>
<li>An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.</li>
<li>An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected
at this stage, it will be one of the
UTF-* encodings, EBCDIC, or ASCII.</li>
<li>An
encoding sniffed by the chardet
library, if you have it installed.</li>
<li>UTF-8</li>
<li>Windows-1252</li>
</ul>
| 28 | 2009-09-30T00:41:59Z | 15,481,982 | <p>I would use <a href="https://code.google.com/p/html5lib/" rel="nofollow">html5lib</a> for this.</p>
| 3 | 2013-03-18T16:31:10Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] |
How to define a class in Python | 1,495,666 | <p>Quite simple, I'm learning python and I can't find a reference that tells me how to write the following:</p>
<pre><code>public class Team {
private String name;
private String logo;
private int members;
public Team(){}
// getters/setters
}
</code></pre>
<p>Later:</p>
<pre><code>Team team = new Team();
team.setName( "Oscar" );
team.setLogo( "http://...." );
team.setMembers( 10 );
</code></pre>
<p>That is a class Team with the properties: name/logo/members </p>
<p><strong>Edit</strong>
After a few attempt I got this:</p>
<pre><code>class Team:
pass
</code></pre>
<p>Later</p>
<pre><code>team = Team()
team.name="Oscar"
team.logo="http://..."
team.members=10
</code></pre>
<p>Is this the python way?? Feels odd ( coming from a strongly typed language of course ) </p>
| 40 | 2009-09-30T01:02:16Z | 1,495,680 | <pre><code>class Team:
def __init__(self):
self.name = None
self.logo = None
self.members = 0
</code></pre>
<p>In Python, you typically don't write getters and setters, unless you really have a non-trivial implementation for them (at which point you use property descriptors).</p>
| 38 | 2009-09-30T01:06:33Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.