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
list
How to pass information using an HTTP redirect (in Django)
599,280
<p>I have a view that accepts a form submission and updates a model.</p> <p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p> <p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
19
2009-03-01T05:02:13Z
2,304,004
<p>You could also have the redirect url be the path to an already parameterized view.</p> <p>urls.py:</p> <pre><code>(r'^some/path/(?P&lt;field_name&gt;\w+)/$', direct_to_template, {'template': 'field_updated_message.html', }, 'url-name' ), </code></pre> <p>views.py:</p> <pre><code>HttpResponseRedirect( reverse('url-name', args=(myfieldname,)) ) </code></pre> <p>Note that args= needs to take a tuple.</p>
0
2010-02-20T22:30:21Z
[ "python", "django", "http" ]
How to pass information using an HTTP redirect (in Django)
599,280
<p>I have a view that accepts a form submission and updates a model.</p> <p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p> <p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
19
2009-03-01T05:02:13Z
4,642,620
<p>I liked the idea of using the message framework, but the example in the django documentation doesn't work for me in the context of the question above. </p> <p>What really annoys me, is the line in the django docs:</p> <p><code>If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.</code></p> <p>which is incomprehensible to a newbie (like me) and needs to expanded upon, preferably with what those 2 options look like. </p> <p>I was only able to find solutions that required rendering with RequestContext... which doesn't answer the question above.</p> <p>I believe I've created a solution for the 2nd option below:</p> <p>Hopefully this will help someone else.</p> <p>== urls.py ==</p> <pre><code>from django.conf.urls.defaults import * from views import * urlpatterns = patterns('', (r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'), (r'^test/$', test ), </code></pre> <p>== viewtest.py ==</p> <pre><code>from django.contrib import messages from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse def test(request): messages.success( request, 'Test successful' ) return HttpResponseRedirect( reverse('main_page') ) </code></pre> <p>== viewmain.py ==</p> <pre><code>from django.contrib.messages import get_messages from django.shortcuts import render_to_response def main_page(request, template_name ): # create dictionary of items to be passed to the template c = { messages': get_messages( request ) } # render page return render_to_response( template_name, c, ) </code></pre> <p>== main_page.html ==</p> <pre><code>{% block content %} {% if messages %} &lt;div&gt; {% for message in messages %} &lt;h2 class="{{message.tag}}"&gt;{{ message.message }}&lt;/h2&gt; {% endfor %} &lt;/div&gt; {% endif %} {% endblock %} </code></pre>
4
2011-01-09T23:46:57Z
[ "python", "django", "http" ]
How to pass information using an HTTP redirect (in Django)
599,280
<p>I have a view that accepts a form submission and updates a model.</p> <p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p> <p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
19
2009-03-01T05:02:13Z
5,131,666
<p>The solution used by Pydev UA is the less intrusive and can be used without modifying almost nothing in your code. When you pass the message, you can update your context in the view that handles the message and in your template you can show it.</p> <p>I used the same approach, but instead passing a simple text, passed a dict with the information in useful fields for me. Then in the view, updated context as well and then returned the rendered template with the updated context.</p> <p>Simple, effective and very unobstrusive.</p>
0
2011-02-27T05:42:47Z
[ "python", "django", "http" ]
How to pass information using an HTTP redirect (in Django)
599,280
<p>I have a view that accepts a form submission and updates a model.</p> <p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p> <p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
19
2009-03-01T05:02:13Z
5,402,113
<p>I think this code should work for you</p> <pre><code>request.user.message_set.create(message="This is some message") return http.HttpResponseRedirect('/url') </code></pre>
1
2011-03-23T07:37:42Z
[ "python", "django", "http" ]
How to pass information using an HTTP redirect (in Django)
599,280
<p>I have a view that accepts a form submission and updates a model.</p> <p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p> <p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
19
2009-03-01T05:02:13Z
8,704,580
<p>I have read and checked all answers, and it seems to me that the way to go now is using <a href="https://docs.djangoproject.com/en/1.3/ref/contrib/messages/" rel="nofollow">the messaging framework</a>. Some of the replies are fairly old and have probably been the right way at the time of the posting.</p>
4
2012-01-02T19:26:34Z
[ "python", "django", "http" ]
Why doesn't the weakref work on this bound method?
599,430
<p>I have a project where i'm trying to use weakrefs with callbacks, and I don't understand what I'm doing wrong. I have created simplified test that shows the exact behavior i'm confused with. </p> <p>Why is it that in this test test_a works as expected, but the weakref for self.MyCallbackB disappears between the class initialization and calling test_b? I thought like as long as the instance (a) exists, the reference to self.MyCallbackB should exist, but it doesn't.</p> <pre><code>import weakref class A(object): def __init__(self): def MyCallbackA(): print 'MyCallbackA' self.MyCallbackA = MyCallbackA self._testA = weakref.proxy(self.MyCallbackA) self._testB = weakref.proxy(self.MyCallbackB) def MyCallbackB(self): print 'MyCallbackB' def test_a(self): self._testA() def test_b(self): self._testB() if __name__ == '__main__': a = A() a.test_a() a.test_b() </code></pre>
8
2009-03-01T07:23:20Z
599,486
<p>You want a <a href="http://code.activestate.com/recipes/81253/">WeakMethod</a>. </p> <p>An explanation why your solution doesn't work can be found in the discussion of the recipe:</p> <blockquote> <p>Normal weakref.refs to bound methods don't quite work the way one expects, because bound methods are first-class objects; <strong>weakrefs to bound methods are dead-on-arrival</strong> unless some other strong reference to the same bound method exists.</p> </blockquote>
9
2009-03-01T08:16:06Z
[ "python", "weak-references" ]
Why doesn't the weakref work on this bound method?
599,430
<p>I have a project where i'm trying to use weakrefs with callbacks, and I don't understand what I'm doing wrong. I have created simplified test that shows the exact behavior i'm confused with. </p> <p>Why is it that in this test test_a works as expected, but the weakref for self.MyCallbackB disappears between the class initialization and calling test_b? I thought like as long as the instance (a) exists, the reference to self.MyCallbackB should exist, but it doesn't.</p> <pre><code>import weakref class A(object): def __init__(self): def MyCallbackA(): print 'MyCallbackA' self.MyCallbackA = MyCallbackA self._testA = weakref.proxy(self.MyCallbackA) self._testB = weakref.proxy(self.MyCallbackB) def MyCallbackB(self): print 'MyCallbackB' def test_a(self): self._testA() def test_b(self): self._testB() if __name__ == '__main__': a = A() a.test_a() a.test_b() </code></pre>
8
2009-03-01T07:23:20Z
599,492
<p>According to the documentation for the Weakref module:</p> <blockquote> <p>In the following, the term referent means the object which is referred to by a weak reference.</p> <p>A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else.</p> </blockquote> <p>Whats happening with MyCallbackA is that you are holding a reference to it in the instances of A, thanks to -</p> <pre><code>self.MyCallbackA = MyCallbackA </code></pre> <p>Now, there is no reference to the bound method MyCallbackB in your code. It is held only in a.__class__.__dict__ as an unbound method. Basically, a bound method is created (and returned to you) when you do self.methodName. (AFAIK, a bound method works like a property -using a descriptor (read-only): at least for new style classes. I am sure, something similar i.e. w/o descriptors happens for old style classes. I'll leave it to someone more experienced to verify the claim about old style classes.) So, self.MyCallbackB dies as soon as the weakref is created, because there is no strong reference to it! </p> <p>My conclusions are based on :-</p> <pre><code>import weakref #Trace is called when the object is deleted! - see weakref docs. def trace(x): print "Del MycallbackB" class A(object): def __init__(self): def MyCallbackA(): print 'MyCallbackA' self.MyCallbackA = MyCallbackA self._testA = weakref.proxy(self.MyCallbackA) print "Create MyCallbackB" # To fix it, do - # self.MyCallbackB = self.MyCallBackB # The name on the LHS could be anything, even foo! self._testB = weakref.proxy(self.MyCallbackB, trace) print "Done playing with MyCallbackB" def MyCallbackB(self): print 'MyCallbackB' def test_a(self): self._testA() def test_b(self): self._testB() if __name__ == '__main__': a = A() #print a.__class__.__dict__["MyCallbackB"] a.test_a() </code></pre> <p><strong>Output</strong> </p> <blockquote> <p>Create MyCallbackB<br /> Del MycallbackB<br /> Done playing with MyCallbackB<br /> MyCallbackA </p> </blockquote> <p><strong>Note :</strong><br /> I tried verifying this for old style classes. It turned out that "print a.test_a.__get__" outputs -</p> <p><code>&lt;method-wrapper '__get__' of instancemethod object at 0xb7d7ffcc&gt;</code> </p> <p>for both new and old style classes. So it may not really be a descriptor, just something descriptor-like. In any case, the point is that a bound-method object is created when you acces an instance method through self, and unless you maintain a strong reference to it, it will be deleted.</p>
4
2009-03-01T08:27:33Z
[ "python", "weak-references" ]
Why doesn't the weakref work on this bound method?
599,430
<p>I have a project where i'm trying to use weakrefs with callbacks, and I don't understand what I'm doing wrong. I have created simplified test that shows the exact behavior i'm confused with. </p> <p>Why is it that in this test test_a works as expected, but the weakref for self.MyCallbackB disappears between the class initialization and calling test_b? I thought like as long as the instance (a) exists, the reference to self.MyCallbackB should exist, but it doesn't.</p> <pre><code>import weakref class A(object): def __init__(self): def MyCallbackA(): print 'MyCallbackA' self.MyCallbackA = MyCallbackA self._testA = weakref.proxy(self.MyCallbackA) self._testB = weakref.proxy(self.MyCallbackB) def MyCallbackB(self): print 'MyCallbackB' def test_a(self): self._testA() def test_b(self): self._testB() if __name__ == '__main__': a = A() a.test_a() a.test_b() </code></pre>
8
2009-03-01T07:23:20Z
15,468,266
<p>The other answers address the <em>why</em> in the original question, but either don't provide a workaround or refer to external sites.</p> <p>After working through several other posts on StackExchange on this topic, many of which are marked as duplicates of this question, I finally came to a succinct workaround. When I know the nature of the object I'm dealing with, I use the weakref module; when I might instead be dealing with a bound method (as occurs in my code when using event callbacks), I now use the following WeakRef class as a direct replacement for weakref.ref(). I've tested this with Python 2.4 through and including Python 2.7, but not on Python 3.x.</p> <pre><code>class WeakRef: def __init__ (self, item): try: self.method = weakref.ref (item.im_func) self.instance = weakref.ref (item.im_self) except AttributeError: self.reference = weakref.ref (item) else: self.reference = None def __call__ (self): if self.reference != None: return self.reference () instance = self.instance () if instance == None: return None method = self.method () return getattr (instance, method.__name__) </code></pre>
0
2013-03-18T01:05:09Z
[ "python", "weak-references" ]
How do I tell a file from directory in Python?
599,474
<p>When using os.listdir method I need to tell which item in the resulting list is a directory or just a file.</p> <p>I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory.</p> <p>Is there a way to go through this list and remove all files from it? If it isn't possible to do with os.listdir, what method should I use instead?</p> <p>Thanks.</p>
7
2009-03-01T08:11:13Z
599,481
<p>Use <code>os.path.isdir</code> to filter out the directories. Possibly something like</p> <pre><code>dirs = filter(os.path.isdir, os.listdir('/path')) for dir in dirs: # add your file </code></pre>
14
2009-03-01T08:14:03Z
[ "python", "file", "directory" ]
How do I tell a file from directory in Python?
599,474
<p>When using os.listdir method I need to tell which item in the resulting list is a directory or just a file.</p> <p>I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory.</p> <p>Is there a way to go through this list and remove all files from it? If it isn't possible to do with os.listdir, what method should I use instead?</p> <p>Thanks.</p>
7
2009-03-01T08:11:13Z
599,568
<blockquote> <p>dirs = filter(os.path.isdir, os.listdir('/path'))</p> </blockquote> <p>Note this won't work unless '/path' is the current working directory. os.listdir() returns leafnames, so you'll be asking “os.path.isdir('file.txt')”, and if the current directory is elsewhere you'll be looking at the wrong 'file.txt'.</p> <p>os.path.join() should be used on the output of os.listdir() to obtain a complete filename.</p> <pre><code>children= [os.path.join('/path', child) for child in os.listdir('/path')] directories= filter(os.path.isdir, children) </code></pre>
2
2009-03-01T09:50:02Z
[ "python", "file", "directory" ]
How do I tell a file from directory in Python?
599,474
<p>When using os.listdir method I need to tell which item in the resulting list is a directory or just a file.</p> <p>I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory.</p> <p>Is there a way to go through this list and remove all files from it? If it isn't possible to do with os.listdir, what method should I use instead?</p> <p>Thanks.</p>
7
2009-03-01T08:11:13Z
599,650
<p>This might be faster:</p> <pre><code>current, dirs, files = os.walk('/path').next() </code></pre> <p>The list of directories will be in the <code>dirs</code> variable.</p>
7
2009-03-01T11:18:53Z
[ "python", "file", "directory" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
599,635
<p>Do you really mean <code>u'String'</code>? </p> <p>In any event, can't you just do <code>str(string)</code> to get a string rather than a unicode-string? (This should be different for Python 3, for which all strings are unicode.)</p>
0
2009-03-01T11:01:20Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
599,644
<p>Use <code>dir</code> or <code>type</code> on the 'string' to find out what it is. I suspect that it's one of BeautifulSoup's tag objects, that prints like a string, but really isn't one. Otherwise, its inside a list and you need to convert each string separately.</p> <p>In any case, why are you objecting to using Unicode? Any specific reason?</p>
0
2009-03-01T11:14:19Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
599,653
<p><code>[u'ABC']</code> would be a one-element list of unicode strings. <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit">Beautiful Soup always produces Unicode</a>. So you need to convert the list to a single unicode string, and then convert that to ASCII.</p> <p>I don't know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really <em>only</em> ASCII you would use this:</p> <pre><code> soup[0].encode("ascii") </code></pre> <p>However, please double-check that your data is really ASCII. This is pretty rare. Much more likely it's latin-1 or utf-8.</p> <pre><code> soup[0].encode("latin-1") soup[0].encode("utf-8") </code></pre> <p>Or you ask Beautiful Soup what the original encoding was and get it back in this encoding: </p> <pre><code> soup[0].encode(soup.originalEncoding) </code></pre>
53
2009-03-01T11:22:11Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
599,681
<p>You probably have a list containing one unicode string. The <code>repr</code> of this is <code>[u'String']</code>.</p> <p>You can convert this to a list of byte strings using any variation of the following:</p> <pre><code># Functional style. print map(lambda x: x.encode('ascii'), my_list) # List comprehension. print [x.encode('ascii') for x in my_list] # Interesting if my_list may be a tuple or a string. print type(my_list)(x.encode('ascii') for x in my_list) # What do I care about the brackets anyway? print ', '.join(repr(x.encode('ascii')) for x in my_list) # That's actually not a good way of doing it. print ' '.join(repr(x).lstrip('u')[1:-1] for x in my_list) </code></pre>
13
2009-03-01T11:40:24Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
14,785,555
<p>If accessing/printing single element lists (e.g., sequentially or filtered):</p> <pre><code>my_list = [u'String'] # sample element my_list = [str(my_list[0])] </code></pre>
4
2013-02-09T06:21:39Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
16,262,256
<p>pass the output to str() function and it will remove the convert the unicode output. also by printing the output it will remove the u'' tags from it. </p>
1
2013-04-28T11:14:18Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
29,584,254
<p><code>encode("latin-1")</code> helped me in my case:</p> <pre><code>facultyname[0].encode("latin-1") </code></pre>
-1
2015-04-11T23:30:43Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
36,891,685
<p><code>[u'String']</code> is a text representation of a list that contains a Unicode string on Python 2.</p> <p>If you run <code>print(some_list)</code> then it is equivalent to<br> <code>print'[%s]' % ', '.join(map(repr, some_list))</code> i.e., to create a text representation of a Python object with the type <code>list</code>, <code>repr()</code> function is called for each item.</p> <p><strong>Don't confuse a Python object and its text representation</strong>—<code>repr('a') != 'a'</code> and even the text representation of the text representation differs: <code>repr(repr('a')) != repr('a')</code>.</p> <p><code>repr(obj)</code> returns a string that contains a printable representation of an object. Its purpose is to be an unambiguous representation of an object that can be useful for debugging, in a REPL. Often <code>eval(repr(obj)) == obj</code>.</p> <p>To avoid calling <code>repr()</code>, you could print list items directly (if they are all Unicode strings) e.g.: <code>print ",".join(some_list)</code>—it prints a comma separated list of the strings: <code>String</code></p> <p>Do not encode a Unicode string to bytes using a hardcoded character encoding, <strong>print Unicode directly</strong> instead. Otherwise, the code may fail because the encoding can't represent all the characters e.g., if you try to use <code>'ascii'</code> encoding with non-ascii characters. Or the code silently produces mojibake (corrupted data is passed further in a pipeline) if the environment uses an encoding that is incompatible with the hardcoded encoding.</p>
0
2016-04-27T13:45:09Z
[ "python", "unicode", "ascii" ]
Python string prints as [u'String']
599,625
<p>This will surely be an easy one but it is really bugging me. </p> <p>I have a script that reads in a webpage and uses <a href="https://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> to parse it. From the <em>soup</em> I extract all the links as my final goal is to print out the link.contents.</p> <p>All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script. </p> <p>Every time I go to print out a variable that holds 'String' I get <code>[u'String']</code> printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?</p>
59
2009-03-01T10:48:45Z
40,090,338
<pre><code>import json, ast r = {u'name': u'A', u'primary_key': 1} ast.literal_eval(json.dumps(r)) </code></pre> <p>will print </p> <pre><code>{'name': 'A', 'primary_key': 1} </code></pre>
0
2016-10-17T15:30:50Z
[ "python", "unicode", "ascii" ]
PyS60: Bluetooth sockets
599,737
<p>From the website <a href="http://www.mobilepythonbook.org/" rel="nofollow">http://www.mobilepythonbook.org/</a> I found the following example of bluetooth sockets: <a href="http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html" rel="nofollow">BT chat example</a></p> <p>Here in function chat_server() the bind method accepts a tuple with two elements. The first one has been used as a null string. What does it signify?</p> <p>Which node will act as master in the Bluetooth, the one that starts chat_client or the one that starts chat_server? I feel it should be the node running chat_client. Andhence Bluetooth slave will be the other nodes.</p>
0
2009-03-01T12:22:41Z
668,345
<p>For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string '' represents INADDR_BROADCAST -- <a href="http://docs.python.org/library/socket.html" rel="nofollow">http://docs.python.org/library/socket.html</a></p> <p>There you'll find more than enough information. Basically what INADDR_ANY means that it will bind to any address that the host has.</p> <p>The server is would be the Bluetooth master and the clients the slave, this is because the master <strong>has</strong> to exist before the the client can be spawned. As a discoverable device the server is the one that determines how the channel gets configured.</p> <p>I hope this clarifies things up.</p>
1
2009-03-20T23:24:33Z
[ "python", "bluetooth", "nokia", "pys60" ]
PyS60: Bluetooth sockets
599,737
<p>From the website <a href="http://www.mobilepythonbook.org/" rel="nofollow">http://www.mobilepythonbook.org/</a> I found the following example of bluetooth sockets: <a href="http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html" rel="nofollow">BT chat example</a></p> <p>Here in function chat_server() the bind method accepts a tuple with two elements. The first one has been used as a null string. What does it signify?</p> <p>Which node will act as master in the Bluetooth, the one that starts chat_client or the one that starts chat_server? I feel it should be the node running chat_client. Andhence Bluetooth slave will be the other nodes.</p>
0
2009-03-01T12:22:41Z
669,159
<p>I found the answer the device that starts listening for incoming connections is slave and the one that discovers and requests for connection is the master.</p> <p>Sorry michelpeterson your answer is totally wrong.</p>
0
2009-03-21T11:39:32Z
[ "python", "bluetooth", "nokia", "pys60" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
599,959
<p>The simplest way I can think of is with slicing- </p> <pre><code>def findPath( i_file): lines = open( i_file ).readlines() for line in lines: if line.startswith( "Path=" ) : return line[5:] </code></pre> <p>A quick note on slice notation, it uses two indices instead of the usual one. The first index indicates the first element of the sequence you want to include in the <em>slice</em> and the last index is the index immediately after the last element you wish to include in the slice.<br /> <strong>Eg:</strong> </p> <pre><code>sequenceObj[firstIndex:lastIndex] </code></pre> <p>The slice consists of all the elements between firstIndex and lastIndex, including firstIndex and not lastIndex. If the first index is omitted, it defaults to the start of the sequence. If the last index is omitted, it includes all elements upto the lsdt element in the sequence. Negative indices are also allowed. Use Google to learn more about the topic.</p>
3
2009-03-01T15:25:16Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
599,960
<pre><code>line[5:] </code></pre> <p>gives you characters after the first five.</p>
2
2009-03-01T15:25:58Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
599,961
<p><code>line[5:]</code> will give the substring you want. Search the <a href="http://docs.python.org/tutorial/introduction.html" rel="nofollow">introduction</a> and look for 'slice notation'</p>
2
2009-03-01T15:26:31Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
599,962
<p>If the string is fixed you can simply use:</p> <pre><code>if line.startswith("Path="): return line[5:] </code></pre> <p>which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too).</p> <p>Or you can split the line at the first <code>=</code>:</p> <pre><code>if "=" in line: param, value = line.split("=",1) </code></pre> <p>Then param is "Path" and value is the rest after the first =.</p>
97
2009-03-01T15:26:56Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
599,979
<p>For slicing (conditional or non-conditional) in general I prefer what a colleague suggested recently; Use replacement with an empty string. Easier to read the code, less code (sometimes) and less risk of specifying the wrong number of characters. Ok; I do not use Python, but in other languages I do prefer this approach:</p> <pre><code>rightMost = fullPath.replace('Path=','',1) </code></pre> <p>or - to follow up to the first comment to this post - if this should only be done <em>if the line starts</em> with <code>Path</code>:</p> <pre><code>rightmost = re.compile('^Path=').sub('',fullPath) </code></pre> <p>The main difference to some of what has been suggested above is that there is no "magic number" (5) involved, nor any need to specify both '<code>5</code>' <em>and</em> the string '<code>Path=</code>', In other words I prefer this approach from a code maintenance point of view.</p>
15
2009-03-01T15:43:50Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
600,002
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; p = re.compile(r'path=(.*)', re.IGNORECASE) &gt;&gt;&gt; path = "path=c:\path" &gt;&gt;&gt; re.match(p, path).group(1) 'c:\\path' </code></pre>
3
2009-03-01T15:57:15Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
600,195
<h3>Remove prefix from a string</h3> <pre><code># ... if line.startswith(prefix): return line[len(prefix):] </code></pre> <h3>Split on the first occurrence of the separator via <code>str.partition()</code></h3> <pre><code>def findvar(filename, varname="Path", sep="=") : for line in open(filename): if line.startswith(varname + sep): head, sep_, tail = line.partition(sep) # instead of `str.split()` assert head == varname assert sep_ == sep return tail </code></pre> <h3>Parse INI-like file with <a href="http://docs.python.org/library/configparser.html">ConfigParser</a></h3> <pre><code>from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read(filename) # requires section headers to be present path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation </code></pre> <h3>Other options</h3> <ul> <li><a href="http://stackoverflow.com/questions/599953/how-to-remove-left-part-of-a-string-in-python/599962#599962"><code>str.split()</code></a></li> <li><a href="http://stackoverflow.com/questions/599953/how-to-remove-left-part-of-a-string-in-python/600002#600002"><code>re.match()</code></a></li> </ul>
80
2009-03-01T18:03:24Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
600,644
<p>If you know list comprehensions:</p> <pre><code>lines = [line[5:] for line in file.readlines() if line[:5] == "Path="] </code></pre>
0
2009-03-01T22:11:56Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
5,293,388
<p>I prefer the looks of pop to indexing:</p> <pre><code>value = line.split("Path=").pop() </code></pre> <p>to</p> <pre><code>value = line.split("Path=")[1] param, value = line.split("Path=") </code></pre>
7
2011-03-13T23:58:33Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
7,440,332
<pre><code>def removePrefix(text, prefix): return text[len(prefix):] if text.startswith(prefix) else text </code></pre> <p>Couldn't resist doing this in one line. Requires Python 2.5+.</p>
7
2011-09-16T04:59:30Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
19,083,836
<p>Or why not</p> <pre><code>if line.startswith(prefix): return line.replace(prefix, '', 1) </code></pre>
4
2013-09-29T22:03:51Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
19,929,571
<p>How about..</p> <pre><code>line = 'path=c:\path' head, sep, tail = line.partition('path=') &gt;&gt;&gt; print 'head = ', head head = print 'sep = ',sep sep = path= print 'tail = ',tail tail = c:\path &gt;&gt;&gt; </code></pre>
2
2013-11-12T12:45:27Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
20,348,535
<p>I guess this what you are exactly looking for</p> <pre><code> def findPath(i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ): output_line=line[(line.find("Path=")+len("Path=")):] return output_line </code></pre>
0
2013-12-03T10:27:15Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
27,855,275
<p>The pop version isn't quite right. I think you want:</p> <pre><code>&gt;&gt;&gt; print "foofoobar".split("foo",1).pop() foobar </code></pre>
0
2015-01-09T06:50:12Z
[ "python", "string" ]
How to remove the left part of a string?
599,953
<p>I have some simple python code that searches files for a string e.g. <code>path=c:\path</code>, whereby the <code>c:\path</code> may vary. The current code is:</p> <pre><code>def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line content after "Path=" ? </code></pre> <p>What is a simple way to get a string text after <code>Path=</code>? Is there a simple method, without closures, reflection or other esoteric things ?</p>
63
2009-03-01T15:19:38Z
35,135,905
<p>Another simple one-liner that hasn't been mentioned here:</p> <pre><code>value = line.split("Path=", 1)[-1] </code></pre> <p>This will also work properly for various edge cases:</p> <pre><code>&gt;&gt;&gt; print ("prefixfoobar".split("foo", 1)[-1]) "bar" &gt;&gt;&gt; print ("foofoobar".split("foo", 1)[-1]) "foobar" &gt;&gt;&gt; print ("foobar".split("foo", 1)[-1]) "bar" &gt;&gt;&gt; print ("bar".split("foo", 1)[-1]) "bar" &gt;&gt;&gt; print ("".split("foo", 1)[-1]) "" </code></pre>
0
2016-02-01T16:51:40Z
[ "python", "string" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,199
<p>The second approach seems better. I'd use the first one only for configuration files or something.</p> <p>Anyway, to avoid the problem you could always:</p> <pre><code>from myapp.appstate import AppState </code></pre> <p>That way you don't have to write the long line anymore.</p>
3
2009-03-01T18:05:34Z
[ "python", "design" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,200
<p>I would go with the classes route as it will better organize your code. Remember that for readability you can do this:</p> <pre><code>from appstate import AppSate </code></pre>
0
2009-03-01T18:05:58Z
[ "python", "design" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,201
<p>Sounds like the classic conundrum :-) In Python, there's nothing dirty or shameful about choosing to use a module if that's the best approach. After all, modules, functions, and the like are, in fact, first-class citizens in the language, and offer introspection and other properties that many other languages use objects to obtain.</p> <p>The way you've described your options, it kinda sounds like you're not too crazy about a class-based approach in this case.</p> <p>I don't know if you've used the Django framework, but if not have a look at their documentation on how they handle settings. These are app-wide, they are defined in a module, and they are available gobally. The way they parse the options and expose them globally is quite elegant, and you may find such an approach inspiring for your needs.</p>
13
2009-03-01T18:06:47Z
[ "python", "design" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,206
<p>I'd definitely go for the second option : having already used the first one, I'm now forced to refactor, as my application evolved and have to support more modular constructs, so I now need to handle multiple simulataneous 'configurations'.</p> <p>The second approach is, IMO, more flexible and future proof. To avoid the longer lines of code, you could use <code>from appstate import AppState</code> instead of just <code>import appstate</code>.</p>
0
2009-03-01T18:08:45Z
[ "python", "design" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,219
<p>The second approach is only significantly different from the first approach if you have application state stored in an <em>instance</em> of AppState, in which case your complaint doesn't apply. If you're just storing stuff in a class and using static/class methods, your class is no different than a module, and it would be pythonic to instead actually have it as a module.</p>
4
2009-03-01T18:19:17Z
[ "python", "design" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,325
<p>Why not go with an instance of that class? That way you might even be able later on to have 2 different "sessions" running, depending on what instance you use. It might make it more flexible. Maybe add some method <code>get_appstate()</code> to the module so it instanciates the class once. Later on if you might want several instances you can change this method to eventually take a parameter and use some dictionary etc. to store those instances.</p> <p>You could also use property decorators btw to make things more readable and have the flexibility of storing it how and where you want it stores.</p> <p>I agree that it would be more pythonic to use the module approach instead of classmethods. </p> <p>BTW, I am not such a big fan of having things available globally by some "magic". I'd rather use some explicit call to obtain that information. Then I know where things come from and how to debug it when things fail.</p>
0
2009-03-01T19:17:16Z
[ "python", "design" ]
Python: Choosing between modules and classes
600,190
<p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p> <ol> <li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li> <li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li> </ol> <p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
8
2009-03-01T18:00:39Z
600,381
<p>Consider this example:</p> <pre><code>configuration | +-&gt; graphics | | | +-&gt; 3D | | | +-&gt; 2D | +-&gt; sound </code></pre> <p>The real question is: What is the difference between classes and modules in this hierarchy, as it could be represented by both means?</p> <p>Classes represent types. If you implement your solution with classes instead of modules, you are able to check a graphics object for it's proper type, but write generic graphics functions.</p> <p>With classes you can generate parametrized values. This means it is possible to initialize differently the <em>sounds</em> class with a constructor, but it is hard to initialize a module with different parameters.</p> <p>The point is, that you really something different from the modeling standpoint.</p>
1
2009-03-01T19:47:52Z
[ "python", "design" ]
How to make Satchmo work in Google App Engine
600,225
<p>I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?</p> <p>Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.</p> <p>Plus, if this is not possible today, lets band together and form a new Open Source project to "extend" satchmo or perhaps branch it, for compatibility?</p>
3
2009-03-01T18:22:33Z
600,231
<p>You can't. There are alot of dependencies in Satchmo that you aren't allowed to install on AppEngine.</p> <p>See this thread as well: <a href="http://groups.google.com/group/satchmo-users/browse_thread/thread/509265ccd5f5fc1e?pli=1" rel="nofollow">http://groups.google.com/group/satchmo-users/browse_thread/thread/509265ccd5f5fc1e?pli=1</a></p>
3
2009-03-01T18:25:18Z
[ "python", "google-app-engine", "e-commerce", "satchmo" ]
How to make Satchmo work in Google App Engine
600,225
<p>I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?</p> <p>Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.</p> <p>Plus, if this is not possible today, lets band together and form a new Open Source project to "extend" satchmo or perhaps branch it, for compatibility?</p>
3
2009-03-01T18:22:33Z
833,823
<p>Nothing is impossible - this will just require lots of effort - if there will be somebody wishing to do so - why not? But it might be easier (cheaper) to get Django friendly hosting instead of spending hours on hacking the code.</p>
2
2009-05-07T10:11:27Z
[ "python", "google-app-engine", "e-commerce", "satchmo" ]
How to make Satchmo work in Google App Engine
600,225
<p>I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?</p> <p>Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.</p> <p>Plus, if this is not possible today, lets band together and form a new Open Source project to "extend" satchmo or perhaps branch it, for compatibility?</p>
3
2009-03-01T18:22:33Z
835,520
<p>Possible if:</p> <ul> <li><p>Someone writes a generic ORM to Bigtable mapper. Most probably, <a href="http://code.google.com/appengine/articles/app-engine-patch.html" rel="nofollow">Appengine Patch Guys</a></p></li> <li><p>Someone rewrites the views and models of Satchmo to remove existing ORM queries and use the minimal functionality of the ORM provided by the patch project, should be either you or the Satchmo guys.</p></li> <li><p>Someone hacks around a lot using the <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html" rel="nofollow">django helper project</a>, can only be helper project guys.</p></li> </ul>
2
2009-05-07T15:57:57Z
[ "python", "google-app-engine", "e-commerce", "satchmo" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
600,606
<p>I think Asa's answer is essentially correct, but you could extend it a little to act more like <code>mkdir -p</code>, either:</p> <pre><code>import os def mkdir_path(path): if not os.access(path, os.F_OK): os.mkdirs(path) </code></pre> <p>or</p> <pre><code>import os import errno def mkdir_path(path): try: os.mkdirs(path) except os.error, e: if e.errno != errno.EEXIST: raise </code></pre> <p>These both handle the case where the path already exists silently but let other errors bubble up.</p>
5
2009-03-01T21:47:58Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
600,612
<p><code>mkdir -p</code> functionality as follows:</p> <pre><code>import errno import os def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python &gt;2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise </code></pre> <h3>Update</h3> <p>For Python ≥ 3.2, <code>os.makedirs</code> has an <a href="http://docs.python.org/3/library/os.html?highlight=makedirs#os.makedirs">optional third argument</a> <code>exist_ok</code> that, when true, enables the <code>mkdir -p</code> functionality —<em>unless</em> <code>mode</code> is provided and the existing directory has different permissions than the intended ones; in that case, <code>OSError</code> is raised as previously.</p>
635
2009-03-01T21:51:46Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
600,879
<p><code>mkdir -p</code> gives you an error if you the file already exists:</p> <pre><code>$ touch /tmp/foo $ mkdir -p /tmp/foo mkdir: cannot create directory `/tmp/foo': File exists </code></pre> <p>So a refinement to the previous suggestions would be to re-<code>raise</code> the exception if <code>os.path.isdir</code> returns <code>False</code> (when checking for <code>errno.EEXIST</code>).</p> <p>(Update) See also this <a href="http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write">highly similar question</a>; I agree with the accepted answer (and caveats) except I would recommend <code>os.path.isdir</code> instead of <code>os.path.exists</code>.</p> <p>(Update) Per a suggestion in the comments, the full function would look like:</p> <pre><code>import os def mkdirp(directory): if not os.path.isdir(directory): os.makedirs(directory) </code></pre>
11
2009-03-02T00:09:10Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
600,940
<p>This is easier than trapping the exception:</p> <pre><code>import os if not os.path.exists(...): os.makedirs(...) </code></pre> <p><strong>Disclaimer</strong> This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you're writing something more sophisticated than a simple throwaway script running in a controlled environment, you're better off going with the accepted answer that requires only one system call.</p> <p><strong>UPDATE 2012-07-27</strong></p> <p>I'm tempted to delete this answer, but I think there's value in the comment thread below. As such, I'm converting it to a wiki. </p>
113
2009-03-02T00:48:58Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
11,101,867
<p>In Python >=3.2, that's</p> <pre><code>os.makedirs(path, exist_ok=True) </code></pre> <p>In earlier versions, use <a href="http://stackoverflow.com/a/600612/11343">@tzot's answer</a>.</p>
95
2012-06-19T13:21:48Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
11,825,909
<pre><code>import os import tempfile path = tempfile.mktemp(dir=path) os.makedirs(path) os.rmdir(path) </code></pre>
1
2012-08-06T09:47:43Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
11,860,637
<p>As mentioned in the other solutions, we want to be able to hit the file system once while mimicking the behaviour of <code>mkdir -p</code>. I don't think that this is possible to do, but we should get as close as possible.</p> <p>Code first, explanation later:</p> <pre><code>import os import errno def mkdir_p(path): """ 'mkdir -p' in Python """ try: os.makedirs(path) except OSError as exc: # Python &gt;2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise </code></pre> <p>As the comments to @tzot's answer indicate there are problems with checking whether you can create a directory before you actually create it: you can't tell whether someone has changed the file system in the meantime. That also fits in with Python's style of asking for forgiveness, not permission.</p> <p>So the first thing we should do is try to make the directory, then if it goes wrong, work out why.</p> <p>As Jacob Gabrielson points out, one of the cases we must look for is the case where a file already exists where we are trying to put the directory. </p> <p>With <code>mkdir -p</code>:</p> <pre><code>$ touch /tmp/foo $ mkdir -p /tmp/foo mkdir: cannot create directory '/tmp/foo': File exists </code></pre> <p>The analogous behaviour in Python would be to raise an exception.</p> <p>So we have to work out if this was the case. Unfortunately, we can't. We get the same error message back from makedirs whether a directory exists (good) or a file exists preventing the creation of the directory (bad).</p> <p>The only way to work out what happened is to inspect the file system again to see if there is a directory there. If there is, then return silently, otherwise raise the exception.</p> <p>The only problem is that the file system may be in a different state now than when makedirs was called. eg: a file existed causing makedirs to fail, but now a directory is in its place. That doesn't really matter that much, because the the function will only exit silently without raising an exception when at the time of the last file system call the directory existed.</p>
9
2012-08-08T08:31:24Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
14,347,436
<p>Recently, I found this <a href="http://docs.python.org/2/distutils/apiref.html#distutils.dir_util.mkpath">distutils.dir_util.mkpath</a>:</p> <pre><code>In [17]: from distutils.dir_util import mkpath In [18]: mkpath('./foo/bar') Out[18]: ['foo', 'foo/bar'] </code></pre>
30
2013-01-15T21:39:43Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
27,611,157
<p>Function declaration;</p> <pre><code>import os def mkdir_p(filename): try: folder=os.path.dirname(filename) if not os.path.exists(folder): os.makedirs(folder) return True except: return False </code></pre> <p>usage :</p> <pre><code>filename = "./download/80c16ee665c8/upload/backup/mysql/2014-12-22/adclient_sql_2014-12-22-13-38.sql.gz" if (mkdir_p(filename): print "Created dir :%s" % (os.path.dirname(filename)) </code></pre>
1
2014-12-22T22:06:56Z
[ "python", "mkdir" ]
mkdir -p functionality in Python
600,268
<p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
441
2009-03-01T18:49:39Z
35,275,153
<p>With <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir" rel="nofollow">Pathlib</a> from python3 standard library:</p> <pre><code>Path(mypath).mkdir(parents=True, exist_ok=True) </code></pre> <blockquote> <p>If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command). If exist_ok is false (the default), an FileExistsError is raised if the target directory already exists.</p> <p>If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.</p> <p><strong>Changed in version 3.5:</strong> The exist_ok parameter was added.</p> </blockquote>
4
2016-02-08T17:02:36Z
[ "python", "mkdir" ]
Python error when using urllib.open
600,389
<p>When I run this:</p> <pre><code>import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed </code></pre> <p>I get this output in the interactive window (PythonWin):</p> <pre><code>&lt;addinfourl at 48213968 whose fp = &lt;socket._fileobject object at 0x02E14070&gt;&gt; </code></pre> <p>I'm expecting to get the source of the above URL. I know this has worked on other computers (like the ones at school) but this is on my laptop and I'm not sure what the problem is here. Also, I don't understand this error at all. What does it mean? Addinfourl? fp? Please help.</p>
21
2009-03-01T19:56:54Z
600,394
<p>Try this:</p> <p><code>print feed.read()</code></p> <p>See Python docs <a href="http://docs.python.org/library/urllib.html">here</a>.</p>
50
2009-03-01T20:00:08Z
[ "python", "urllib" ]
Python error when using urllib.open
600,389
<p>When I run this:</p> <pre><code>import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed </code></pre> <p>I get this output in the interactive window (PythonWin):</p> <pre><code>&lt;addinfourl at 48213968 whose fp = &lt;socket._fileobject object at 0x02E14070&gt;&gt; </code></pre> <p>I'm expecting to get the source of the above URL. I know this has worked on other computers (like the ones at school) but this is on my laptop and I'm not sure what the problem is here. Also, I don't understand this error at all. What does it mean? Addinfourl? fp? Please help.</p>
21
2009-03-01T19:56:54Z
600,396
<p>urllib.urlopen actually returns a file-like object so to retrieve the contents you will need to use:</p> <pre><code>import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed.read() </code></pre>
15
2009-03-01T20:00:35Z
[ "python", "urllib" ]
Python error when using urllib.open
600,389
<p>When I run this:</p> <pre><code>import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed </code></pre> <p>I get this output in the interactive window (PythonWin):</p> <pre><code>&lt;addinfourl at 48213968 whose fp = &lt;socket._fileobject object at 0x02E14070&gt;&gt; </code></pre> <p>I'm expecting to get the source of the above URL. I know this has worked on other computers (like the ones at school) but this is on my laptop and I'm not sure what the problem is here. Also, I don't understand this error at all. What does it mean? Addinfourl? fp? Please help.</p>
21
2009-03-01T19:56:54Z
600,645
<p>In python 3.0:</p> <pre><code>import urllib import urllib.request fh = urllib.request.urlopen(url) html = fh.read().decode("iso-8859-1") fh.close() print (html) </code></pre>
6
2009-03-01T22:11:58Z
[ "python", "urllib" ]
What features would a *perfect* Python debugger have?
600,401
<p>Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!</p>
3
2009-03-01T20:04:20Z
600,434
<p>The #1 debug feature for me (that my current IDE, Wing, does happen to have) is the ability to drop into a python interpreter and run arbitrary python code when at a breakpoint. Reminds me of using Smalltalk back in the day.</p> <p>Ability to execute code in local scope is incredibly useful, especially in contrast to working in C++ when it can sometimes be a fight to inspect a local variable.</p>
2
2009-03-01T20:22:05Z
[ "python", "ide", "debugging" ]
What features would a *perfect* Python debugger have?
600,401
<p>Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!</p>
3
2009-03-01T20:04:20Z
600,436
<p>Forgive me for the shameless functional programming plug, but...</p> <p>The ability to <em>step backwards</em>.</p>
6
2009-03-01T20:23:28Z
[ "python", "ide", "debugging" ]
What features would a *perfect* Python debugger have?
600,401
<p>Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!</p>
3
2009-03-01T20:04:20Z
600,470
<p>I would love a debugger that could somehow split into two when a thread was created, then I could watch both threads with independent call stacks, etc. </p> <p>If it exists, then I just haven't found it yet.</p>
3
2009-03-01T20:42:24Z
[ "python", "ide", "debugging" ]
What features would a *perfect* Python debugger have?
600,401
<p>Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!</p>
3
2009-03-01T20:04:20Z
600,489
<p>I use <a href="http://winpdb.org/" rel="nofollow">winpdb</a> and I like it very much. I think a new debugger would need to have at least its features. It has some GUI nuisiances though, so maybe you fix it or take some ideas from it to write your own.</p> <p><a href="http://winpdb.org/" rel="nofollow">Winpdb</a> is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p> <p>Features:</p> <ul> <li>GPL license. Winpdb is Free Software.</li> <li>Compatible with CPython 2.3 through 2.6 and Python 3000</li> <li>Compatible with wxPython 2.6 through 2.8</li> <li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li> <li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li> </ul> <p><img src="http://winpdb.org/images/screenshot%5Fwinpdb%5Fsmall.jpg" alt="Screenshot" /></p>
7
2009-03-01T20:50:13Z
[ "python", "ide", "debugging" ]
What features would a *perfect* Python debugger have?
600,401
<p>Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!</p>
3
2009-03-01T20:04:20Z
37,810,886
<p>Ability to step through expression evaluation and intuitive visualization of call stack like in Thonny (<a href="http://thonny.cs.ut.ee" rel="nofollow">http://thonny.cs.ut.ee</a>)</p>
0
2016-06-14T11:35:50Z
[ "python", "ide", "debugging" ]
Why does Google Search return HTTP Error 403?
600,536
<p>Consider the following Python code:</p> <pre> 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); </pre> <p>When this is run, an Exception is thrown:</p> <pre><code>File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically?</p> <p>Any thoughts?</p>
16
2009-03-01T21:16:25Z
600,547
<p>You're doing it too often. Google has limits in place to prevent getting swamped by search bots. You can also try setting the user-agent to something that more closely resembles a normal browser.</p>
0
2009-03-01T21:20:45Z
[ "python", "google-search" ]
Why does Google Search return HTTP Error 403?
600,536
<p>Consider the following Python code:</p> <pre> 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); </pre> <p>When this is run, an Exception is thrown:</p> <pre><code>File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically?</p> <p>Any thoughts?</p>
16
2009-03-01T21:16:25Z
600,551
<p>If you want to do Google searches "properly" through a programming interface, take a look at <a href="http://code.google.com/more/">Google APIs</a>. Not only are these the official way of searching Google, they are also not likely to change if Google changes their result page layout.</p>
23
2009-03-01T21:22:09Z
[ "python", "google-search" ]
Why does Google Search return HTTP Error 403?
600,536
<p>Consider the following Python code:</p> <pre> 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); </pre> <p>When this is run, an Exception is thrown:</p> <pre><code>File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically?</p> <p>Any thoughts?</p>
16
2009-03-01T21:16:25Z
854,782
<p>this should do the trick</p> <pre><code>user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' url = "http://www.google.com/search?hl=en&amp;safe=off&amp;q=Monkey" headers={'User-Agent':user_agent,} request=urllib2.Request(url,None,headers) //The assembled request response = urllib2.urlopen(request) data = response.read() // The data u need </code></pre>
21
2009-05-12T20:46:05Z
[ "python", "google-search" ]
Why does Google Search return HTTP Error 403?
600,536
<p>Consider the following Python code:</p> <pre> 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); </pre> <p>When this is run, an Exception is thrown:</p> <pre><code>File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden </code></pre> <p>However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically?</p> <p>Any thoughts?</p>
16
2009-03-01T21:16:25Z
4,094,342
<p>As <a href="http://stackoverflow.com/questions/600536/why-does-google-search-return-http-error-403/600551#600551">lacqui suggested</a>, the <a href="http://code.google.com/more/" rel="nofollow">Google API's</a> are the way they want you to make requests from code. Unfortunately, I found their documentation was aimed at people writing AJAX web pages, not making raw HTTP requests. I used <a href="http://livehttpheaders.mozdev.org/" rel="nofollow">LiveHTTP Headers</a> to trace the HTTP requests that the samples made, and I found <a href="http://blog.ghcoders.net/2007/09/07/google-apis-no-soap-key-no-problem/" rel="nofollow">ddipaolo's blog post</a> helpful.</p> <p>One more thing that messed me up: they limit you to the <strong>first 64 results</strong> from a query. Usually not a problem if you are just providing web users with a search box, but not helpful if you're trying to use Google to go data mining. I guess they don't want you to go data mining using their API. That 64 number has changed over time and varies between search products.</p> <p><strong>Update:</strong> It appears they definitely do not want you to go data mining. Eventually, you get a 403 error with a link to this <a href="http://code.google.com/apis/errors/" rel="nofollow">API access notice</a>.</p> <blockquote> <p>Please review the Terms of Use for the API(s) you are using (linked in the right sidebar) and ensure compliance. It is likely that we blocked you for one of the following Terms of Use violations: We received automated requests, such as scraping and prefetching. Automated requests are prohibited; all requests must be made as a result of an end-user action.</p> </blockquote> <p>They also list other violations, but I think that's the one that triggered for me. I may have to investigate Yahoo's BOSS service. It doesn't seem to have as many restrictions.</p>
1
2010-11-04T06:22:55Z
[ "python", "google-search" ]
BOO Vs IronPython
600,539
<p>What is the difference between <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a> and <a href="http://boo.codehaus.org/">BOO</a>? Is there a need for 2 Python-like languages?</p>
16
2009-03-01T21:17:30Z
600,552
<p>IronPython is a python implementation wheras Boo is another language with a python-esque syntax. One major difference is that Boo is statically typed by default.</p> <p>I'm sure there are more differences, I've only looked at Boo briefly, but I've been meaning to look at bit deeper (so many languages so little time!).</p> <p>Here is a list of Boo gotchas for python programmers which sums up the differences quite nicely:</p> <ul> <li><a href="http://boo.codehaus.org/Gotchas+for+Python+Users" rel="nofollow">http://boo.codehaus.org/Gotchas+for+Python+Users</a></li> </ul>
11
2009-03-01T21:22:36Z
[ "python", "clr", "ironpython", "boo" ]
BOO Vs IronPython
600,539
<p>What is the difference between <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a> and <a href="http://boo.codehaus.org/">BOO</a>? Is there a need for 2 Python-like languages?</p>
16
2009-03-01T21:17:30Z
600,567
<p>IronPython is Python. Boo looks like Python.</p> <p>They have different goals and while IronPython aims to be just like Python, Boo does not. Boo is not worried about compatibility with Python like IronPython is...</p>
3
2009-03-01T21:30:55Z
[ "python", "clr", "ironpython", "boo" ]
BOO Vs IronPython
600,539
<p>What is the difference between <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a> and <a href="http://boo.codehaus.org/">BOO</a>? Is there a need for 2 Python-like languages?</p>
16
2009-03-01T21:17:30Z
601,106
<p><a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a> is designed to be a faithful implementation of Python on the .NET platform. Version 1 targets Python 2.4 for compatibility, and version 2 targets version 2.5 (although most of the Python standard library modules implemented in C aren't supported).</p> <p><a href="http://boo.codehaus.org/">Boo</a>'s stated aim is to be a "wrist-friendly [dynamic] language for the CLI." It takes a lot of inspiration from Python, but diverges on four main points:</p> <ol> <li>It's designed specifically to take good advantage of the .NET platform</li> <li>The designer diverges from Python syntax where he doesn't agree with the design decisions (most notably, lack of explicit self)</li> <li>The language is explicitly designed to be "wrist friendly" -- that is, to minimize the need for the Shift key or other multi-key combinations to be used.</li> <li>Boo is statically typed by default, but allows optional duck typing.</li> </ol> <p>There are some other minor differences in implementation/performance, but the divergent design goals above should (IMO) inform your choice of languages.</p> <p>Two more things to take into account are maturity and community. Python is much more mature than Boo, and has a much larger community. IronPython also has the explicit blessing of Microsoft.</p>
18
2009-03-02T02:41:34Z
[ "python", "clr", "ironpython", "boo" ]
BOO Vs IronPython
600,539
<p>What is the difference between <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a> and <a href="http://boo.codehaus.org/">BOO</a>? Is there a need for 2 Python-like languages?</p>
16
2009-03-01T21:17:30Z
2,617,831
<p>In a nutshell, Boo's claim to fame is that it is supposed to give you most of the benefits of Python's elegant, terse syntax and very high-level abstractions, but without sacrificing (most) of the speed advantages of a statically typed language like C#.</p>
1
2010-04-11T16:54:33Z
[ "python", "clr", "ironpython", "boo" ]
Making a 2-player web-based textual game
600,621
<p>I'm making a simple web-based, turn-based game and am trying to determine what modules exist out there to help me on this task. </p> <p>Here's the web app I'm looking to build:</p> <ul> <li>User visits the homepage, clicks on a "play game" link</li> <li>This takes the user to a "game room" where he either joins someone else who has been waiting for a partner to play with or waits for someone to join him</li> <li>As soon as there are two users in the room, the game starts. It's a very simple turn-based textual game. One user enters a number, then the other user responds by entering another number, and so on, until some conditions are met and the game is over; each player is shown their final score.</li> </ul> <p>My default plan has been to do this using Django and AJAX. Are there any existing modules/frameworks out there that would potentially save me some of the work of writing this from scratch? (Note: I might be able to negotiate to have this done in .NET if there are some great .NET libraries.)</p>
3
2009-03-01T21:53:51Z
600,641
<p>Try the <a href="http://www.jabber.org" rel="nofollow">Jabber</a> protocol ... It works great for IM, but was designed for use by other types of systems as well and there's already a set of <a href="http://xmpppy.sourceforge.net/" rel="nofollow">bindings for Python</a> since it has become so popular.</p>
1
2009-03-01T22:10:31Z
[ ".net", "javascript", "python", "ajax" ]
Making a 2-player web-based textual game
600,621
<p>I'm making a simple web-based, turn-based game and am trying to determine what modules exist out there to help me on this task. </p> <p>Here's the web app I'm looking to build:</p> <ul> <li>User visits the homepage, clicks on a "play game" link</li> <li>This takes the user to a "game room" where he either joins someone else who has been waiting for a partner to play with or waits for someone to join him</li> <li>As soon as there are two users in the room, the game starts. It's a very simple turn-based textual game. One user enters a number, then the other user responds by entering another number, and so on, until some conditions are met and the game is over; each player is shown their final score.</li> </ul> <p>My default plan has been to do this using Django and AJAX. Are there any existing modules/frameworks out there that would potentially save me some of the work of writing this from scratch? (Note: I might be able to negotiate to have this done in .NET if there are some great .NET libraries.)</p>
3
2009-03-01T21:53:51Z
602,291
<p>If you're not going to have huge numbers of concurrent users or want it done quickly I would go for holding game state on the server and polling via Ajax.</p> <p>The js library of your choice will make that polling easier.</p> <p>If you want it to be larger and hairier, you might look at <a href="http://code.stanziq.com/strophe/" rel="nofollow">Strophe</a>, a js library for writing XMPP clients -- it has a handful of example sites.</p>
1
2009-03-02T13:08:22Z
[ ".net", "javascript", "python", "ajax" ]
how to time-out gracefully while downloading with python
600,848
<p>I'm downloading a huge set of files with following code in a loop:</p> <pre><code>try: urllib.urlretrieve(url2download, destination_on_local_filesystem) except KeyboardInterrupt: break except: print "Timed-out or got some other exception: "+url2download </code></pre> <p>If the server times-out on URL url2download when connection is just initiating, the last exception is handled properly. But sometimes server responded, and downloading is started, but the server is so slow, that it'll takes hours for even one file, and eventually it returns something like:</p> <pre><code>Enter username for Clients Only at albrightandomalley.com: Enter password for in Clients Only at albrightandomalley.com: </code></pre> <p>and just hangs there (although no username/passworde is aksed if the same link is downloaded through the browser).</p> <p>My intention in this situation would be -- skip this file and go to the next one. The question is -- how to do that? Is there a way in python to specify how long is OK to work on downloading one file, and if more time is already spent, interrupt, and go forward?</p>
8
2009-03-01T23:44:38Z
600,858
<p>There's a discussion of this <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#sockets-and-layers" rel="nofollow">here</a>. Caveats (in addition to the ones they mention): I haven't tried it, and they're using <code>urllib2</code>, not <code>urllib</code> (would that be a problem for you?) (Actually, now that I think about it, this technique would probably work for <code>urllib</code>, too).</p>
3
2009-03-01T23:50:43Z
[ "python", "exception-handling", "downloading" ]
how to time-out gracefully while downloading with python
600,848
<p>I'm downloading a huge set of files with following code in a loop:</p> <pre><code>try: urllib.urlretrieve(url2download, destination_on_local_filesystem) except KeyboardInterrupt: break except: print "Timed-out or got some other exception: "+url2download </code></pre> <p>If the server times-out on URL url2download when connection is just initiating, the last exception is handled properly. But sometimes server responded, and downloading is started, but the server is so slow, that it'll takes hours for even one file, and eventually it returns something like:</p> <pre><code>Enter username for Clients Only at albrightandomalley.com: Enter password for in Clients Only at albrightandomalley.com: </code></pre> <p>and just hangs there (although no username/passworde is aksed if the same link is downloaded through the browser).</p> <p>My intention in this situation would be -- skip this file and go to the next one. The question is -- how to do that? Is there a way in python to specify how long is OK to work on downloading one file, and if more time is already spent, interrupt, and go forward?</p>
8
2009-03-01T23:44:38Z
600,863
<p>If you're not limited to what's shipped with python out of the box, then the <a href="http://linux.duke.edu/projects/urlgrabber/" rel="nofollow">urlgrabber</a> module might come in handy:</p> <pre><code>import urlgrabber urlgrabber.urlgrab(url2download, destination_on_local_filesystem, timeout=30.0) </code></pre>
4
2009-03-01T23:55:47Z
[ "python", "exception-handling", "downloading" ]
how to time-out gracefully while downloading with python
600,848
<p>I'm downloading a huge set of files with following code in a loop:</p> <pre><code>try: urllib.urlretrieve(url2download, destination_on_local_filesystem) except KeyboardInterrupt: break except: print "Timed-out or got some other exception: "+url2download </code></pre> <p>If the server times-out on URL url2download when connection is just initiating, the last exception is handled properly. But sometimes server responded, and downloading is started, but the server is so slow, that it'll takes hours for even one file, and eventually it returns something like:</p> <pre><code>Enter username for Clients Only at albrightandomalley.com: Enter password for in Clients Only at albrightandomalley.com: </code></pre> <p>and just hangs there (although no username/passworde is aksed if the same link is downloaded through the browser).</p> <p>My intention in this situation would be -- skip this file and go to the next one. The question is -- how to do that? Is there a way in python to specify how long is OK to work on downloading one file, and if more time is already spent, interrupt, and go forward?</p>
8
2009-03-01T23:44:38Z
601,002
<p>This question is more general about timing out a function: <a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python</a></p> <p>I've used the method described in my answer there to write a wait for text function that times out to attempt an auto-login. If you'd like similar functionality you can reference the code here:</p> <p><a href="http://code.google.com/p/psftplib/source/browse/trunk/psftplib.py" rel="nofollow">http://code.google.com/p/psftplib/source/browse/trunk/psftplib.py</a></p>
2
2009-03-02T01:33:51Z
[ "python", "exception-handling", "downloading" ]
how to time-out gracefully while downloading with python
600,848
<p>I'm downloading a huge set of files with following code in a loop:</p> <pre><code>try: urllib.urlretrieve(url2download, destination_on_local_filesystem) except KeyboardInterrupt: break except: print "Timed-out or got some other exception: "+url2download </code></pre> <p>If the server times-out on URL url2download when connection is just initiating, the last exception is handled properly. But sometimes server responded, and downloading is started, but the server is so slow, that it'll takes hours for even one file, and eventually it returns something like:</p> <pre><code>Enter username for Clients Only at albrightandomalley.com: Enter password for in Clients Only at albrightandomalley.com: </code></pre> <p>and just hangs there (although no username/passworde is aksed if the same link is downloaded through the browser).</p> <p>My intention in this situation would be -- skip this file and go to the next one. The question is -- how to do that? Is there a way in python to specify how long is OK to work on downloading one file, and if more time is already spent, interrupt, and go forward?</p>
8
2009-03-01T23:44:38Z
26,457,801
<p>Try: </p> <p><code>import socket</code></p> <p><code>socket.setdefaulttimeout(30)</code></p>
6
2014-10-20T02:36:10Z
[ "python", "exception-handling", "downloading" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
601,053
<p>Command combination seems to work through <code>|</code> character, so perhaps something like aliasing <code>:w|!your-command-here</code> to a distinct key combination?</p>
3
2009-03-02T02:00:30Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
601,084
<p><strong>Option 1:</strong> </p> <p>Write a function similar to this and place it in your startup settings:</p> <pre><code>function myex() execute ':w' execute ':!!' endfunction </code></pre> <p>You could even map a key combo to it-- look a the docs.</p> <p><hr /></p> <p><strong>Option 2 (better):</strong></p> <p>Look at the documentation for remapping keystrokes - you may be able to accomplish it through a simple key remap. The following works, but has "filename.py" hardcoded. Perhaps you can dig in and figure out how to replace that with the current file?</p> <pre><code>:map &lt;F2&gt; &lt;Esc&gt;:w&lt;CR&gt;:!filename.py&lt;CR&gt; </code></pre> <p>After mapping that, you can just press F2 in command mode.</p> <p>imap, vmap, etc... are mappings in different modes. The above only applies to command mode. The following should work in insert mode also:</p> <pre><code>:imap &lt;F2&gt; &lt;Esc&gt;:w&lt;CR&gt;:!filename.py&lt;CR&gt;a </code></pre> <p>Section 40.1 of the VIM manual is very helpful.</p>
20
2009-03-02T02:27:33Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
601,107
<p>Here you go:</p> <p><code>:nmap &lt;F1&gt; :w&lt;cr&gt;:!%&lt;cr&gt;</code></p> <p>save &amp; run (you have to be in n mode though - just add esc and a for i mode)</p>
4
2009-03-02T02:41:40Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
601,965
<ol> <li><p>Consider switching to IDLE. F5 does everything.</p></li> <li><p>Consider switching to Komodo. You can define a command so that F5 does everything.</p></li> </ol>
-11
2009-03-02T11:08:13Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
602,056
<p>I got the following from the vim tips wiki:</p> <pre><code>command! -complete=file -nargs=+ shell call s:runshellcommand(&lt;q-args&gt;) function! s:runshellcommand(cmdline) botright vnew setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap call setline(1,a:cmdline) call setline(2,substitute(a:cmdline,'.','=','g')) execute 'silent $read !'.escape(a:cmdline,'%#') setlocal nomodifiable 1 endfunction </code></pre> <p>but changed new to vnew on the third line, then for python i have the following</p> <pre><code>map &lt;F9&gt; :w:Shell python %&lt;cr&gt;&lt;c-w&gt; </code></pre> <p>hitting f9 saves, runs, and dumps the output into a new vertically split scratch buffer, for easy yanking/saving etc ... also hits c-w so i only have to press h/c to close it / move back to my code.</p>
0
2009-03-02T11:58:19Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
602,315
<p>Use the <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27autowrite%27">autowrite</a> option:</p> <pre><code>:set autowrite </code></pre> <blockquote> <p>Write the contents of the file, if it has been modified, on each :next, :rewind, :last, :first, :previous, :stop, :suspend, :tag, <strong>:!</strong>, :make, CTRL-] and CTRL-^ command [...]</p> </blockquote>
9
2009-03-02T13:15:39Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
619,380
<p>Okay, the simplest form of what you're looking for is the pipe command. It allows you to run multiple cmdline commands on the same line. In your case, the two commands are write \<code>w\</code> and execute current file \<code>! %:p\</code>. If you have a specific command you run for you current file, the second command becomes, e.g. \<code>!python %:p\</code>. So, the simplest answer to you question becomes:</p> <pre><code>:w | ! %:p ^ ^ ^ | | |--Execute current file | |--Chain two commands |--Save current file </code></pre> <p>One last thing to note is that not all commands can be chained. According to the <a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-lines">Vim docs</a>, certain commands accept a pipe as an argument, and thus break the chain...</p>
34
2009-03-06T16:10:53Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
6,517,768
<p>Another possibility:</p> <pre><code>au BufWriteCmd *.py write | !! </code></pre> <p>Though this will <code>run</code> every time you save, which might not be what you want.</p>
3
2011-06-29T08:33:05Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
25,598,014
<p>Try making it inside the Bash!</p> <p>In case of a C file called t.c, this is very convenient:</p> <p><code>vi t.c &amp;&amp; cc t.c -o t &amp;&amp; ./t</code></p> <p>The and symbols (&amp;&amp;) ensure that one error message breaks the command chain. </p> <p>For Python this might be even easier:</p> <p><code>vi t.py &amp;&amp; python t.py</code></p>
-1
2014-09-01T02:05:15Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
39,241,782
<p>This is what I put in my <code>.vimrc</code> and works like a charm</p> <pre><code>nnoremap &lt;leader&gt;r :w&lt;CR&gt;:!!&lt;CR&gt; </code></pre> <p>Of course you need to run your shell command once before this so it knows what command to execute.</p> <p>Ex:</p> <pre><code>:!node ./test.js </code></pre>
1
2016-08-31T05:58:50Z
[ "python", "vim" ]
VIM: Save and Run at the same time?
601,039
<p>I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.</p> <p>Thanks for your help.</p>
23
2009-03-02T01:54:29Z
40,002,312
<p>In vim, you could simply redirect any range of your current buffer to an external command (be it bash, python, or you own python script).</p> <pre><code># redirect whole buffer to python :%w !python </code></pre> <p>suppose your current buffer contain two lines as below,</p> <pre><code>import numpy as np print np.arange(12).reshape(3,4) </code></pre> <p>then <code>:%w !python</code> will run it, be it saved or not. and print something like below on your terminal, </p> <pre><code>[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] </code></pre> <p>Of course, you could make something persistent, eg, some keymaps.</p> <pre><code>nnoremap &lt;F8&gt; :.w !python&lt;CR&gt; vnoremap &lt;F8&gt; :w !python&lt;CR&gt; </code></pre> <p>first one run current line, second one run visual selection, via python interpreter.</p> <pre><code>#!! be careful, in vim ':w!python' and ':.w !python' are very different, the first write (create or overwrite) a file named 'python' with contents of current buffer, the second redirect the selected cmdline range (here dot ., which mean current line) to external command (here 'python'). </code></pre> <p>for cmdline range, see </p> <pre><code>:h cmdline-ranges </code></pre> <p>not below one, which concerning normal command, not cmdline one.</p> <pre><code>:h command-range </code></pre> <p>inspired by <a href="http://stackoverflow.com/a/19883963/3625404">http://stackoverflow.com/a/19883963/3625404</a></p>
0
2016-10-12T15:18:16Z
[ "python", "vim" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
601,246
<p>BeautifulSoup isn't magic: if the incoming HTML is too horrible then it isn't going to work.</p> <p>In this case, the incoming HTML is exactly that: too broken for BeautifulSoup to figure out what to do. For instance it contains markup like:</p> <p>SCRIPT type=""javascript""</p> <p>(Notice the double quoting.)</p> <p>The BeautifulSoup docs contains a section what you can do if BeautifulSoup can't parse you markup. You'll need to investigate those alternatives.</p>
2
2009-03-02T04:09:28Z
[ "python", "beautifulsoup" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
601,636
<p>I tested this script on BeautifulSoup version '3.0.7a' and it returns what appears to be correct output. I don't know what changed between '3.0.7a' and '3.1.0.1' but give it a try.</p>
0
2009-03-02T08:31:44Z
[ "python", "beautifulsoup" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
601,725
<p>Try with version 3.0.7a as <a href="http://stackoverflow.com/questions/601166/issues-with-beautifulsoup-parsing/601636#601636">Łukasz</a> suggested. BeautifulSoup 3.1 was designed to be compatible with Python 3.0 so they had to change the parser from SGMLParser to HTMLParser which seems more vulnerable to bad HTML.</p> <p>From the <a href="http://www.crummy.com/software/BeautifulSoup/CHANGELOG.html">changelog for BeautifulSoup 3.1</a>:</p> <p>"Beautiful Soup is now based on HTMLParser rather than SGMLParser, which is gone in Python 3. There's some bad HTML that SGMLParser handled but HTMLParser doesn't"</p>
6
2009-03-02T09:16:27Z
[ "python", "beautifulsoup" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
617,959
<pre><code>import urllib from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; page = urllib.urlopen('http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1') &gt;&gt;&gt; soup = BeautifulSoup(page) &gt;&gt;&gt; soup.prettify() </code></pre> <p>In my case by executing the above statements, it returns the entire HTML page.</p>
0
2009-03-06T07:31:58Z
[ "python", "beautifulsoup" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
767,905
<p>I had problems parsing the following code too:</p> <pre><code>&lt;script&gt; function show_ads() { document.write("&lt;div&gt;&lt;sc"+"ript type='text/javascript'src='http://pagead2.googlesyndication.com/pagead/show_ads.js'&gt;&lt;/scr"+"ipt&gt;&lt;/div&gt;"); } &lt;/script&gt; </code></pre> <p>HTMLParseError: bad end tag: u'', at line 26, column 127</p> <p>Sam</p>
1
2009-04-20T11:39:53Z
[ "python", "beautifulsoup" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
1,223,038
<p>Try <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup, so it might work better for you. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p> <p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/" rel="nofollow">Ian Blicking agrees</a>.</p> <p>There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.</p>
4
2009-08-03T15:39:32Z
[ "python", "beautifulsoup" ]
Issues with BeautifulSoup parsing
601,166
<p>I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? </p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.futureshop.ca/catalog/subclass.asp?catid=10607&amp;mfr=&amp;logon=&amp;langid=FR&amp;sort=0&amp;page=1" html = "".join(urllib2.urlopen(url).readlines()) print "-- HTML ------------------------------------------" print html print "-- BeautifulSoup ---------------------------------" print BeautifulSoup(html).prettify() </code></pre> <p>The is the output produced by BeautifulSoup.</p> <pre><code>-- BeautifulSoup --------------------------------- &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script language="JavaScript"&gt; &lt;!-- function highlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_on.gif"; } function unhighlight(img) { document[img].src = "/marketing/sony/images/en/" + img + "_off.gif"; } //--&gt; &lt;/script&gt; </code></pre> <p>Thanks!</p> <p>UPDATE: I am using the following version, which appears to be the latest.</p> <pre><code>__author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.1.0.1" __copyright__ = "Copyright (c) 2004-2009 Leonard Richardson" __license__ = "New-style BSD" </code></pre>
4
2009-03-02T03:13:21Z
3,240,985
<p>Samj: If I get things like <code>HTMLParser.HTMLParseError: bad end tag: u"&lt;/scr' + 'ipt&gt;"</code> I just remove the culprit from markup before I serve it to BeautifulSoup and all is dandy:</p> <pre><code>html = urllib2.urlopen(url).read() html = html.replace("&lt;/scr' + 'ipt&gt;","") soup = BeautifulSoup(html) </code></pre>
1
2010-07-13T20:00:35Z
[ "python", "beautifulsoup" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
601,243
<p>Here's some helpful info to get you started. <a href="http://www.python.org/download/mac/" rel="nofollow">http://www.python.org/download/mac/</a></p>
3
2009-03-02T04:07:28Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
601,250
<p>I recommend using Python Virtual environments, especially if you use a Timecapsule because Timecapsule will back everything up, except modules you added to Python!</p>
2
2009-03-02T04:14:25Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
601,252
<p>One advantage I see in using the "stock" Python that's included with Mac OS X is that it makes deployment to other Macs a piece of cake. I don't know what your deployment scenario is, but for me this is important. My code has to run on any number of Macs at work, and I try to minimize the amount of work it takes to run my code on all of those systems.</p>
9
2009-03-02T04:15:18Z
[ "python", "osx" ]