title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How can I use a DLL file from Python?
252,417
<p>What is the easiest way to use a DLL file from within Python?</p> <p>Specifically, how can this be done <em>without</em> writing any additional wrapper C++ code to expose the functionality to Python?</p> <p>Native Python functionality is strongly preferred over using a third-party library.</p>
105
2008-10-31T02:01:48Z
252,438
<p>ctypes can be used to access dlls, here's a tutorial:</p> <p><a href="http://docs.python.org/library/ctypes.html#module-ctypes">http://docs.python.org/library/ctypes.html#module-ctypes</a></p>
6
2008-10-31T02:18:03Z
[ "python", "dll" ]
How can I use a DLL file from Python?
252,417
<p>What is the easiest way to use a DLL file from within Python?</p> <p>Specifically, how can this be done <em>without</em> writing any additional wrapper C++ code to expose the functionality to Python?</p> <p>Native Python functionality is strongly preferred over using a third-party library.</p>
105
2008-10-31T02:01:48Z
252,444
<p>ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.</p> <p>I would encourage you to check out <a href="http://www.boost.org/doc/libs/1_36_0/libs/python/doc/index.html" rel="nofollow">Boost Python</a>. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) <a href="http://www.microsoft.com/express/vc/" rel="nofollow">C++ compiler from Microsoft</a>.</p>
1
2008-10-31T02:24:51Z
[ "python", "dll" ]
How can I use a DLL file from Python?
252,417
<p>What is the easiest way to use a DLL file from within Python?</p> <p>Specifically, how can this be done <em>without</em> writing any additional wrapper C++ code to expose the functionality to Python?</p> <p>Native Python functionality is strongly preferred over using a third-party library.</p>
105
2008-10-31T02:01:48Z
252,473
<p>For ease of use, <a href="http://docs.python.org/library/ctypes.html">ctypes</a> is the way to go.</p> <p>The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.</p> <pre><code>import ctypes # Load DLL into memory. hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll") # Set up prototype and parameters for the desired function call. # HLLAPI hllApiProto = ctypes.WINFUNCTYPE ( ctypes.c_int, # Return type. ctypes.c_void_p, # Parameters 1 ... ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) # ... thru 4. hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0), # Actually map the call ("HLLAPI(...)") to a Python name. hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams) # This is how you can actually call the DLL function. # Set up the variables and call the Python name with them. p1 = ctypes.c_int (1) p2 = ctypes.c_char_p (sessionVar) p3 = ctypes.c_int (1) p4 = ctypes.c_int (0) hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4)) </code></pre> <p>The <code>ctypes</code> stuff has all the C-type data types (<code>int</code>, <code>char</code>, <code>short</code>, <code>void*</code>, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).</p> <hr> <p>In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.</p> <p>All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an <code>int</code> so, while I specify <code>int</code> as the return type, I can safely ignore it) as per IBM's documentation <a href="http://publib.boulder.ibm.com/infocenter/pcomhelp/v5r9/index.jsp?topic=/com.ibm.pcomm.doc/books/html/emulator_programming08.htm">here</a>. In other words, the C variant of the function would be:</p> <pre><code>int hllApi (void *p1, void *p2, void *p3, void *p4) </code></pre> <p>This makes for a single, simple <code>ctypes</code> function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate <code>ctypes</code> function set up per library function.</p> <p>The return value from <code>WINFUNCTYPE</code> is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in <code>hllApiParams</code> has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the <code>ctypes</code> doco for details</p> <p>Once you have the prototype and parameter information, you can create a Python "callable" <code>hllApi</code> with which to call the function. You simply create the needed variable (<code>p1</code> through <code>p4</code> in my case) and call the function with them.</p>
88
2008-10-31T02:43:41Z
[ "python", "dll" ]
How can I use a DLL file from Python?
252,417
<p>What is the easiest way to use a DLL file from within Python?</p> <p>Specifically, how can this be done <em>without</em> writing any additional wrapper C++ code to expose the functionality to Python?</p> <p>Native Python functionality is strongly preferred over using a third-party library.</p>
105
2008-10-31T02:01:48Z
3,173,926
<p><a href="http://web.archive.org/web/20111006042404/http://www.knowledgetantra.com/component/content/article/2-python/1-call-dll-function-in-python.html">This page</a> is a very simple example of calling functions from a DLL file.</p> <blockquote> <p>It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: <code>add</code> and <code>sub</code> which take two arguments.</p> <p><code>add(a, b)</code> returns addition of two numbers<br/> <code>sub(a, b)</code> returns substraction of two numbers</p> <p>The name of the DLL file will be "demo.dll"</p> <p><strong>Program:</strong></p> <p><code>from ctypes import*</code><br/> <code># give location of dll</code><br/> <code>mydll = cdll.LoadLibrary("C:\\demo.dll")</code><br/> <code>result1= mydll.add(10,1)</code><br/> <code>result2= mydll.sub(10,1)</code><br/> <code>print "Addition value:-"+result1</code><br/> <code>print "Substraction:-"+result2</code></p> <p><strong>Output:</strong></p> <p><code>Addition value:-11</code><br/> <code>Substraction:-9</code></p> </blockquote>
32
2010-07-04T06:28:31Z
[ "python", "dll" ]
How can I use a DLL file from Python?
252,417
<p>What is the easiest way to use a DLL file from within Python?</p> <p>Specifically, how can this be done <em>without</em> writing any additional wrapper C++ code to expose the functionality to Python?</p> <p>Native Python functionality is strongly preferred over using a third-party library.</p>
105
2008-10-31T02:01:48Z
17,157,302
<p>Maybe with <code>Dispatch</code>:</p> <pre><code>from win32com.client import Dispatch zk = Dispatch("zkemkeeper.ZKEM") </code></pre> <p>Where zkemkeeper is a registered DLL file on the system... After that, you can access functions just by calling them:</p> <pre><code>zk.Connect_Net(IP_address, port) </code></pre>
1
2013-06-17T21:38:07Z
[ "python", "dll" ]
Why won't Django 1.0 admin application work?
252,531
<p>I've just started playing with Django and am loosely following the tutorial with my own set of basic requirements. The models I've sketched out so far are a lot more comprehensive than the tutorial, but they compile fine. Otherwise, everything should have been the same.</p> <p>My problem is with the admin application. I can log into it, and view the editable models, but when I click on a model or any of the change/add buttons, I get a 404.</p> <p>This is the exact error I get:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://localhost:8000/admin/auth/user/add/ App u'', model u'auth', not found. </code></pre> <p>These are the relevant files and what is in them:</p> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^daso/', include('daso.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: #(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin(.*)', admin.site.root) ) </code></pre> <p>admin.py</p> <pre><code>from daso.clients.models import Person, Client, Contact from django.contrib import admin admin.site.register(Person) admin.site.register(Client) admin.site.register(Contact) </code></pre> <p>models.py - I'll just show one model</p> <pre><code>class Client(Person): relationships = models.ManyToManyField("Contact", through="Relationship", null=True) disabilities = models.ManyToManyField("Disability", related_name="disability", null=True) medical_issues = models.ManyToManyField("MedicalIssue", related_name="medical_issue", null=True) medicare_num = models.CharField(max_length=15, blank=True) insurance = models.OneToOneField("Insurance", null=True, blank=True) medications = models.ManyToManyField("Medication", through="Medication_Details", null=True) def __unicode__(self): client = u"[Client[id: ", self.id, " name: ", self.first_name, " ", self.last_name, "]" return client </code></pre> <p>settings.py</p> <pre><code>INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'daso.clients', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) </code></pre> <p>Those should be the relevant files/sections of files. If anyone has an idea about WHY I'm getting a 404, please enlighten me?</p> <p>Note, when pasting in here, installed apps had the last 2 apps tabbed instead of spaced*4, and when reloading the admin page it worked for half a second then 404'd again. Strange. Ideas?</p>
5
2008-10-31T03:35:19Z
252,621
<p>It's because you left out a <code>/</code> in <code>urls.py</code>. Change the admin line to the following:</p> <pre><code>(r'^admin/(.*)', admin.site.root), </code></pre> <p>I checked this on my server and got the same error with your line from <code>urls.py</code>.</p>
12
2008-10-31T04:50:27Z
[ "python", "django", "admin" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
252,704
<p><code>append</code> appends a single element. <code>extend</code> appends a list of elements.</p> <p>Note that if you pass a list to append, it still adds one element:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; a.append([4, 5, 6]) &gt;&gt;&gt; a [1, 2, 3, [4, 5, 6]] </code></pre>
72
2008-10-31T05:57:32Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
252,705
<p><code>append</code> adds an element to a list, <code>extend</code> concatenates the first list with another list (or another iterable not necessarily a list.)</p> <pre><code>&gt;&gt;&gt; li = ['a', 'b', 'mpilgrim', 'z', 'example'] &gt;&gt;&gt; li ['a', 'b', 'mpilgrim', 'z', 'example'] &gt;&gt;&gt; li.append("new") &gt;&gt;&gt; li ['a', 'b', 'mpilgrim', 'z', 'example', 'new'] &gt;&gt;&gt; li.insert(2, "new") &gt;&gt;&gt; li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new'] &gt;&gt;&gt; li.extend(["two", "elements"]) &gt;&gt;&gt; li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'] </code></pre> <p>From <a href="http://www.diveintopython.net/native_data_types/lists.html#d0e5887">Dive into Python</a>.</p>
388
2008-10-31T05:57:37Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
252,711
<p><a href="https://docs.python.org/2/library/array.html?#array.array.append"><code>append</code></a>: Appends object at end.</p> <pre><code>x = [1, 2, 3] x.append([4, 5]) print (x) </code></pre> <p>gives you: <code>[1, 2, 3, [4, 5]]</code></p> <hr> <p><a href="https://docs.python.org/2/library/array.html?#array.array.extend"><code>extend</code></a>: Extends list by appending elements from the iterable.</p> <pre><code>x = [1, 2, 3] x.extend([4, 5]) print (x) </code></pre> <p>gives you: <code>[1, 2, 3, 4, 5]</code></p>
2,392
2008-10-31T06:02:25Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
252,918
<p>Good answers, but don't forget, any iterable will do for <code>extend</code> (not just list):</p> <pre><code>l.extend(xrange(5)) </code></pre>
50
2008-10-31T09:03:22Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
262,132
<p>And in this context it can also be good to remember that strings are also iterable.</p> <pre><code>&gt;&gt;&gt; a = [1, 2] &gt;&gt;&gt; a [1, 2] &gt;&gt;&gt; a.extend('hey') &gt;&gt;&gt; a [1, 2, 'h', 'e', 'y'] </code></pre>
197
2008-11-04T15:19:52Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
5,605,403
<p>Like <code>Ali A</code> said, any iterable will do for the extend, here is an example for dictionary argument,</p> <pre><code>&gt;&gt;&gt; li=[1,2,3] &gt;&gt;&gt; li.extend({4:5,6:7}) &gt;&gt;&gt; li [1, 2, 3, 4, 6] &gt;&gt;&gt; </code></pre> <p>as you can see, only <code>keys</code> are added to the list.</p>
31
2011-04-09T13:46:02Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
12,045,242
<p>The following two snippets are semantically equivalent:</p> <pre><code> for item in iterator: a_list.append(item) </code></pre> <p>and</p> <pre><code>a_list.extend(iterator) </code></pre> <p>The latter may be faster as the loop is implemented in C.</p>
28
2012-08-20T21:11:00Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
16,510,635
<p><code>extend()</code> can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way:</p> <p>from</p> <pre><code>list2d = [[1,2,3],[4,5,6], [7], [8,9]] </code></pre> <p>you want</p> <pre><code>&gt;&gt;&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>You may use <code>itertools.chain.from_iterable()</code> to do so. This method's output is an iterator. It's implementation is equivalent to</p> <pre><code>def from_iterable(iterables): # chain.from_iterable(['ABC', 'DEF']) --&gt; A B C D E F for it in iterables: for element in it: yield element </code></pre> <p>Back to our example, we can do </p> <pre><code>import itertools list2d = [[1,2,3],[4,5,6], [7], [8,9]] merged = list(itertools.chain.from_iterable(list2d)) </code></pre> <p>and get the wanted list.</p> <p>Here is how equivalently <code>extend()</code> can be used with an iterator argument:</p> <pre><code>merged = [] merged.extend(itertools.chain.from_iterable(list2d)) print(merged) &gt;&gt;&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
10
2013-05-12T18:21:40Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
16,511,403
<p>append(object) - Updates the list by adding an object to the list.</p> <pre><code>x = [20] # list passed to the append(object) method is treated as a single object. x.append([21,22,23]) #hence the resultant list length will be 2 print x --&gt; [20, [21,22,23]] </code></pre> <p>extend(list) - Essentially concatenates 2 lists.</p> <pre><code>x = [20] #the parameter passed to extend(list) method is treated as a list. #eventually it is 2 list's being concatenated. x.extend([21,22,23]) #here the resultant list's length is 4 print x [20,21,22,23] </code></pre>
10
2013-05-12T19:51:07Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
18,442,908
<p>You can use "+" for returning extend, instead of extending in place.</p> <pre><code>l1=range(10) l1+[11] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11] l2=range(10,1,-1) l1+l2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2] </code></pre> <p>Similarly <code>+=</code> for in place behavior, but with slight differences from <code>append</code> &amp; <code>extend</code>. One of the biggest differences of <code>+=</code> from <code>append</code> and <code>extend</code> is when it is used in function scopes, see this blog post:</p> <p><a href="https://www.toptal.com/python/top-10-mistakes-that-python-programmers-make?utm_medium=referral&amp;utm_source=zeef.com&amp;utm_campaign=ZEEF" rel="nofollow">https://www.toptal.com/python/top-10-mistakes-that-python-programmers-make?utm_medium=referral&amp;utm_source=zeef.com&amp;utm_campaign=ZEEF</a></p>
20
2013-08-26T11:21:12Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
19,707,477
<p>The append() method adds a single item to the end of the list. </p> <pre><code>x = [1, 2, 3] x.append([4, 5]) x.append('abc') print x # gives you [1, 2, 3, [4, 5], 'abc'] </code></pre> <p>The extend() method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list has methods that operate on it.)</p> <pre><code>x = [1, 2, 3] x.extend([4, 5]) x.extend('abc') print x # gives you [1, 2, 3, 4, 5, 'a', 'b', 'c'] </code></pre> <p>From <a href="http://rads.stackoverflow.com/amzn/click/1430224150">Dive Into Python</a></p>
22
2013-10-31T13:12:10Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
24,632,188
<p>This is the equivalent of <code>append</code> and <code>extend</code> using the <code>+</code> operator:</p> <pre><code>&gt;&gt;&gt; x = [1,2,3] &gt;&gt;&gt; x [1, 2, 3] &gt;&gt;&gt; x = x + [4,5,6] # Extend &gt;&gt;&gt; x [1, 2, 3, 4, 5, 6] &gt;&gt;&gt; x = x + [[7,8]] # Append &gt;&gt;&gt; x [1, 2, 3, 4, 5, 6, [7, 8]] </code></pre>
8
2014-07-08T12:42:52Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
25,144,368
<p>An interesting point that has been hinted, but not explained, is that extend is faster than append. For any loop that has append inside should be considered to be replaced by list.extend(processed_elements).</p> <p>Bear in mind that apprending new elements might result in the realloaction of the whole list to a better location in memory. If this is done several times because we are appending 1 element at a time, overall performance suffers. In this sense, list.extend is analogous to "".join(stringlist).</p>
5
2014-08-05T16:58:25Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
25,920,729
<pre><code>list1 = [1,2,3,4,5] list2 = ["a","b","c","d","e"] </code></pre> <p>append:</p> <pre><code>print list.append(list2) </code></pre> <p>output : [1,2,3,4,5,["a","b","c","d","e"]]</p> <p>extend :</p> <pre><code>print list1.extend(list2) </code></pre> <p>output : [1,2,3,4,5,"a","b","c","d","e"]</p>
2
2014-09-18T19:19:57Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
26,397,913
<p>Append add the entire data at once. The whole data will be added to the newly created index. On the other hand Extend as it name suggests extends the current array. for example</p> <pre><code>list1 = [123, 456, 678] list2 = [111,222] </code></pre> <p>when append we get:</p> <pre><code>result = [123,456,678,[111,222]] </code></pre> <p>while on extend we get:</p> <pre><code>result = [123,456,678,111,222] </code></pre>
3
2014-10-16T06:49:07Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
28,119,966
<blockquote> <h1>What is the difference between the list methods append and extend?</h1> </blockquote> <ul> <li><code>append</code> adds its argument as a single element to the end of a list. The length of the list itself will increase by one.</li> <li><code>extend</code> iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument.</li> </ul> <h1><code>append</code></h1> <p>The <code>list.append</code> method appends an object to the end of the list.</p> <pre><code>my_list.append(object) </code></pre> <p>Whatever the object is, whether a number, a string, another list, or something else, it gets added onto the end of <code>my_list</code> as a single entry on the list. </p> <pre><code>&gt;&gt;&gt; my_list ['foo', 'bar'] &gt;&gt;&gt; my_list.append('baz') &gt;&gt;&gt; my_list ['foo', 'bar', 'baz'] </code></pre> <p>So keep in mind that a list is an object. If you append another list onto a list, the first list will be a single object at the end of the list (which may not be what you want):</p> <pre><code>&gt;&gt;&gt; another_list = [1, 2, 3] &gt;&gt;&gt; my_list.append(another_list) &gt;&gt;&gt; my_list ['foo', 'bar', 'baz', [1, 2, 3]] #^^^^^^^^^--- single item on end of list. </code></pre> <h1><code>extend</code></h1> <p>The <code>list.extend</code> method extends a list by appending elements from an iterable:</p> <pre><code>my_list.extend(iterable) </code></pre> <p>So with extend, each element of the iterable gets appended onto the list. For example:</p> <pre><code>&gt;&gt;&gt; my_list ['foo', 'bar'] &gt;&gt;&gt; another_list = [1, 2, 3] &gt;&gt;&gt; my_list.extend(another_list) &gt;&gt;&gt; my_list ['foo', 'bar', 1, 2, 3] </code></pre> <p>Keep in mind that a string is an iterable, so if you extend a list with a string, you'll append each character as you iterate over the string (which may not be what you want):</p> <pre><code>&gt;&gt;&gt; my_list.extend('baz') &gt;&gt;&gt; my_list ['foo', 'bar', 1, 2, 3, 'b', 'a', 'z'] </code></pre> <h1>Operator Overload, <code>__and__</code>, (<code>+</code>) and <code>__iand__</code> (<code>+=</code>)</h1> <p>Both <code>+</code> and <code>+=</code> operators are defined for <code>list</code>. They are semantically similar to extend.</p> <p><code>my_list + another_list</code> creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list. </p> <p><code>my_list += another_list</code> modifies the list in-place (it <em>is</em> the in-place operator, and lists are mutable objects, as we've seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.</p> <h1>Performance</h1> <p>You may wonder what is more performant, since append can be used to achieve the same outcome as extend. The following functions do the same thing:</p> <pre><code>def append(alist, iterable): for item in iterable: alist.append(item) def extend(alist, iterable): alist.extend(iterable) </code></pre> <p>So let's time them:</p> <pre><code>import timeit &gt;&gt;&gt; min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz"))) 2.867846965789795 &gt;&gt;&gt; min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz"))) 0.8060121536254883 </code></pre> <h1>Conclusion</h1> <p>We see that <code>extend</code> can run much faster than <code>append</code>, and it is semantically clearer, so it is preferred <em>when you intend to append each element in an iterable to a list.</em> </p> <p>If you only have a single element to add to the list, use <code>append</code>.</p>
58
2015-01-23T22:44:37Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
32,049,895
<pre><code>Append a dictionary to another one: &gt;&gt;&gt;def asd(): dic = {1:'a',2:'b',3:'c',4:'a'} newdic={5:'v',1:'aa'} for i in dic.keys(): if not newdic.has_key(dic[i]): newdic[i] = dic[i] print "appended one:",newdic &gt;&gt;&gt;asd() appended one: {1: 'a', 2: 'b', 3: 'c', 4: 'a', 5: 'v'} </code></pre>
3
2015-08-17T12:02:46Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
37,787,163
<p><strong><em>append()</em></strong> : It is basically used in python to add, one element.</p> <blockquote> <p>Example 1:</p> </blockquote> <pre><code>&gt;&gt;a=[1,2,3,4] &gt;&gt;a.append(5) &gt;&gt;print(a) &gt;&gt;a=[1,2,3,4,5] </code></pre> <blockquote> <p>Example 2:</p> </blockquote> <pre><code>&gt;&gt;a=[1,2,3,4] &gt;&gt;a.append(5,6) &gt;&gt;print(a) &gt;&gt;a=[1,2,3,4,[5,6]] </code></pre> <p><br><br> <strong><em>extend()</em></strong> : Where extend(), is used to merged to lists or insert multiple elements in one list.</p> <blockquote> <p>Example 1:</p> </blockquote> <pre><code>&gt;&gt;a=[1,2,3,4] &gt;&gt;b=[5,6,7,8] &gt;&gt;a.extend(b) &gt;&gt;print(a) &gt;&gt;a=[1,2,3,4,5,6,7,8] </code></pre> <blockquote> <p>Example 2:</p> </blockquote> <pre><code>&gt;&gt;a=[1,2,3,4] &gt;&gt;a.extend(5,6) &gt;&gt;print(a) &gt;&gt;a=[1,2,3,4,5,6] </code></pre>
1
2016-06-13T10:17:46Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
39,256,096
<p>The method "append" adds its parameter as a <strong>single element</strong> to the list, while "extend" gets a list and adds its content.</p> <p>for example, </p> <blockquote> <p><strong>extend</strong></p> </blockquote> <pre><code> letters = ['a', 'b'] letters.extend(['c', 'd']) print(letters) # ['a', 'b', 'c', 'd'] </code></pre> <blockquote> <p><strong>append</strong> </p> </blockquote> <pre><code> letters.append(['e', 'f']) print(letters) # ['a', 'b', 'c', 'd', ['e', 'f']] </code></pre>
0
2016-08-31T17:55:10Z
[ "python", "list", "append", "extend" ]
append vs. extend
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
1,581
2008-10-31T05:55:36Z
39,256,397
<p>extend(L) extends the list by appending all the items in the given list L.</p> <pre><code>&gt;&gt;&gt; a [1, 2, 3] a.extend([4) #is eqivalent of a[len(a):] = [4] &gt;&gt;&gt;a [1, 2, 3, 4] a =[1,2,3] &gt;&gt;&gt; a [1, 2, 3] &gt;&gt;&gt; a[len(a):] = [4] &gt;&gt;&gt; a [1, 2, 3, 4] </code></pre>
0
2016-08-31T18:14:42Z
[ "python", "list", "append", "extend" ]
Finding invocations of a certain function in a c++ file using python
252,951
<p>I need to find all occurrences of a function call in a c++ file using python, and extract the arguments for each call.<br /> I'm playing with the <a href="http://www.language-binding.net/pygccxml/pygccxml.html" rel="nofollow">pygccxml</a> package, and extracting the arguments given a string with the function call is extremely easy:</p> <pre><code>from pygccxml.declarations import call_invocation def test_is_call_invocation(call): if call_invocation.is_call_invocation(call): print call_invocation.name(call) for arg in call_invocation.args(call): print " ",arg else: print "not a function invocation" </code></pre> <p>What I couldn't find is a way of getting the calls parsing a file: </p> <pre><code>from pygccxml import parser from pygccxml import declarations decls = parser.parse( ['main.cpp'] ) # ... </code></pre> <p>Is there a way to find the calls to a certain function using the pygccxml package?<br /> Or maybe that package is an overkill for what I'm trying to do :) and there's a much simpler way? Finding the function calls with a regular expression is, I'm afraid, much trickier than it might look at a first sight...</p>
1
2008-10-31T09:24:45Z
252,996
<p>XML-GCC can't do that, because it only reports the data types (and function signatures). It ignores the function bodies. To see that, create a.cc:</p> <pre><code>void foo() {} void bar() { foo(); } </code></pre> <p>and then run <code>gccxml a.cc -fxml=a.xml</code>. Look at the generated a.xml, to see that the only mentioning of foo (or its id) is in the declaration of foo.</p> <p>An alternative might be available in codeviz (<a href="http://www.csn.ul.ie/~mel/projects/codeviz/" rel="nofollow">http://www.csn.ul.ie/~mel/projects/codeviz/</a>). It consists of a patch to gcc 3.4.6 that generates call dependency information - plus some perl scripts that generate graphviz input; the latter you can safely ignore.</p> <p>As yet another alternative (which doesn't need gcc modifications) you could copy the approach from egypt (<a href="http://www.gson.org/egypt/" rel="nofollow">http://www.gson.org/egypt/</a>); this parses GCC RTL dumps. It should work with any recent GCC, however, it might be that you don't get calls to inline functions.</p> <p>In any case, with these approaches, you won't get "calls" to macros, but that might be actually the better choice.</p>
2
2008-10-31T09:56:52Z
[ "c++", "python", "parsing" ]
How to configure the import path in Visual Studio IronPython projects
253,018
<p>I have built the IronPythonIntegration solution that comes with the Visual Studio 2005 SDK (as explained at <a href="http://www.izume.com/2007/10/13/integrating-ironpython-with-visual-studio-2005" rel="nofollow">http://www.izume.com/2007/10/13/integrating-ironpython-with-visual-studio-2005</a>), and I can now use IronPython projects inside Visual Studio 2005. However, to let a Python file import from the standard library I need to include these two lines first: </p> <pre><code>import sys sys.path.append('c:\Python24\lib') </code></pre> <p>and similarly for any other folders I want to be able to import from. </p> <p>Does anyone know a way to set up import paths so that all IronPython projects automatically pick them up?</p>
3
2008-10-31T10:08:50Z
253,273
<p>Set the environment variable IRONPYTHONPATH in your operating system to 'c:\Python24\lib'. (Or anywhere else you need).</p>
2
2008-10-31T12:06:12Z
[ "python", "visual-studio", "ironpython", "ironpython-studio" ]
What Python bindings are there for CVS or SVN?
253,375
<p>I once did a cursory search and found no good CVS bindings for Python. I wanted to be able to write helper scripts to do some fine-grained manipulation of the repository and projects in it. I had to resort to using <code>popen</code> and checking <code>stdout</code> and <code>stderr</code> and then parsing those. It was messy and error-prone.</p> <p>Are there any good quality modules for CVS integration for Python? Which module do you prefer and why?</p> <p>While I am at it, is there a good Subversion integration module for Python? My understanding is that Subversion has a great API for such things.</p>
13
2008-10-31T12:51:14Z
253,390
<p>For cvs, <a href="http://pycvs.sourceforge.net/" rel="nofollow">pyCVS</a> may be worth a look.</p> <p>For svn, there is <a href="http://pysvn.tigris.org/" rel="nofollow">pysvn</a>, which is pretty good.</p>
8
2008-10-31T13:01:31Z
[ "python", "svn", "version-control", "cvs" ]
What Python bindings are there for CVS or SVN?
253,375
<p>I once did a cursory search and found no good CVS bindings for Python. I wanted to be able to write helper scripts to do some fine-grained manipulation of the repository and projects in it. I had to resort to using <code>popen</code> and checking <code>stdout</code> and <code>stderr</code> and then parsing those. It was messy and error-prone.</p> <p>Are there any good quality modules for CVS integration for Python? Which module do you prefer and why?</p> <p>While I am at it, is there a good Subversion integration module for Python? My understanding is that Subversion has a great API for such things.</p>
13
2008-10-31T12:51:14Z
254,092
<p><a href="http://progetti.arstecnica.it/tailor" rel="nofollow">Tailor</a>, a Python program which lets different version control systems interoperate, simply calls the external programs <code>cvs</code> and <code>svn</code> when working with repositories of those formats. This seems pretty ugly, but reduces Tailor's dependencies from "requires ____ bindings" to "requires working system".</p>
1
2008-10-31T16:23:37Z
[ "python", "svn", "version-control", "cvs" ]
Looking a generic Python script to add a field and populate the field with conditions
253,761
<p>I am looking for a script to allow users to add a text field to a .dbf table(e.g. landuse categories) and allow them to input/update the rows basing on what values in the GRIDCODE (numeric categories) field they think should be assigned into text categories.i.e. if GRIDCODE value is 4, the corresponding field value of landuse/landclass is “forest” etc.</p> <p>Is there such a script in existence?</p> <p>Or, do you have something similar that I can customise to create a new script?</p> <p>The script will accept users' interactive input as parameters passed into the script.</p> <p>Sincerely, David</p>
0
2008-10-31T14:42:28Z
253,837
<p>When you say dbf table, are you referring to ESRI shape file dbf files, which are in fact dbase files? If so you could implement such a thing pretty easily with the python wrapper for <a href="http://shapelib.maptools.org/" rel="nofollow">shapelib,</a> which also supports dbf files.</p>
2
2008-10-31T15:03:26Z
[ "python", "sql", "sql-update" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
254,357
<p>The low level way:</p> <pre><code>from __future__ import with_statement with open(filename1) as f1: with open(filename2) as f2: if f1.read() == f2.read(): ... </code></pre> <p>The high level way:</p> <pre><code>import filecmp if filecmp.cmp(filename1, filename2, shallow=False): ... </code></pre>
40
2008-10-31T17:50:04Z
[ "python" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
254,362
<pre> <code> f = open(filename1, "r").read() f2 = open(filename2,"r").read() print f == f2 </code> </pre>
1
2008-10-31T17:52:16Z
[ "python" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
254,373
<p>If you're going for even basic efficiency, you probably want to check the file size first:</p> <pre><code>if os.path.getsize(filename1) == os.path.getsize(filename2): if open('filename1','r').read() == open('filename2','r').read(): # Files are the same. </code></pre> <p>This saves you reading every line of two files that aren't even the same size, and thus can't be the same.</p> <p>(Even further than that, you could call out to a fast MD5sum of each file and compare those, but that's not "in Python", so I'll stop here.)</p>
20
2008-10-31T17:56:15Z
[ "python" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
254,374
<p>For larger files you could compute a <a href="http://docs.python.org/library/md5.html" rel="nofollow">MD5</a> or <a href="http://docs.python.org/library/sha.html" rel="nofollow">SHA</a> hash of the files.</p>
1
2008-10-31T17:56:33Z
[ "python" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
254,518
<p>I would use a hash of the file's contents using MD5.</p> <pre><code>import hashlib def checksum(f): md5 = hashlib.md5() md5.update(open(f).read()) return md5.hexdigest() def is_contents_same(f1, f2): return checksum(f1) == checksum(f2) if not is_contents_same('foo.txt', 'bar.txt'): print 'The contents are not the same!' </code></pre>
1
2008-10-31T18:53:52Z
[ "python" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
254,567
<p>Since I can't comment on the answers of others I'll write my own.</p> <p>If you use md5 you definitely must not just md5.update(f.read()) since you'll use too much memory.</p> <pre><code>def get_file_md5(f, chunk_size=8192): h = hashlib.md5() while True: chunk = f.read(chunk_size) if not chunk: break h.update(chunk) return h.hexdigest() </code></pre>
5
2008-10-31T19:06:03Z
[ "python" ]
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
<p>I don't care what the differences are. I just want to know whether the contents are different.</p>
29
2008-10-31T17:47:39Z
255,210
<p>This is a functional-style file comparison function. It returns instantly False if the files have different sizes; otherwise, it reads in 4KiB block sizes and returns False instantly upon the first difference:</p> <pre><code>from __future__ import with_statement import os import itertools, functools, operator def filecmp(filename1, filename2): "Do the two files have exactly the same contents?" with open(filename1, "rb") as fp1, open(filename2, "rb") as fp2: if os.fstat(fp1.fileno()).st_size != os.fstat(fp2.fileno()).st_size: return False # different sizes ∴ not equal fp1_reader= functools.partial(fp1.read, 4096) fp2_reader= functools.partial(fp2.read, 4096) cmp_pairs= itertools.izip(iter(fp1_reader, ''), iter(fp2_reader, '')) inequalities= itertools.starmap(operator.ne, cmp_pairs) return not any(inequalities) if __name__ == "__main__": import sys print filecmp(sys.argv[1], sys.argv[2]) </code></pre> <p>Just a different take :)</p>
5
2008-10-31T23:03:01Z
[ "python" ]
Tiny python executable?
254,635
<p>I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb).</p> <p>Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something similiar?</p>
8
2008-10-31T19:20:30Z
254,723
<p>If you recompile pythonxy.dll, you can omit modules that you don't need. Going by size, stripping off the unicode database and the CJK codes creates the largest code reduction. This, of course, assumes that you don't need these. Remove the modules from the pythoncore project, and also remove them from PC/config.c</p>
9
2008-10-31T19:51:46Z
[ "python", "executable", "pyinstaller" ]
Tiny python executable?
254,635
<p>I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb).</p> <p>Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something similiar?</p>
8
2008-10-31T19:20:30Z
255,582
<p>You can't go too low in size, because you obviously need to bundle the Python interpreter in, and only that takes a considerable amount of space.</p> <p>I had the same concerns once, and there are two approaches:</p> <ol> <li>Install Python on the computers you want to run on and only distribute the scripts</li> <li>Install Python in the internal network on some shared drive, and rig the users' PATH to recognize where Python is located. With some installation script / program trickery, users can be completely oblivious to this, and you'll get to distribute minimal applications.</li> </ol>
1
2008-11-01T06:32:59Z
[ "python", "executable", "pyinstaller" ]
Tiny python executable?
254,635
<p>I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb).</p> <p>Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something similiar?</p>
8
2008-10-31T19:20:30Z
4,902,830
<p>Using a earlier Python version will also decrease the size considerably if your really needing a small file size. I don't recommend using a very old version, Python2.3 would be the best option. I got my Python executable size to 700KB's! Also I prefer Py2Exe over Pyinstaller.</p>
1
2011-02-04T20:54:15Z
[ "python", "executable", "pyinstaller" ]
How to embed a tag within a url templatetag in a django template?
254,895
<p>How do I embed a tag within a <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow" title="url templatetag">url templatetag</a> in a django template?</p> <p>Django 1.0 , Python 2.5.2</p> <p>In views.py</p> <pre><code>def home_page_view(request): NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"} variables = RequestContext(request, {'NUP':NUP}) return render_to_response('home_page.html', variables) </code></pre> <p>In home_page.html, the following</p> <pre><code>NUP.HOMEPAGE = {{ NUP.HOMEPAGE }} </code></pre> <p>is displayed as </p> <pre><code>NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view </code></pre> <p>and the following url named pattern works ( as expected ),</p> <pre><code>url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %} </code></pre> <p>and is displayed as </p> <pre><code>url template tag for NUP.HOMEPAGE = /myhomepage/ </code></pre> <p>but when <code>{{ NUP.HOMEPAGE }}</code> is embedded within a <code>{% url ... %}</code> as follows</p> <pre><code>url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %} </code></pre> <p>this results in a template syntax error</p> <pre><code>TemplateSyntaxError at /myhomepage/ Could not parse the remainder: '}}' from '}}' Request Method: GET Request URL: http://localhost:8000/myhomepage/ Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '}}' from '}}' Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529 Python Executable: C:\Python25\python.exe Python Version: 2.5.2 </code></pre> <p>I was expecting <code>{% url {{ NUP.HOMEPAGE }} %}</code> to resolve to <code>{% url named-url-pattern-string-for-my-home-page-view %}</code> at runtime and be displayed as <code>/myhomepage/</code>.</p> <p>Are embedded tags not supported in django? </p> <p>is it possible to write a custom url template tag with embedded tags support to make this work?</p> <p><code>{% url {{ NUP.HOMEPAGE }} %}</code></p>
2
2008-10-31T20:45:04Z
254,942
<p>That's seems way too dynamic. You're supposed to do</p> <pre><code>{% url named-url-pattern-string-for-my-home-page-view %} </code></pre> <p>And leave it at that. Dynamically filling in the name of the URL tag is -- frankly -- a little odd. </p> <p>If you want to use any of a large number of different URL tags, you'd have to do something like this</p> <pre><code>{% if tagoption1 %}&lt;a href="{% url named-url-1 %}"&gt;Text&lt;/a&gt;{% endif %} </code></pre> <p>Which seems long-winded because, again, the dynamic thing you're trying to achieve seems a little odd.</p> <p>If you have something like a "families" or "clusters" of pages, perhaps separate template directories would be a way to manage this better. Each of the clusters of pages can inherit from a base templates and override small things like this navigation feature to keep all of the pages in the cluster looking similar but having one navigation difference for a "local home".</p>
0
2008-10-31T20:59:47Z
[ "python", "django", "url", "templates", "templatetag" ]
How to embed a tag within a url templatetag in a django template?
254,895
<p>How do I embed a tag within a <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow" title="url templatetag">url templatetag</a> in a django template?</p> <p>Django 1.0 , Python 2.5.2</p> <p>In views.py</p> <pre><code>def home_page_view(request): NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"} variables = RequestContext(request, {'NUP':NUP}) return render_to_response('home_page.html', variables) </code></pre> <p>In home_page.html, the following</p> <pre><code>NUP.HOMEPAGE = {{ NUP.HOMEPAGE }} </code></pre> <p>is displayed as </p> <pre><code>NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view </code></pre> <p>and the following url named pattern works ( as expected ),</p> <pre><code>url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %} </code></pre> <p>and is displayed as </p> <pre><code>url template tag for NUP.HOMEPAGE = /myhomepage/ </code></pre> <p>but when <code>{{ NUP.HOMEPAGE }}</code> is embedded within a <code>{% url ... %}</code> as follows</p> <pre><code>url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %} </code></pre> <p>this results in a template syntax error</p> <pre><code>TemplateSyntaxError at /myhomepage/ Could not parse the remainder: '}}' from '}}' Request Method: GET Request URL: http://localhost:8000/myhomepage/ Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '}}' from '}}' Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529 Python Executable: C:\Python25\python.exe Python Version: 2.5.2 </code></pre> <p>I was expecting <code>{% url {{ NUP.HOMEPAGE }} %}</code> to resolve to <code>{% url named-url-pattern-string-for-my-home-page-view %}</code> at runtime and be displayed as <code>/myhomepage/</code>.</p> <p>Are embedded tags not supported in django? </p> <p>is it possible to write a custom url template tag with embedded tags support to make this work?</p> <p><code>{% url {{ NUP.HOMEPAGE }} %}</code></p>
2
2008-10-31T20:45:04Z
254,948
<p>Maybe you could try passing the final URL to the template, instead?</p> <p>Something like this:</p> <pre><code>from django.core.urlresolvers import reverse def home_page_view(request): NUP={"HOMEPAGE": reverse('named-url-pattern-string-for-my-home-page-view')} variables = RequestContext(request, {'NUP':NUP}) return render_to_response('home_page.html', variables) </code></pre> <p>Then in the template, the <code>NUP.HOMEPAGE</code> should the the url itself.</p>
2
2008-10-31T21:00:30Z
[ "python", "django", "url", "templates", "templatetag" ]
How to embed a tag within a url templatetag in a django template?
254,895
<p>How do I embed a tag within a <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow" title="url templatetag">url templatetag</a> in a django template?</p> <p>Django 1.0 , Python 2.5.2</p> <p>In views.py</p> <pre><code>def home_page_view(request): NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"} variables = RequestContext(request, {'NUP':NUP}) return render_to_response('home_page.html', variables) </code></pre> <p>In home_page.html, the following</p> <pre><code>NUP.HOMEPAGE = {{ NUP.HOMEPAGE }} </code></pre> <p>is displayed as </p> <pre><code>NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view </code></pre> <p>and the following url named pattern works ( as expected ),</p> <pre><code>url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %} </code></pre> <p>and is displayed as </p> <pre><code>url template tag for NUP.HOMEPAGE = /myhomepage/ </code></pre> <p>but when <code>{{ NUP.HOMEPAGE }}</code> is embedded within a <code>{% url ... %}</code> as follows</p> <pre><code>url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %} </code></pre> <p>this results in a template syntax error</p> <pre><code>TemplateSyntaxError at /myhomepage/ Could not parse the remainder: '}}' from '}}' Request Method: GET Request URL: http://localhost:8000/myhomepage/ Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '}}' from '}}' Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529 Python Executable: C:\Python25\python.exe Python Version: 2.5.2 </code></pre> <p>I was expecting <code>{% url {{ NUP.HOMEPAGE }} %}</code> to resolve to <code>{% url named-url-pattern-string-for-my-home-page-view %}</code> at runtime and be displayed as <code>/myhomepage/</code>.</p> <p>Are embedded tags not supported in django? </p> <p>is it possible to write a custom url template tag with embedded tags support to make this work?</p> <p><code>{% url {{ NUP.HOMEPAGE }} %}</code></p>
2
2008-10-31T20:45:04Z
751,683
<p>Posted a bug to Django. They should be able to fix this on their side.</p> <p><a href="http://code.djangoproject.com/ticket/10823" rel="nofollow">http://code.djangoproject.com/ticket/10823</a></p>
0
2009-04-15T13:28:15Z
[ "python", "django", "url", "templates", "templatetag" ]
Converting datetime to POSIX time
255,035
<p>How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.</p>
36
2008-10-31T21:38:02Z
255,053
<pre><code>import time, datetime d = datetime.datetime.now() print time.mktime(d.timetuple()) </code></pre>
44
2008-10-31T21:44:35Z
[ "python", "datetime", "posix" ]
Converting datetime to POSIX time
255,035
<p>How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.</p>
36
2008-10-31T21:38:02Z
5,872,022
<p>For UTC calculations, <code>calendar.timegm</code> is the inverse of <code>time.gmtime</code>.</p> <pre><code>import calendar, datetime d = datetime.datetime.utcnow() print calendar.timegm(d.timetuple()) </code></pre>
19
2011-05-03T15:39:15Z
[ "python", "datetime", "posix" ]
Converting datetime to POSIX time
255,035
<p>How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.</p>
36
2008-10-31T21:38:02Z
14,369,386
<p>In python, time.time() can return seconds as a floating point number that includes a decimal component with the microseconds. In order to convert a datetime back to this representation, you have to add the microseconds component because the direct timetuple doesn't include it.</p> <pre><code>import time, datetime posix_now = time.time() d = datetime.datetime.fromtimestamp(posix_now) no_microseconds_time = time.mktime(d.timetuple()) has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001 print posix_now print no_microseconds_time print has_microseconds_time </code></pre>
3
2013-01-16T22:52:43Z
[ "python", "datetime", "posix" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
255,154
<p>You can use:</p> <pre><code>sys.stdout.write('h') sys.stdout.write('m') </code></pre>
147
2008-10-31T22:35:49Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
255,172
<p>Just a comment. In <a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html">Python 3</a>, you will use</p> <pre><code>print('h', end='') </code></pre> <p>to suppress the endline terminator, and</p> <pre><code>print('a', 'b', 'c', sep='') </code></pre> <p>to suppress the whitespace separator between items.</p>
186
2008-10-31T22:44:14Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
255,199
<p>Greg is right-- you can use sys.stdout.write</p> <p>Perhaps, though, you should consider refactoring your algorithm to accumulate a list of &lt;whatevers&gt; and then</p> <pre><code>lst = ['h', 'm'] print "".join(lst) </code></pre>
33
2008-10-31T22:53:52Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
255,306
<pre><code>Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; print "hello",; print "there" hello there &gt;&gt;&gt; print "hello",; sys.stdout.softspace=False; print "there" hellothere </code></pre> <p>But really, you should use <code>sys.stdout.write</code> directly.</p>
18
2008-11-01T00:21:28Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
255,336
<p>For completeness, one other way is to clear the softspace value after performing the write.</p> <pre><code>import sys print "hello", sys.stdout.softspace=0 print "world", print "!" </code></pre> <p>prints <code>helloworld !</code></p> <p>Using stdout.write() is probably more convenient for most cases though.</p>
13
2008-11-01T00:43:51Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
410,850
<p>Or use a <code>+</code>, i.e.:</p> <pre><code>&gt;&gt;&gt; print 'me'+'no'+'likee'+'spacees'+'pls' menolikeespaceespls </code></pre> <p>Just make sure all are concatenate-able objects.</p>
15
2009-01-04T11:27:42Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
1,036,396
<p>Regain control of your console! Simply:</p> <pre><code>from __past__ import printf </code></pre> <p>where <code>__past__.py</code> contains:</p> <pre><code>import sys def printf(fmt, *varargs): sys.stdout.write(fmt % varargs) </code></pre> <p>then:</p> <pre><code>&gt;&gt;&gt; printf("Hello, world!\n") Hello, world! &gt;&gt;&gt; printf("%d %d %d\n", 0, 1, 42) 0 1 42 &gt;&gt;&gt; printf('a'); printf('b'); printf('c'); printf('\n') abc &gt;&gt;&gt; </code></pre> <p>Bonus extra: If you don't like <code>print &gt;&gt; f, ...</code>, you can extending this caper to fprintf(f, ...).</p>
8
2009-06-24T04:26:03Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
20,677,875
<p>This may look stupid, but seems to be the simplest:</p> <pre><code> print 'h', print '\bm' </code></pre>
11
2013-12-19T09:32:40Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
21,369,899
<p>You can use print like the printf function in C.</p> <p>e.g.</p> <p>print "%s%s" % (x, y)</p>
0
2014-01-26T22:06:39Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
23,247,362
<p>In python 2.6:</p> <pre><code>&gt;&gt;&gt; print 'h','m','h' h m h &gt;&gt;&gt; from __future__ import print_function &gt;&gt;&gt; print('h',end='') h&gt;&gt;&gt; print('h',end='');print('m',end='');print('h',end='') hmh&gt;&gt;&gt; &gt;&gt;&gt; print('h','m','h',sep=''); hmh &gt;&gt;&gt; </code></pre> <p>So using print_function from __future__ you can set explicitly the <strong>sep</strong> and <strong>end</strong> parameteres of print function.</p>
2
2014-04-23T14:27:07Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
24,686,404
<pre><code>print("{0}{1}{2}".format(a, b, c)) </code></pre>
-1
2014-07-10T21:13:39Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
26,343,928
<p>I am not adding a new answer. I am just putting the best marked answer in a better format. I can see that the best answer by rating is using <code>sys.stdout.write(someString)</code>. You can try this out:</p> <pre><code> import sys Print = sys.stdout.write Print("Hello") Print("World") </code></pre> <p>will yield:</p> <pre><code>HelloWorld </code></pre> <p>That is all.</p>
5
2014-10-13T15:46:56Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
27,295,541
<p><code>sys.stdout.write</code> is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:</p> <pre><code>print "a", print "b", </code></pre> <p>This will print <code>a b</code>, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:</p> <pre><code>print "a", sys.stdout.write("0") print "b", </code></pre> <p>This will print <code>a0b</code>. How do you explain that? <strong><em>Where have the spaces gone?</em></strong></p> <p>I still can't quite make out what's really going on here. Could somebody look over my best guess:</p> <p><em>My attempt at deducing the rules when you have a trailing <code>,</code> on your <code>print</code></em>:</p> <p>First, let's assume that <code>print ,</code> (in Python 2) doesn't print any whitespace (spaces <em>nor</em> newlines).</p> <p>Python 2 does, however, pay attention to how you are printing - are you using <code>print</code>, or <code>sys.stdout.write</code>, or something else? If you make two <em>consecutive</em> calls to <code>print</code>, then Python will insist on putting in a space in between the two.</p>
0
2014-12-04T13:41:52Z
[ "python", "printing", "formatting", "python-2.x" ]
How do I keep Python print from adding newlines or spaces?
255,147
<p>In python, if I say</p> <pre><code>print 'h' </code></pre> <p>I get the letter h and a newline. If I say </p> <pre><code>print 'h', </code></pre> <p>I get the letter h and no newline. If I say</p> <pre><code>print 'h', print 'm', </code></pre> <p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p> <p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
169
2008-10-31T22:33:21Z
29,714,273
<pre><code>import sys a=raw_input() for i in range(0,len(a)): sys.stdout.write(a[i]) </code></pre>
-1
2015-04-18T07:21:47Z
[ "python", "printing", "formatting", "python-2.x" ]
How to override HTTP request verb in GAE
255,157
<p>In the context of a Google App Engine Webapp framework application:</p> <p>I want to changed the request verb of a request in the case a parameter _method is provided, for example if a POST request comes in with a parameter _method=PUT, I need to change the request to call the put method of the handler. This is to cope with the way prototype.js works with verbs like PUT and DELETE(workaround for IE). Here is my first attempt:</p> <pre> class MyRequestHandler(webapp.RequestHandler): def initialize(self, request, response): m = request.get('_method') if m: request.method = m.upper() webapp.RequestHandler.initialize(self, request, response) </pre> <p>The problem is, for some reason whenever the redirect is done, the self.request.params are emptied by the time the handling method(put or delete) is called, even though they were populated when initialize was called. Anyone have a clue why this is? As a workaround I thought I could clone the params at initialize() time, but .copy() did not work, and I haven't found a way to do that either.</p> <p><em>Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below.</em></p>
1
2008-10-31T22:37:00Z
255,906
<p>Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well.</p> <p>Instead, you have a couple of options:</p> <ul> <li>You can subclass webapp.WSGIApplication and override <strong>call</strong> to select the method based on _method when it exists.</li> <li>You can check for the existence of _method in initialize, and if it exists, modify the request object's 'REQUEST_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose.</li> </ul> <p>Either way, take a look at google/appengine/ext/webapp/<strong>init</strong>.py in the SDK so you can see how it works.</p>
3
2008-11-01T18:22:13Z
[ "python", "google-app-engine", "rest", "metaclass" ]
How to override HTTP request verb in GAE
255,157
<p>In the context of a Google App Engine Webapp framework application:</p> <p>I want to changed the request verb of a request in the case a parameter _method is provided, for example if a POST request comes in with a parameter _method=PUT, I need to change the request to call the put method of the handler. This is to cope with the way prototype.js works with verbs like PUT and DELETE(workaround for IE). Here is my first attempt:</p> <pre> class MyRequestHandler(webapp.RequestHandler): def initialize(self, request, response): m = request.get('_method') if m: request.method = m.upper() webapp.RequestHandler.initialize(self, request, response) </pre> <p>The problem is, for some reason whenever the redirect is done, the self.request.params are emptied by the time the handling method(put or delete) is called, even though they were populated when initialize was called. Anyone have a clue why this is? As a workaround I thought I could clone the params at initialize() time, but .copy() did not work, and I haven't found a way to do that either.</p> <p><em>Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below.</em></p>
1
2008-10-31T22:37:00Z
257,094
<p>Thats Arachnid for your response. Pointing me to the source of the framework was really helpful. Last I looked the source wasn't there(there was only .pyc), maybe it changed with the new version of the SDK. For my situation I think overriding WSGIApplication would have been the right thing to do. However, I chose to use a metaclass instead, because it didn't require me to cargo-cult(copy) a bunch of the framework code into my code and then modifying it. This is my solution:</p> <pre> class RequestHandlerMetaclass(type): def __init__(cls, name, bases, dct): super(RequestHandlerMetaclass, cls).__init__(name, bases, dct) org_post = getattr(cls, 'post') def post(self, *params, **kws): verb = self.request.get('_method') if verb: verb = verb.upper() if verb == 'DELETE': self.delete(*params, **kws) elif verb == 'PUT': self.put(*params, **kws) else: org_post(self, *params, **kws) setattr(cls, 'post', post) class MyRequestHandler(webapp.RequestHandler): __metaclass__ = RequestHandlerMetaclass </pre>
2
2008-11-02T17:35:47Z
[ "python", "google-app-engine", "rest", "metaclass" ]
Storage transactions in Redland's Python bindings?
255,263
<p>I've currently skimming through the Python-bindings for Redland and haven't found a clean way to do transactions on the storage engine via it. I found some model-transactions within the low-level Redland module:</p> <pre><code>import RDF, Redland storage = RDF.Storage(...) model = RDF.Model(storage) Redland.librdf_model_transaction_start(model._model) try: # Do something Redland.librdf_model_transaction_commit(model._model) model.sync() except: Redland.librdf_model_transaction_rollback(model._model) </code></pre> <p>Do these also translate down to the storage layer?</p> <p>Thanks :-)</p>
4
2008-10-31T23:42:20Z
257,582
<p>Yes, this should work. There are no convenience functions for the model class in the python wrapper right now but they would be similar to what you wrote:</p> <pre><code>class Model(object): ... def transaction_start(self): return Redland.librdf_model_transaction_start(self._model) </code></pre>
3
2008-11-02T23:40:46Z
[ "python", "transactions", "rdf", "rdfstore", "redland" ]
Python re.findall with groupdicts
255,332
<p>I kind of wish that there were a version of <code>re.findall</code> that returned <code>groupdict</code>s instead of just <code>group</code>s. Am I missing some simple way to accomplish the same result? (Does anybody know of a reason that this function doesn't exist?)</p>
8
2008-11-01T00:41:54Z
255,344
<p>You could use the finditer() function. This will give you a sequence of match objects, so you can get the groupdict for each with:</p> <pre><code>[m.groupdict() for m in regex.finditer(search_string)] </code></pre>
19
2008-11-01T00:52:19Z
[ "python", "regex" ]
Determine if a named parameter was passed
255,429
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?</p> <pre><code>&gt;&gt;&gt; {}.pop('test') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'pop(): dictionary is empty' &gt;&gt;&gt; {}.pop('test',None) &gt;&gt;&gt; {}.pop('test',3) 3 &gt;&gt;&gt; {}.pop('test',NotImplemented) NotImplemented </code></pre> <p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p> <p>Thanks</p>
10
2008-11-01T02:23:27Z
255,433
<p>You can do it like this:</p> <pre><code>def isdefarg(*args): if len(args) &gt; 0: print len(args), "arguments" else: print "no arguments" isdefarg() isdefarg(None) isdefarg(5, 7) </code></pre> <p>See the Python documentation on <a href="http://python.org/doc/2.5/ref/calls.html" rel="nofollow">calls</a> for full information.</p>
1
2008-11-01T02:34:46Z
[ "python", "default-value", "named-parameters" ]
Determine if a named parameter was passed
255,429
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?</p> <pre><code>&gt;&gt;&gt; {}.pop('test') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'pop(): dictionary is empty' &gt;&gt;&gt; {}.pop('test',None) &gt;&gt;&gt; {}.pop('test',3) 3 &gt;&gt;&gt; {}.pop('test',NotImplemented) NotImplemented </code></pre> <p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p> <p>Thanks</p>
10
2008-11-01T02:23:27Z
255,438
<p>I guess you mean "keyword argument", when you say "named parameter". <code>dict.pop()</code> does not accept keyword argument, so this part of the question is moot.</p> <pre><code>&gt;&gt;&gt; {}.pop('test', d=None) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: pop() takes no keyword arguments </code></pre> <p>That said, the way to detect whether an argument was provided is to use the <code>*args</code> or <code>**kwargs</code> syntax. For example:</p> <pre><code>def foo(first, *rest): if len(rest) &gt; 1: raise TypeError("foo() expected at most 2 arguments, got %d" % (len(rest) + 1)) print 'first =', first if rest: print 'second =', rest[0] </code></pre> <p>With some work, and using the <code>**kwargs</code> syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.</p>
6
2008-11-01T02:45:13Z
[ "python", "default-value", "named-parameters" ]
Determine if a named parameter was passed
255,429
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?</p> <pre><code>&gt;&gt;&gt; {}.pop('test') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'pop(): dictionary is empty' &gt;&gt;&gt; {}.pop('test',None) &gt;&gt;&gt; {}.pop('test',3) 3 &gt;&gt;&gt; {}.pop('test',NotImplemented) NotImplemented </code></pre> <p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p> <p>Thanks</p>
10
2008-11-01T02:23:27Z
255,446
<pre><code>def f(one, two=2): print "I wonder if", two, "has been passed or not..." f(1, 2) </code></pre> <p>If this is the exact meaning of your question, I think that there is no way to distinguish between a 2 that was in the default value and a 2 that has been passed. I didn't find how to accomplish such distinction even in the <a href="http://www.python.org/doc/2.5.2/lib/module-inspect.html" rel="nofollow">inspect</a> module.</p>
1
2008-11-01T02:58:41Z
[ "python", "default-value", "named-parameters" ]
Determine if a named parameter was passed
255,429
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?</p> <pre><code>&gt;&gt;&gt; {}.pop('test') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'pop(): dictionary is empty' &gt;&gt;&gt; {}.pop('test',None) &gt;&gt;&gt; {}.pop('test',3) 3 &gt;&gt;&gt; {}.pop('test',NotImplemented) NotImplemented </code></pre> <p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p> <p>Thanks</p>
10
2008-11-01T02:23:27Z
255,472
<p>I am not certain if I fully understand what is it you want; however:</p> <pre><code>def fun(arg=Ellipsis): if arg is Ellipsis: print "No arg provided" else: print "arg provided:", repr(arg) </code></pre> <p>does that do what you want? If not, then as others have suggested, you should declare your function with the <code>*args, **kwargs</code> syntax and check in the kwargs dict for the parameter existence.</p>
1
2008-11-01T03:19:07Z
[ "python", "default-value", "named-parameters" ]
Determine if a named parameter was passed
255,429
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work?</p> <pre><code>&gt;&gt;&gt; {}.pop('test') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'pop(): dictionary is empty' &gt;&gt;&gt; {}.pop('test',None) &gt;&gt;&gt; {}.pop('test',3) 3 &gt;&gt;&gt; {}.pop('test',NotImplemented) NotImplemented </code></pre> <p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p> <p>Thanks</p>
10
2008-11-01T02:23:27Z
255,580
<p>The convention is often to use <code>arg=None</code> and use</p> <pre><code>def foo(arg=None): if arg is None: arg = "default value" # other stuff # ... </code></pre> <p>to check if it was passed or not. Allowing the user to pass <code>None</code>, which would be interpreted as if the argument was <em>not</em> passed.</p>
7
2008-11-01T06:17:54Z
[ "python", "default-value", "named-parameters" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,481
<p>The obvious advantages to browser-based:</p> <ul> <li>you can present the same UI regardless of platform</li> <li>you can upgrade the application easily, and all users have the same version of the app running</li> <li>you know the environment that your application will be running in (the server hardware/OS) which makes for easier testing and support compared to the multitude of operating system/hardware configurations that a GUI app will be installed on.</li> </ul> <p>And for GUI based:</p> <ul> <li>some applications (e.g.: image editing) arguably work better in a native GUI application</li> <li>doesn't require network access</li> </ul> <p>Also see my comments on <a href="http://stackoverflow.com/questions/115501/is-ruby-any-good-for-gui-development#115638">this question</a>:</p> <blockquote> <p>Cross-platform GUIs are an age-old problem. Qt, GTK, wxWindows, Java AWT, Java Swing, XUL -- they all suffer from the same problem: the resulting GUI doesn't look native on every platform. Worse still, every platform has a slightly different look and <strong>feel</strong>, so even if you were somehow able to get a toolkit that looked native on every platform, you'd have to somehow code your app to feel native on each platform.</p> <p>It comes down to a decision: do you want to minimise development effort and have a GUI that doesn't look and feel quite right on each platform, or do you want to maximise the user experience? If you choose the second option, you'll need to develop a common backend and a custom UI for each platform. <em>[edit: or use a web application.]</em></p> </blockquote> <p>Another thought I just had: you also need to consider the kind of data that your application manipulates and where it is stored, and how the users will feel about that. People are obviously okay having their facebook profile data stored on a webserver, but they might feel differently if you're writing a finance application like MYOB and you want to store all their personal financial details on your server. You might be able to get that to work, but it would require a lot of effort to implement the required security and to assure the userbase that their data is safe. In that situation you might decide that the overall effort is lower if you go with a native GUI app.</p>
10
2008-11-01T03:29:53Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,484
<p>Browsers can be accessed anywhere with internet and you deploy it on the server. The desktop app has to be deployed to their computers and each computer somehow has its own uniqueness even with same OS and same version. This could bring you lots of hassles. Go for web.</p>
0
2008-11-01T03:30:08Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,491
<p>When it comes to simple data entry using user-entry forms, I'd argue that using a browser-based solution would probably be easier and faster to develop.</p> <p>Unless your core feature is the interface itself ("<em>If it's a core business function -- do it yourself, no matter what.</em>" , see <a href="http://www.joelonsoftware.com/articles/fog0000000007.html" rel="nofollow">In Defense of Not-Invented-Here Syndrome</a> from <a href="http://www.joelonsoftware.com/" rel="nofollow">Joel on Software</a>), I feel that the browser will be able to perform the form rendering and handling better than having to develop a GUI from scratch. Also, not to mention the it would take a much longer time to code a GUI as opposed to generating HTML forms and processing them after they are POSTed by the browser.</p> <p>What I found in the past was that I was asked by a friend to write an application to enter results from a survey. At first, I was writing a Java applet to display the survey itself with all the radio boxes, when it hit me that I would be better off writing a simple HTTP server which would generate the forms and process them.</p> <p>What it really comes down is to whether you are either developing:</p> <ol> <li>the user interface</li> <li>data-entry application</li> </ol> <p>If you are making a data-entry application, then leave the user interface to the browser, and focus on your core functionality.</p>
4
2008-11-01T03:37:23Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,501
<p>Benefits of browser-based interface:</p> <ul> <li>Easier to manage: no installation required on user machines, upgrades need only be performed on server side and are immediately available to all users. Data backup can be performed on a single machine as data won't be spread out across multiple clients.</li> <li>Application can be accessed from any machine with a browser.</li> <li>Can easily support multiple platforms consistently.</li> <li>Memory and CPU requirements may be considerably less on the client side as intensive operations can be performed on the server.</li> <li>Increased security: data is stored on a single server instead of multiple client machines and access can be better controlled.</li> <li>Many other benefits of a centralized environment including logging, data entered from multiple sources can immediately be available from other clients, etc.</li> <li>In my experience, it is often easier to debug and faster to develop web-based solutions.</li> </ul> <p>Benefits of GUI-based interface:</p> <ul> <li>May be easier to design a more responsive, fluid interface.</li> <li>Can take advantage of OS-specific functionality that may not be available via a browser.</li> <li>Doesn't necessarily require network access.</li> <li>Don't need to worry about browser compatibility issues.</li> <li>No single point of failure if server goes down or becomes unavailable.</li> </ul>
3
2008-11-01T03:49:50Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,505
<p>There's pretty good evidence that the trump-card issue in most cases is deployability and supportability. Browser apps are lower overhead in general; implementing and supporting more than a couple dozen users can end up consuming substantial support resources.</p> <p>I saw a table a year or two ago that showed something like:</p> <p> <br><br /> <br>UI quality - Desktop <br>Granularity of validation - Desktop <br>Responsiveness - Desktop <br>User acceptance - Desktop <br> etc. - Desktop <br> etc. - Desktop <br>Install &amp; Support - Browser <br>and the Browser wins.</p>
2
2008-11-01T03:51:15Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,508
<p>Let's pretend for a moment that the development/deployment/maintenance effort/cost is equal and we look at it from the application user's perspective:</p> <p><em>Which UI is the user going to find more useful?</em></p> <p>in terms of</p> <ul> <li>Ease of use</li> <li>Responsiveness</li> <li>Familiar navigation/usage patterns</li> <li>Most like other tools/applications in use on the platform (ie, native)</li> </ul> <p>I understand that "useful" is subjective. I personally would never use (as a user, not developer) a web interface again if I could get away with it. I <strong><em>hate</em></strong> them.</p> <p>There are some applications that just don't make sense to develop as browser based apps.</p> <p>From a development perspective</p> <ul> <li>No two browsers available today render <em>exactly</em> the same.</li> <li>Even with Ajax, javascript and dynamic, responsive interfaces are non-trivial to implement/debug.</li> </ul> <p>There are many, many standalone GUI applications that are just terrible, no argument. Development/deployment and maintenance for a multi-platform GUI is non-trivial.</p> <p>Developing good user-interfaces is hard, period.</p> <p>The reality is that I've made my living over the last 10 years developing mostly web based applications, because they're faster to develop, easier to deploy and provide enough utility that people will use them if they have to.</p> <p>I don't believe that most users would use a web interface if given an alternative.</p> <p>IMNSHO</p>
10
2008-11-01T03:53:47Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
255,514
<p>For this task (form-based text entry) a browser is great. You don't need anything that being a desktop app will give you (speed, flexibility)</p> <p>There are draw-backs to being a web-application, such as..</p> <p><strong>It's a web-page. There are things you just cannot (easily) do</strong></p> <p>You cannot easily map the ctrl+j key to do something. For example: Google Spreadsheet tries to map keyboard shortcuts and works <em>most</em> of the time, sometimes the browsers default handling of the shortcut takes over..</p> <p>You cannot make Growl alerts (An OS X notification framework). You cannot access the filesystem. It's difficult to allow access while offline.</p> <p><strong>Javascript is very CPU-heavy.</strong></p> <p>Try resizing a Google Spreadsheet document, or load a page on Digg (a very javascript heavy site) - the browsers CPU usage will be at 100% for a while.. Doing the same in a native desktop application is trivial</p> <p><strong>When you perform upgrades, you <em>force</em> them on all your users.</strong> With a desktop application, they have the choice of not upgrading. For example, I didn't like one of the Google Reader upgrades, but I was stuck. Using NetNewsWire (a desktop application), if I don't like a change in the newest version, I can quite easily keep using this one (or try it, and downgrade)</p> <p><strong>You web-server <em>must</em> be accessible at all times, for ever</strong></p> <p>If the server disappears, your users have no recourse. The application is gone. If it's down for 10 minutes, they cannot use it.</p> <p><hr /></p> <p>With your application, while I'm not too sure what it is, none of the above seems like its going to be an issue.</p> <p><em>"It's a web -page"</em>: Forms and dialogue boxes are easy to do in HTML and javascript (or even using server-side scripting, for example <code>&lt;?php if($_POST["email"] ==""){echo("Are you sure you want to continue?); ?&gt;</code>)</p> <p><em>"Javascript is very CPU-heavy"</em>: Doesn't sound like your application will require any Javascript (maybe some client-side input-validation when the user clicks "Submit", to warn them about any input errors?)</p> <p><em>"Forced upgrades"</em>: I imagine this may be desirable, as you wouldn't want users inputing data in the old way.</p> <p><em>"Server must be accessible"</em>: Could be an issue, but I don't think it'll be a large one.. Say you want to store all the users data in a central database, this issue becomes inescapable anyway - keeping a web and database server running isn't much more work than only a database (for the GUIs to connect to)</p> <p>Also, you get the benefits others have posted - you develop it once, and it runs identically on every operating system that can run a sane browser.</p>
2
2008-11-01T04:05:43Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
256,770
<p>Everything has advantages and disavantages, but:</p> <p><em>I have yet to use a single browser-based application on localhost, intranet, or internet that feels nice to use, is responsive, and who's user interface isn't strictly limited by the limitations of HTML/JS/CSS.</em></p> <p>Note: Flash/Java-based UI is an exception (but that's even worse in some regards and I don't think it's really what you are talking about here).</p>
0
2008-11-02T11:07:25Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
266,145
<p>One of the things I hate about web based UIs is the fact that they run inside another window. Meaning, you have controls -- maybe dozens of them -- that have nothing to do with your application. From a usability point of view this can be confusing though most of us have adapted by "tuning out" the extra stuff. </p> <p>As I look at my browser window as I type this, the window is perhaps 12 inches tall, but the window in which I type is only maybe 3 inches. And out of that 12 inches overall, perhaps two full inches are taken up with browser toolbars, tabs, rows of bookmarks and the statusbar, none of which have anything to do with the web app I'm interacting with. There's a lot of wasted space (the edit window isn't as wide as the window as a whole, for example), space filled with stuff I don't need, etc. Some of the most fundamental controls (back button, I'm looking at you) can completely break poorly designed web applications.</p> <p>Not to mention the fact that if I type a sufficiently long response I now end up with two sets of scrollbars. stackoverflow.com partially addresses that by giving me a resizable text area but I still have to interact with the inner scrollbar to scroll the text I'm editing, then scroll the whole window up or down to access the app controls at the top or bottom of the editing window.</p> <p>All in all, a web based application just can't compare to the usability of a desktop application. For me, then, the question simply becomes "are you more interested in usability, or in making your (as the developer) life easier".</p> <p>If you want usability, go with a desktop application, hands down. If you're concerned with deployment and support a web app is something to consider, but there are still many easy ways to deploy desktop apps, including creating apps that can update themselves over the net at runtime.</p>
1
2008-11-05T18:29:28Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
574,535
<p>I think the browser based UI concept is here to stay. There is nothing more portalble than the web itself, and as long as one stays within the boundaries of decent javascript libraries...the rendering would be almost the same. Plus since the rendering is not your headache, you can concern yourself more with developing the business logic itself.</p> <p>I am all for it...</p>
0
2009-02-22T07:41:51Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
2,707,352
<p>The rich client GUI will generally be faster and better integrated with the look and feel the user is accustomed to deal with - this does not only mean bells and whistles, but also means a lot of time saving features like keyboard shortcuts.</p> <p>The web based UI will be more portable since does not bound the development to a single platform, and if the application runs in remote it is easier to update and to test all of it (excluding the GUI...) on a consistent environment (your server). But you should understand that while all of that is great and really groundbreaking, it also comes with some serious drawbacks. You should not only debug the application under all the target systems, but also under each single browser running on each single target system... and don't forget many versions of the same browser may coexists for some time, and that each browser's settings will be probably running different sets (and versions) of popular plugins which makes it behave differently, and probably network settings will be customized by users. If the application is in remote it opens a lot of interesting new problem, starting from different ISP that will drop different problems in the middle, or services downtimes due to network problems of you server, the user's machines or anywhere in the middle. A remote application is not an option for all the users in countries where the network service is of low quality, or is not reasonably priced; the same is true for you: you can start providing such a service only if in your country bandwidth is reasonable and reasonably priced. And if the application has to do something nontrivial on the user's system, you will be probably doomed in creating a lot of platform dependent code anyway.</p> <p>As bottom line, today there are advantages and disadvantages in any of the two solutions. There are some applications that really need to be developed under the rich client model, and there are applications that really need to be developed under the web based paradigm. It's good to have both the options, it is critical to have a clear idea of what is the way fitting best our development / deployment / support strategy, and, I may add, it is silly to go after one or the other as if it is the definitive silver bullet following the fashion of the moment.</p>
0
2010-04-25T06:14:31Z
[ "python", "user-interface", "browser" ]
Browser-based application or stand-alone GUI app?
255,476
<p>I'm sure this has been asked before, but I can't find it. </p> <p>What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework?</p> <p>I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff.</p> <p>The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using <a href="http://karrigell.sourceforge.net/">Karrigell</a> for the web framework if I go browser-based.</p> <p><hr /></p> <p><strong>Edit</strong> For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.</p>
22
2008-11-01T03:25:09Z
17,340,205
<p>My solution is this</p> <ol> <li>Website applications obviously go on browsers</li> <li>Networked applications that do not need accessing client's computer goes by browser</li> <li>Any application that need to be accessed by more than a client at a time goes by browser</li> <li>Applications that will be used per client with no obvious need for network stays with gui and this may include software that needs a lot of security on its use (same security can be addressed for browser based though).</li> </ol> <p>This is something learnt through the hard way. One main reason for this is that customers find it easier to install and manage browser based apps much easier than gui based eg where using JavaWebStart means the client will need to have a minimum JRE and their likes whereas the browser based only needs a link. </p> <p>IN all the decision is really yours!. As a Java developer using JavaFX and Swing can solve my problem with this issue.</p>
0
2013-06-27T10:00:29Z
[ "python", "user-interface", "browser" ]
How to implement Google Suggest in your own web application (e.g. using Python)
255,700
<p>In my website, users have the possibility to store links.</p> <p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p> <p>Example:</p> <p>User is typing as URL:</p> <pre><code>http://www.sta </code></pre> <p>Suggestions which would be displayed:</p> <pre><code>http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com </code></pre> <p>How can I achieve this while not reinventing the wheel? :)</p>
9
2008-11-01T15:50:30Z
255,705
<p>You could try with <a href="http://google.com/complete/search?output=toolbar&amp;q=keyword">http://google.com/complete/search?output=toolbar&amp;q=keyword</a></p> <p>and then parse the xml result.</p>
7
2008-11-01T15:58:31Z
[ "python", "autocomplete", "autosuggest" ]
How to implement Google Suggest in your own web application (e.g. using Python)
255,700
<p>In my website, users have the possibility to store links.</p> <p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p> <p>Example:</p> <p>User is typing as URL:</p> <pre><code>http://www.sta </code></pre> <p>Suggestions which would be displayed:</p> <pre><code>http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com </code></pre> <p>How can I achieve this while not reinventing the wheel? :)</p>
9
2008-11-01T15:50:30Z
255,962
<p>If you want the auto-complete to use date from your own database, you'll need to do the search yourself and update the suggestions using AJAX as users type. For the search part, you might want to look at <a href="http://lucene.apache.org/java/docs/" rel="nofollow">Lucene</a>.</p>
0
2008-11-01T19:00:16Z
[ "python", "autocomplete", "autosuggest" ]
How to implement Google Suggest in your own web application (e.g. using Python)
255,700
<p>In my website, users have the possibility to store links.</p> <p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p> <p>Example:</p> <p>User is typing as URL:</p> <pre><code>http://www.sta </code></pre> <p>Suggestions which would be displayed:</p> <pre><code>http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com </code></pre> <p>How can I achieve this while not reinventing the wheel? :)</p>
9
2008-11-01T15:50:30Z
256,099
<p>I did this once before in a Django server. There's two parts - client-side and server-side.</p> <p>Client side you will have to send out XmlHttpRequests to the server as the user is typing, and then when the information comes back, display it. This part will require a decent amount of javascript, including some tricky parts like callbacks and keypress handlers.</p> <p>Server side you will have to handle the XmlHttpRequests which will be something that contains what the user has typed so far. Like a url of</p> <pre><code>www.yoursite.com/suggest?typed=www.sta </code></pre> <p>and then respond with the suggestions encoded in some way. (I'd recommend JSON-encoding the suggestions.) You also have to actually get the suggestions from your database, this could be just a simple SQL call or something else depending on your framework.</p> <p>But the server-side part is pretty simple. The client-side part is trickier, I think. I found this <a href="http://www.phpriot.com/articles/google-suggest-ajaxac" rel="nofollow">article</a> helpful</p> <p>He's writing things in php, but the client side work is pretty much the same. In particular you might find his CSS helpful.</p>
2
2008-11-01T20:59:34Z
[ "python", "autocomplete", "autosuggest" ]
How to implement Google Suggest in your own web application (e.g. using Python)
255,700
<p>In my website, users have the possibility to store links.</p> <p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p> <p>Example:</p> <p>User is typing as URL:</p> <pre><code>http://www.sta </code></pre> <p>Suggestions which would be displayed:</p> <pre><code>http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com </code></pre> <p>How can I achieve this while not reinventing the wheel? :)</p>
9
2008-11-01T15:50:30Z
656,122
<p>Yahoo has a good <a href="http://developer.yahoo.com/yui/autocomplete/" rel="nofollow">autocomplete control</a>.</p> <p>They have a <a href="http://developer.yahoo.com/yui/examples/autocomplete/ac%5Fbasic%5Farray.html" rel="nofollow">sample here.</a>.</p> <p>Obviously this does nothing to help you out in getting the data - but it looks like you have your own source and arent actually looking to get data from Google.</p>
1
2009-03-17T21:34:59Z
[ "python", "autocomplete", "autosuggest" ]
How to implement Google Suggest in your own web application (e.g. using Python)
255,700
<p>In my website, users have the possibility to store links.</p> <p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p> <p>Example:</p> <p>User is typing as URL:</p> <pre><code>http://www.sta </code></pre> <p>Suggestions which would be displayed:</p> <pre><code>http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com </code></pre> <p>How can I achieve this while not reinventing the wheel? :)</p>
9
2008-11-01T15:50:30Z
656,223
<p>That control is often called a word wheel. MSDN has a recent <a href="http://msdn.microsoft.com/en-us/magazine/cc721610.aspx" rel="nofollow">walkthrough</a> on writing one with <code>LINQ</code>. There are two critical aspects: deferred execution and lazy evaluation. The article has source code too. </p>
0
2009-03-17T22:05:48Z
[ "python", "autocomplete", "autosuggest" ]
Can I Use Python to Make a Delete Button in a 'web page'
256,021
<p>I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. </p> <p>I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. </p> <p>Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.</p>
2
2008-11-01T19:52:08Z
256,028
<p>You would have to write the web page in Python. There are many Python web frameworks out there (e.g. Django) that are easy to work with. You could convert your entire scripting framework to a web application that has a worker thread going and crawling through html pages, saving them to a particular location, indexing them for you to see and providing a delete button that calls the system's delete function on the particular file.</p>
0
2008-11-01T19:59:48Z
[ "python", "web-applications", "browser" ]
Can I Use Python to Make a Delete Button in a 'web page'
256,021
<p>I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. </p> <p>I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. </p> <p>Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.</p>
2
2008-11-01T19:52:08Z
256,031
<p>Rather than having your script output static HTML files, with a little amount of work you could probably adapt your script to run as a small web application with the help of something like web.py.</p> <p>You would start your script and point a browser at <a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a>, for instance. The web browser would be your user interface.</p> <p>To achieve the 'delete' functionality, all you need to do is write some Python that gets executed when a form is submitted to actually perform the deletion.</p>
0
2008-11-01T20:00:43Z
[ "python", "web-applications", "browser" ]
Can I Use Python to Make a Delete Button in a 'web page'
256,021
<p>I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. </p> <p>I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. </p> <p>Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.</p>
2
2008-11-01T19:52:08Z
256,040
<p>You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a "Keep this page" and a "Delete this page." When you click either button, the main page refreshes, this time with the next autocreated page in the frame.</p> <p>You could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a "delete".</p>
1
2008-11-01T20:07:07Z
[ "python", "web-applications", "browser" ]
Can I Use Python to Make a Delete Button in a 'web page'
256,021
<p>I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. </p> <p>I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. </p> <p>Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.</p>
2
2008-11-01T19:52:08Z
303,086
<p>Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience</p> <pre><code>def OnDelete(self, event): assert self.current, "invalid delete operation" try: os.remove(os.path.join(self.cwd, self.current)) </code></pre>
0
2008-11-19T19:40:25Z
[ "python", "web-applications", "browser" ]
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p> <pre><code>def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass </code></pre> <p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p>
235
2008-11-01T23:02:36Z
256,235
<p>I've mostly just seen the builtin <code>ValueError</code> used in this situation.</p>
9
2008-11-01T23:17:40Z
[ "python", "exception", "arguments" ]
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p> <pre><code>def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass </code></pre> <p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p>
235
2008-11-01T23:02:36Z
256,236
<p>I would inherit from <code>ValueError</code></p> <pre><code>class IllegalArgumentError(ValueError): pass </code></pre> <p>It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.</p> <p>If you need to catch that specific error, it is helpful to have a name.</p>
40
2008-11-01T23:17:49Z
[ "python", "exception", "arguments" ]
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p> <pre><code>def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass </code></pre> <p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p>
235
2008-11-01T23:02:36Z
256,239
<p>I'm not sure I agree with inheritance from <code>ValueError</code> -- my interpretation of the documentation is that <code>ValueError</code> is <em>only</em> supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.</p> <blockquote> <p>Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.</p> </blockquote> <p>-- <a href="http://docs.python.org/library/exceptions.html?highlight=valueerror#exceptions.ValueError" rel="nofollow">ValueError documentation</a></p>
2
2008-11-01T23:21:54Z
[ "python", "exception", "arguments" ]
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p> <pre><code>def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass </code></pre> <p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p>
235
2008-11-01T23:02:36Z
256,260
<p>I would just raise <a href="https://docs.python.org/2/library/exceptions.html#exceptions.ValueError">ValueError</a>, unless you need a more specific exception..</p> <pre><code>def import_to_orm(name, save=False, recurse=False): if recurse and not save: raise ValueError("save must be True if recurse is True") </code></pre> <p>There's really no point in doing <code>class BadValueError(ValueError):pass</code> - your custom class is identical in use to <a href="https://docs.python.org/2/library/exceptions.html#exceptions.ValueError">ValueError</a>, so why not use that?</p>
243
2008-11-01T23:37:31Z
[ "python", "exception", "arguments" ]
Python packages and egg-info directories
256,417
<p>Can someone explain how egg-info directories are tied to their respective modules? For example, I have the following:</p> <pre><code>/usr/local/lib/python2.5/site-packages/quodlibet/ /usr/local/lib/python2.5/site-packages/quodlibet-2.0.egg-info/ </code></pre> <p>I'm assuming the egg-info directory is to make the corresponding module visible to setuptools (easy_install), right? If so, how does setuptools tie the egg-info directory to the module directory?</p> <p>Assuming that I'm on the right track, and for the sake of example... If I wanted to make an existing package of mine visible to setuptools, could I just symlink the module directory and the egg-info directory to the site-packages directory? I would have just tried this myself, but I'm not sure how to test if the package is visible to setuptools. Bonus points if you can also tell me how to test this :)</p> <p>The main reason I'm trying to understand all this is because I would like to symlink some of my modules into site-packages so that I can make changes to them and have the changes visible to the scripts that use them without having to reinstall the egg from PyPI after each change.</p>
52
2008-11-02T02:26:20Z
256,614
<p>The .egg-info directories get only created if --single-version-externally-managed was used to install the egg. "Normally", installing an egg would create a single directory (or zip file), containing both the code and the metadata. </p> <p>pkg_resources (which is the library that reads the metadata) has a function <code>require</code> which can be used to request a specific version of the package. For "old-style", regular imports, easy_install hacks a .pth file to get the egg directory onto sys.path. For --single-version-externally-managed, this hacking is not necessary, because there will only be a single version installed (by the system's pacakging infrastructure, e.g. rpm or dpkg). The egg-info is still included, for applications that use <code>require</code> (or any of the other pkg_resources binding mechanisms).</p> <p>If you want to install a package by hard-linking, I recommend to use "setup.py develop". This is a command from setuptools which doesn't actually install the egg, but makes it available site-wide. To do so, it creates an egg-link file so that pkg_resources can find it, and it manipulates a .pth file, so that regular import can find it.</p>
46
2008-11-02T06:40:26Z
[ "python", "setuptools", "egg" ]
Putting a pyCurl XML server response into a variable (Python)
256,564
<p>I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (<a href="http://twitpic.com/api.do" rel="nofollow">http://twitpic.com/api.do</a>). For reference purposes, check out the code (<a href="http://pastebin.com/f4c498b6e" rel="nofollow">http://pastebin.com/f4c498b6e</a>) and the error I'm getting (<a href="http://pastebin.com/mff11d31" rel="nofollow">http://pastebin.com/mff11d31</a>).</p> <p>Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!).</p> <p>After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.</p>
3
2008-11-02T05:38:48Z
256,610
<p><a href="http://pycurl.sourceforge.net/doc/curlobject.html" rel="nofollow">The pycurl doc</a> explicitly says:</p> <blockquote> <p>perform() -> None</p> </blockquote> <p>So the expected result is what you observe.</p> <p>looking at an example from the pycurl site:</p> <pre><code>import sys import pycurl class Test: def __init__(self): self.contents = '' def body_callback(self, buf): self.contents = self.contents + buf print &gt;&gt;sys.stderr, 'Testing', pycurl.version t = Test() c = pycurl.Curl() c.setopt(c.URL, 'http://curl.haxx.se/dev/') c.setopt(c.WRITEFUNCTION, t.body_callback) c.perform() c.close() print t.contents </code></pre> <p>The interface requires a class instance - <code>Test()</code> - with a specific callback to save the content. Note the call <code>c.setopt(c.WRITEFUNCTION, t.body_callback)</code> - something like this is missing in your code, so you do not receive any data (<code>buf</code> in the example). The example shows how to access the content:</p> <pre><code>print t.contents </code></pre>
4
2008-11-02T06:35:34Z
[ "python", "xml", "pycurl" ]
Putting a pyCurl XML server response into a variable (Python)
256,564
<p>I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (<a href="http://twitpic.com/api.do" rel="nofollow">http://twitpic.com/api.do</a>). For reference purposes, check out the code (<a href="http://pastebin.com/f4c498b6e" rel="nofollow">http://pastebin.com/f4c498b6e</a>) and the error I'm getting (<a href="http://pastebin.com/mff11d31" rel="nofollow">http://pastebin.com/mff11d31</a>).</p> <p>Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!).</p> <p>After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.</p>
3
2008-11-02T05:38:48Z
2,351,363
<p>Using a StringIO would be much cleaner, no point in using a dummy class like that if all you want is the response data...</p> <p>Something like this would suffice:</p> <pre><code>import pycurl import cStringIO response = cStringIO.StringIO() c = pycurl.Curl() c.setopt(c.URL, 'http://www.turnkeylinux.org') c.setopt(c.WRITEFUNCTION, response.write) c.perform() c.close() print response.getvalue() </code></pre>
12
2010-02-28T14:42:24Z
[ "python", "xml", "pycurl" ]
Message Box in Python
257,398
<p>Is there a UI library to create a message box or input box in python?</p>
6
2008-11-02T21:22:30Z
257,403
<p>Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter).</p> <p>If you can restrict yourself to a specific operating system, better choices might be available.</p>
11
2008-11-02T21:26:54Z
[ "python", "user-controls", "user-interface" ]
Message Box in Python
257,398
<p>Is there a UI library to create a message box or input box in python?</p>
6
2008-11-02T21:22:30Z
257,532
<p>I've heard good things about wx python, which is also multi-platform. </p>
2
2008-11-02T22:58:15Z
[ "python", "user-controls", "user-interface" ]