title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Google AppEngine: Date Range not returning correct results
722,728
<p>Im trying to search for some values within a date range for a specific type, but content for dates that exist in the database are not being returned by the query.</p> <p>Here is an extract of the python code:</p> <pre><code>deltaDays = timedelta(days= 20) endDate = datetime.date.today() startDate = endDate - deltaDays result = db.GqlQuery( "SELECT * FROM myData WHERE mytype = :1 AND pubdate &gt;= :2 and pubdate &lt;= :3", type, startDate, endDate ) class myData(db.Model): mytype = db.StringProperty(required=True) value = db.FloatProperty(required=True) pubdate = db.DateTimeProperty(required=True) </code></pre> <p>The GQL returns data, but some rows that I am expecting are missing:</p> <pre><code> 2009-03-18 00:00:00 (missing date in results: 2009-03-20 data exists in database) 2009-03-23 00:00:00 2009-03-24 00:00:00 2009-03-25 00:00:00 2009-03-26 00:00:00 (missing date in results: 2009-03-27 data exists in database) 2009-03-30 00:00:00 (missing date in results: 2009-03-31. data exists in database) 2009-04-01 00:00:00 2009-04-02 00:00:00 2009-04-03 00:00:00 2009-04-06 00:00:00 </code></pre> <p>I uploaded the data via de bulkload script. I just can think of the indexes being corrupted or something similar. This same query used to work for another table i had. But i had to replace it with new content from another source, and this new content is not responding to the query in the same way. The table has around 700.000 rows if that makes any difference.</p> <p>I have done more research ant it appears that its a bug in the appEngine DataStore. For more information about the bug check this link: <a href="http://code.google.com/p/googleappengine/issues/detail?id=901" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=901</a></p> <p>I have tried droping the index and recreating it with no luck.</p> <p>thanks</p>
0
2009-04-06T19:03:21Z
723,372
<p>nothing looks wrong to me. are you sure that the missing dates also have mytype == type?</p> <p>i have observed some funny behaviour with indexes in the past. I recommend writing a handler to iterate through all of your records and just put() them back in the database. maybe something with the bulk uploader isn't working properly.</p> <p>Here's the type of handler I use to iterate through all the entities in a model class:</p> <pre><code> class PPIterator(BaseRequestHandler): def get(self): query = Model.gql('ORDER BY __key__') last_key_str = self.request.get('last') if last_key_str: last_key = db.Key(last_key_str) query = Model.gql('WHERE __key__ &gt; :1 ORDER BY __key__', last_key) entities = query.fetch(11) new_last_key_str = None if len(entities) == 11: new_last_key_str = str(entities[9].key()) for e in entities: e.put() if new_last_key_str: self.response.out.write(json.write(new_last_key_str)) else: self.response.out.write(json.write('done')) </code></pre> <p>You can use whatever you want to iterate through the entities. I used to use Javascript in a browser window, but found that was a pig when making hundreds of thousands of requests. These days I find it more convenient to use a ruby script like this one:</p> <pre><code>require 'net/http' require 'json' last=nil while last != 'done' url = 'your_url' path = '/your_path' path += "?/last=#{last}" if last last = Net::HTTP.get(url,path) puts last end </code></pre> <p>Ben</p> <p>UPDATE: now that remote api is working and reliable, I rarely write this type of handler anymore. The same ideas apply to the code you'd use there to iterate through the entities in the remote api console.</p>
1
2009-04-06T21:46:37Z
[ "python", "google-app-engine", "gql" ]
Env Variables in Python (v3.0) on Windows
722,739
<p>I'm using Python 3.0. </p> <p>How to expand an environment variable given the %var_name% syntax?</p> <p>Any help is much appreciated! Thanks!</p>
3
2009-04-06T19:07:17Z
722,758
<p>I'm guessing you mean "How do I get environment variables?":</p> <pre><code>import os username = os.environ['UserName'] </code></pre> <p>Alternatively, you can use:</p> <pre><code>username = os.getenv('UserName') </code></pre> <p>And to add/change your own variables, you can use:</p> <pre><code>os.putenv('MyVar', 'something I want to store') </code></pre>
2
2009-04-06T19:13:37Z
[ "python", "windows", "scripting", "shell" ]
Env Variables in Python (v3.0) on Windows
722,739
<p>I'm using Python 3.0. </p> <p>How to expand an environment variable given the %var_name% syntax?</p> <p>Any help is much appreciated! Thanks!</p>
3
2009-04-06T19:07:17Z
722,871
<p>It's in a slightly unexpected place: <a href="http://docs.python.org/3.0/library/os.path.html#os.path.expanduser" rel="nofollow">os.path.expandvars()</a>. Admittedly it is quite often used for processing paths:</p> <pre><code>&gt;&gt;&gt; import os.path &gt;&gt;&gt; os.path.expandvars('%APPDATA%\\MyApp') 'C:\\Documents and Settings\\Administrator\\Application Data\\MyApp' </code></pre> <p>but it's a shell function really.</p>
3
2009-04-06T19:41:20Z
[ "python", "windows", "scripting", "shell" ]
pythonic way to compare compound classes?
722,741
<p>I have a class that acts as an item in a tree:</p> <pre><code>class CItem( list ): pass </code></pre> <p>I have two trees, each with CItem as root, each tree item has some dict members (like item._test = 1). Now i need to compare this trees. I can suggest to overload a comparison operator for CItem:</p> <pre><code>class CItem( list ): def __eq__( self, other ): # first compare items as lists if not list.__eq__( self, other ): return False # now compare dict members if self.__dict__ != other.__dict__: return False # seems equal return True </code></pre> <p>Now i can compare two trees using '==' or '!='. Is this a 'pythonic' way or such comparsion can be done easire?</p>
2
2009-04-06T19:07:55Z
722,786
<p>My feeling would be something like</p> <pre><code>class CItem(list): def __eq__(self, other): return list.__eq__(self, other) and self.__dict__ == other.__dict__ </code></pre> <p>but it's basically the same code you have, just expressed in shorter notation. I can't think of any more substantial changes to make offhand.</p>
3
2009-04-06T19:22:44Z
[ "python" ]
Using paver and nose together with an atypical directory structure
722,992
<p>I'm trying to write a task for <code>Paver</code> that will run <code>nosetests</code> on my files.</p> <p>My directory structure looks like this:</p> <pre><code>project/ file1.py file2.py file3.py build/ pavement.py subproject/ file4.py test/ file5.py file6.py </code></pre> <p>Doctests (using the <code>--with_doctest</code> option) should be run on all the *.py files, while only the files under <code>project/test</code> (in this example, <code>file5.py</code> and <code>file6.py</code>) should be searched for test routines.</p> <p>I can't seem to figure out how to do this--I can write a custom plugin for <code>nose</code> which includes the correct files, but I can't seem to get <code>paver</code> to build and install it before calling the <code>nosetests</code> task. I also can't find a way to get <code>paver</code> to pass a list of files to test to <code>nosetests</code> on the command line.</p> <p>What's the best way of getting this to work?</p>
3
2009-04-06T20:08:06Z
1,942,991
<p>Is this at all close to what you're trying to get at?</p> <pre><code>from paver.easy import sh, path __path__ = path(__file__).abspath().dirname() @task def setup_nose_plugin(): # ... do your plugin setup here. @task @needs('setup_nose_plugin') def nosetests(): nose_options = '--with-doctest' # Put your command-line options in there sh('nosetests %s' % nose_options, # Your pavement.py is in a weird place, so you need to specify the working dir: cwd=__path__.parent) </code></pre> <p>I'm not actually sure how to tell nose to look in specific files, but that's a matter of command-line options. </p> <p><code>--where</code> lets you specify a directory, but I don't see a way to say "run only doctests here, and other tests here". You may need two invocations of <code>sh('nosetests')</code> to do all that.</p>
2
2009-12-21T22:15:04Z
[ "python", "nose", "paver" ]
Inserting object with ManyToMany in Django
723,293
<p>I have a blog-like application with stories and categories:</p> <pre><code>class Category(models.Model): ... class Story(models.Model): categories = models.ManyToManyField(Category) ... </code></pre> <p>Now I know that when you save a new instance of a model with a many-to-many field, problems come up because the object is not yet in the database. This problem usually manifests itself on form submission, which can be neatly worked around with <code>story_form.save(commit=False)</code>. What about a situation where there are no forms to speak of? In my case, I want to build an API to accept remote submissions. Since I like JSON, and a whole lot of other messaging in our company is in JSON (including outgoing messages from this server), I'd like to be able to receive the following:</p> <pre><code>{ "operation": "INSERT", "values": [ { "datatype": "story", "categories": [4,6,8], "id":50, ... } ] } </code></pre> <p>and implement a factory that converts the values to instances. But I'd like the factory to be as agnostic as possible to the type of operation. So:</p> <pre><code>{ "operation": "UPDATE", "values": [ { "datatype": "story", "categories": [4,6,8], "id":50, ... } ] } </code></pre> <p>should also be converted in the same way, except that INSERT ignores id and UPDATE gets the already existing instance and overrides it. (The remote submitter listens to a feed that gives it, among other things, the category objects to cache, so it can, and must, refer to them by id, but it doesn't have any direct communication with the database.)</p> <p>My real question is: what's the most easiest consistent to inflate an instance of a Django model object that has a ManyToManyManager involved. As far as I can fathom, any insert of an object with a many-to-many field will require two database hits, just because it is necessary to obtain a new id first. But my current awkward solution is to save the object right away and mark it hidden, so that functions down the line can play with it and save it as something a little more meaningful. It seems like one step up would be overriding <code>save</code> so that objects without ids save once, copy some proxy field to <code>categories</code>, then save again. Best of all would be some robust manager object that saves me the trouble. What do you recommend?</p>
1
2009-04-06T21:23:22Z
723,514
<p>"As far as I can fathom, any insert of an object with a many-to-many field will require two database hits,..."</p> <p>So what?</p> <p>Micromanaging each individual database access generally isn't worth all the thinking. Do the simplest, most obvious thing so that Django can optimize cache for you. </p> <p>Your application performance is --typically-- dominated by the slow download to the browser, and all the JPEGS, CSS and other static content that is part of your page.</p> <p>Time spent in brain-cramping thinking about how to make two Primary Keys (for a many-to-many relationship) without doing two database accesses is not going to pay out well. Two PK's is usually two database accesses.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"...litters the database on error..."</p> <p>Django has transactions. See <a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/#managing-database-transactions" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/transactions/#managing-database-transactions</a>. Use the <code>@transaction.commit_manually</code> decorator.</p> <p>"forces validation that is meant to occur later"</p> <p>Doesn't make sense -- update your question to explain this.</p>
3
2009-04-06T22:34:55Z
[ "python", "django", "many-to-many" ]
Inserting object with ManyToMany in Django
723,293
<p>I have a blog-like application with stories and categories:</p> <pre><code>class Category(models.Model): ... class Story(models.Model): categories = models.ManyToManyField(Category) ... </code></pre> <p>Now I know that when you save a new instance of a model with a many-to-many field, problems come up because the object is not yet in the database. This problem usually manifests itself on form submission, which can be neatly worked around with <code>story_form.save(commit=False)</code>. What about a situation where there are no forms to speak of? In my case, I want to build an API to accept remote submissions. Since I like JSON, and a whole lot of other messaging in our company is in JSON (including outgoing messages from this server), I'd like to be able to receive the following:</p> <pre><code>{ "operation": "INSERT", "values": [ { "datatype": "story", "categories": [4,6,8], "id":50, ... } ] } </code></pre> <p>and implement a factory that converts the values to instances. But I'd like the factory to be as agnostic as possible to the type of operation. So:</p> <pre><code>{ "operation": "UPDATE", "values": [ { "datatype": "story", "categories": [4,6,8], "id":50, ... } ] } </code></pre> <p>should also be converted in the same way, except that INSERT ignores id and UPDATE gets the already existing instance and overrides it. (The remote submitter listens to a feed that gives it, among other things, the category objects to cache, so it can, and must, refer to them by id, but it doesn't have any direct communication with the database.)</p> <p>My real question is: what's the most easiest consistent to inflate an instance of a Django model object that has a ManyToManyManager involved. As far as I can fathom, any insert of an object with a many-to-many field will require two database hits, just because it is necessary to obtain a new id first. But my current awkward solution is to save the object right away and mark it hidden, so that functions down the line can play with it and save it as something a little more meaningful. It seems like one step up would be overriding <code>save</code> so that objects without ids save once, copy some proxy field to <code>categories</code>, then save again. Best of all would be some robust manager object that saves me the trouble. What do you recommend?</p>
1
2009-04-06T21:23:22Z
723,586
<p>I commented on S.Lott's post that I feel his answer is the best. He's right: if the goal is just to avoid two database hits, then you're just in for a world of unnecessary pain.</p> <p>Reading your reference to ModelForm, however, if you are looking instead for a solution to that allows you to defer official saving in some way, you may wish to have a look at the <code>save_instance()</code> function in <code>forms.models</code>. The inner function <code>save_m2m</code> is how the delayed many-to-many save is accomplished for forms. Implementing something for models without forms would basically follow the same principle.</p> <p>Having said that, and coming back to S.Lott's post, the case of a ModelForm and an actual Model are somewhat different. Because forms expose only a "safe" set of data to be edited in a browser ("safe" because it is filtered in some way, or excludes critical fields that a user shouldn't be editing), it is a reasonable design expectation that someone might need to add important information to the form-derived model before saving. This is why django has the <code>commit=False</code>.</p> <p>This expectation falls down for cases where you are directly instantiating models. Here you have programmatic access to the model API, so you will probably find that using that API directly is easier to maintain and less error prone than through generalized indirection. I can understand why you are picturing the factory concept, but in this case you may find the effort to create a bullet-proof generalization for all manner of models is a complication that's just not worth it.</p>
2
2009-04-06T23:04:11Z
[ "python", "django", "many-to-many" ]
Controlling a Windows Console App w/ stdin pipe
723,424
<p>I am trying to control a console application (JTAG app from Segger) from Python using the subprocess module. The application behaves correctly for stdout, but stdin doesn't seem to be read. If enable the shell, I can type into the input and control the application, but I need to do this programmatically. The same code works fine for issuing commands to something like cmd.exe.</p> <p>I'm guessing that the keyboard is being read directly instead of stdin. Any ideas how I can send the application input?</p> <pre><code>from subprocess import Popen, PIPE, STDOUT jtag = Popen('"C:/Program Files/SEGGER/JLinkARM_V402e/JLink.exe"', shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) jtag.stdin.write('usb\n') jtag.stdin.flush() print "Stdout:" while True: s = jtag.stdout.readline() if not s: break print s, jtag.terminate() </code></pre>
1
2009-04-06T22:01:25Z
723,536
<pre><code>I'm guessing that the keyboard is being read directly instead of stdin </code></pre> <p>This is a pretty strong assumption and before stitching a solution you should try to verify it somehow. There are different levels of doing this. Actually two I can think of right now:</p> <ul> <li>Waiting for keyboard events from the main windows loop. if this is the case then you can simulate a keyboard simply by sending the window the right kind of message. these can be wither <code>WM_KEYDOWN</code> or <code>WM_CHAR</code> or perhaps some other related variants.</li> <li>Actually polling the hardware, for instance using <code>GetAsyncKeyState()</code>. This is somewhat unlikely and if this is really what's going on, I doubt you can do anything to simulate it programatically.</li> </ul> <p>Another take on this is trying to use the on-screen keyboard and see if it works with the application. if it does, figure out how to simulate what it does.</p> <p>Some tools which might be helpful - </p> <ul> <li>Spy++ (comes with Visual Studio) - allows you to see what messages go into a window</li> <li><a href="http://www.intellectualheaven.com/default.asp?BH=projects&amp;H=strace.htm" rel="nofollow">strace</a> allows you to see what syscalls a process is making.</li> </ul>
2
2009-04-06T22:40:50Z
[ "python", "command-line", "subprocess", "jtag" ]
Controlling a Windows Console App w/ stdin pipe
723,424
<p>I am trying to control a console application (JTAG app from Segger) from Python using the subprocess module. The application behaves correctly for stdout, but stdin doesn't seem to be read. If enable the shell, I can type into the input and control the application, but I need to do this programmatically. The same code works fine for issuing commands to something like cmd.exe.</p> <p>I'm guessing that the keyboard is being read directly instead of stdin. Any ideas how I can send the application input?</p> <pre><code>from subprocess import Popen, PIPE, STDOUT jtag = Popen('"C:/Program Files/SEGGER/JLinkARM_V402e/JLink.exe"', shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) jtag.stdin.write('usb\n') jtag.stdin.flush() print "Stdout:" while True: s = jtag.stdout.readline() if not s: break print s, jtag.terminate() </code></pre>
1
2009-04-06T22:01:25Z
723,724
<p>As shoosh says, I'd try to verify that the application really is looking for keyboard input. If it is, you can try Win32 message passing, or sending it keyboard input via automation.</p> <p>For the message passing route, you could use the <a href="http://msdn.microsoft.com/en-us/library/ms633497.aspx" rel="nofollow">EnumWindows</a> function via ctypes to find the window you're after, then using PostMessage to send it WM_KEYDOWN messages.</p> <p>You can also send keyboard input via <a href="http://pywinauto.openqa.org/" rel="nofollow">pywinauto</a>, or the ActiveX control of <a href="http://www.autoitscript.com/autoit3/index.shtml" rel="nofollow">AutoIt</a> via win32com.</p> <p>Using AutoIt:</p> <pre><code>from win32com.client import Dispatch auto = Dispatch("AutoItX3.Control") auto.WinActivate("The window's title", "") auto.WinWaitActive("The window's title", "", 10) auto.Send("The input") </code></pre>
3
2009-04-07T00:16:30Z
[ "python", "command-line", "subprocess", "jtag" ]
How do you send an Ethernet frame with a corrupt FCS?
723,635
<p>I'm not sure if this is even possible since this might be handled in hardware, but I need to send some Ethernet frames with errors in them. I'd like to be able to create runts, jabber, misalignment, and bad FCS errors. I'm working in Python.</p>
6
2009-04-06T23:30:16Z
724,009
<p>It <em>can</em> be handled in hardware, but isn't always -- and even if it is, you can turn that off; see the <A HREF="http://linux.die.net/man/8/ethtool">ethtool</A> offload parameters.</p> <p>With regard to getting full control over the frames you create -- look into <A HREF="http://swoolley.org/man.cgi/7/packet">PF_PACKET</A> (for one approach) or <A HREF="http://vtun.sourceforge.net/tun/faq.html">the tap driver</A> (for another).</p> <p>Here's an article on <A HREF="http://www.larsen-b.com/Article/206.html">using PF_PACKET to send hand-crafted frames from Python</A>.</p>
8
2009-04-07T02:50:09Z
[ "python", "networking", "automated-tests", "ethernet" ]
How do you send an Ethernet frame with a corrupt FCS?
723,635
<p>I'm not sure if this is even possible since this might be handled in hardware, but I need to send some Ethernet frames with errors in them. I'd like to be able to create runts, jabber, misalignment, and bad FCS errors. I'm working in Python.</p>
6
2009-04-06T23:30:16Z
6,382,971
<p>First, you disable your ethernet card's checksumming:</p> <pre><code>sudo ethtool -K eth1 tx off </code></pre> <p>Then, you send the corrupt frames from python:</p> <pre><code>#!/usr/bin/env python from socket import * # # Ethernet Frame: # [ # [ Destination address, 6 bytes ] # [ Source address, 6 bytes ] # [ Ethertype, 2 bytes ] # [ Payload, 40 to 1500 bytes ] # [ 32 bit CRC chcksum, 4 bytes ] # ] # s = socket(AF_PACKET, SOCK_RAW) s.bind(("eth1", 0)) src_addr = "\x01\x02\x03\x04\x05\x06" dst_addr = "\x01\x02\x03\x04\x05\x06" payload = ("["*30)+"PAYLOAD"+("]"*30) checksum = "\x00\x00\x00\x00" ethertype = "\x08\x01" s.send(dst_addr+src_addr+ethertype+payload+checksum) </code></pre> <p>See <a href="http://stackoverflow.com/questions/6329583/how-to-reliably-generate-ethernet-frame-errors-in-software">A similar question</a></p>
3
2011-06-17T08:02:35Z
[ "python", "networking", "automated-tests", "ethernet" ]
How do you send an Ethernet frame with a corrupt FCS?
723,635
<p>I'm not sure if this is even possible since this might be handled in hardware, but I need to send some Ethernet frames with errors in them. I'd like to be able to create runts, jabber, misalignment, and bad FCS errors. I'm working in Python.</p>
6
2009-04-06T23:30:16Z
8,356,862
<p>try using scapy for python, there are examples to generate jumbo frames, a runt frames too. <a href="http://www.dirk-loss.de/scapy-doc/usage.html" rel="nofollow">http://www.dirk-loss.de/scapy-doc/usage.html</a></p>
2
2011-12-02T13:15:42Z
[ "python", "networking", "automated-tests", "ethernet" ]
How do you send an Ethernet frame with a corrupt FCS?
723,635
<p>I'm not sure if this is even possible since this might be handled in hardware, but I need to send some Ethernet frames with errors in them. I'd like to be able to create runts, jabber, misalignment, and bad FCS errors. I'm working in Python.</p>
6
2009-04-06T23:30:16Z
25,922,139
<p>The program did not work as intended for me to generate FCS errors.</p> <p>The network driver added the correct checksum at the end of the generated frame again. Of course it's quite possible that the solution is working for some cards, but I'm sure not with any from Intel. (It's also working without any ethtool changes for me.)</p> <p>With at least an Intel e1000e network card you need a small change to the code above: Add the following line after "s = socket(AF_PACKET, SOCK_RAW)":</p> <pre><code>s.setsockopt(SOL_SOCKET,43,1) </code></pre> <p>This tell the NIC driver to use the "SO_NOFCS" option defined in socket.h and send the frame out without calculating and adding the FCS.</p> <p>You may also be interested in the following C-programm, which did show me how to do it: <a href="http://markmail.org/thread/eoquixklsjgvvaom" rel="nofollow">http://markmail.org/thread/eoquixklsjgvvaom</a></p> <p>But be aware that the program will not work on recent kernels without a small change. The SOL_SOCKET seems to have changed the numeric ID from 42 to 43 at some time in the past. </p> <p>According to the original author the feature should be available for at least the following drivers: e100, e1000, and e1000e. A quick grep in the kernel sources of 3.16.0 is indicating that ixgbe igb and i40e should also work. If you are not using any of these cards this socket option will probably not be available. </p>
1
2014-09-18T20:55:09Z
[ "python", "networking", "automated-tests", "ethernet" ]
Python/Django plugin for Dreamweaver
723,652
<p>Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.</p>
5
2009-04-06T23:38:22Z
723,657
<p>As far as I know there's no Django-specific IDE plugins out there.</p> <p>However I use <a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a> with <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a> for my Django/Python needs and it is quite nice.</p>
3
2009-04-06T23:41:55Z
[ "python", "django", "dreamweaver" ]
Python/Django plugin for Dreamweaver
723,652
<p>Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.</p>
5
2009-04-06T23:38:22Z
723,674
<p><a href="http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&amp;loc=en%5Fus&amp;extid=1557518" rel="nofollow">Found one</a> from some guy named Beshr Kayali, but I can't try it myself, since I don't have Dreamweaver.</p>
2
2009-04-06T23:49:06Z
[ "python", "django", "dreamweaver" ]
Python/Django plugin for Dreamweaver
723,652
<p>Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.</p>
5
2009-04-06T23:38:22Z
723,682
<p>I remember looking for a plugin too, but came across <a href="http://www.djangobook.com/en/beta/chapter04/">this</a> stumbling block:</p> <blockquote> <p><strong>Designers are assumed to be comfortable with HTML code</strong>. The template system isn’t designed so that templates necessarily are displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of a limitation and wouldn’t allow the syntax to be as nice as it is. Django expects template authors are comfortable editing HTML directly.</p> </blockquote> <p>That being said, I found a <a href="http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&amp;loc=en%5Fus&amp;extid=1557518">Dreamweaver extension</a> whilst having another quick look, so give it a try and let us know how it goes! From experience, the Eclipse solution offered by Paolo works very nicely, and the <a href="http://www.activestate.com/komodo/">Komodo</a> <a href="http://code.google.com/p/django-komodo-kit/wiki/ActiveState">plugins</a> look great, too. I know you are looking for a graphical editor, but <a href="http://code.djangoproject.com/wiki/Emacs">emacs</a> does a very nice job ;)</p>
5
2009-04-06T23:54:16Z
[ "python", "django", "dreamweaver" ]
Python/Django plugin for Dreamweaver
723,652
<p>Does a plugin exists for Python/Django into Dreamweaver? Just wondering since Dreamweaver is a great web dev tool.</p>
5
2009-04-06T23:38:22Z
5,149,029
<p>Beshir Kayali's plugin fails installation for DW CS5 and Extension Manager CS4. Irony that it asks for DW CS4 or better, else "upgrade" Extension manager to CS3.</p> <p>I could put some effort in to make this work, yet this is the sole review of the extension:</p> <blockquote> <p>I allows you to insert 6 kinds of template tags; if, for, template variable, block, comment, and tags. You press a button and then get a dialog box asking you for some info with maybe a few options. It doesn't actually do too much from what I can tell, definitely skippable.</p> </blockquote>
0
2011-02-28T23:58:14Z
[ "python", "django", "dreamweaver" ]
Is it possible to update a Google calendar from App Engine without logging in as the owner?
723,719
<p>I'd like to be able to use the Google Data API from an AppEngine application to update a calendar while not logged in as the calendar's owner or the a user that the calendar is shared with. This is in contrast to the examples here:</p> <p><a href="http://code.google.com/appengine/articles/more_google_data.html" rel="nofollow">http://code.google.com/appengine/articles/more_google_data.html</a></p> <p>The login and password for the calendar's owner could be embedded in the application. Is there any way to accomplish the necessary authentication?</p>
1
2009-04-07T00:13:07Z
723,999
<p>It should be possible using OAuth, i havent used it myself but my understanding is the user logs in and then gives your app permission to access their private data (e.g. Calendar records). Once they have authorised your app you will be able to access their data without them logging in.</p> <p>Here is an article explaining oauth and the google data api.</p> <p><a href="http://code.google.com/apis/gdata/articles/oauth.html" rel="nofollow">http://code.google.com/apis/gdata/articles/oauth.html</a></p>
3
2009-04-07T02:44:17Z
[ "python", "web-services", "google-app-engine" ]
Is it possible to update a Google calendar from App Engine without logging in as the owner?
723,719
<p>I'd like to be able to use the Google Data API from an AppEngine application to update a calendar while not logged in as the calendar's owner or the a user that the calendar is shared with. This is in contrast to the examples here:</p> <p><a href="http://code.google.com/appengine/articles/more_google_data.html" rel="nofollow">http://code.google.com/appengine/articles/more_google_data.html</a></p> <p>The login and password for the calendar's owner could be embedded in the application. Is there any way to accomplish the necessary authentication?</p>
1
2009-04-07T00:13:07Z
740,081
<p>It's possible to use ClientLogin as described here:</p> <p><a href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Response" rel="nofollow">http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#Response</a></p> <p>Note the section at the bottom of the document that mentions handling a CAPTCHA challenge. </p> <p>There's example code included in the gdata python client in samples/calendar/calendarExample.py</p> <p>You need to call run_on_app_engine with the right arguments to make this work as described in the Appendix here:</p> <p><a href="http://code.google.com/appengine/articles/gdata.html" rel="nofollow">http://code.google.com/appengine/articles/gdata.html</a></p> <p>Note that the same document recommends against using ClientLogin for web apps. Using OAuth or AuthSub is the correct solution, but this is simpler and good enough for testing.</p>
1
2009-04-11T13:25:19Z
[ "python", "web-services", "google-app-engine" ]
Import XML into SQL database
723,757
<p>I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? </p> <p>I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development release.</p> <p>Also, if I have to do any scripting I would prefer to use Python because that's what I am most familiar with. </p> <p>Thanks.</p>
5
2009-04-07T00:39:25Z
723,824
<p>I've done this several times with Python, but never with such a big XML file. <a href="http://effbot.org/zone/element-index.htm" rel="nofollow">ElementTree</a> is an excellent XML library for Python that would be of assistance. If it was possible, I would divide the XML up into smaller files to make it easier to load into memory and parse.</p>
1
2009-04-07T01:11:28Z
[ "python", "sql", "xml" ]
Import XML into SQL database
723,757
<p>I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? </p> <p>I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development release.</p> <p>Also, if I have to do any scripting I would prefer to use Python because that's what I am most familiar with. </p> <p>Thanks.</p>
5
2009-04-07T00:39:25Z
723,903
<p>You can use the getiterator() function to iterate over the XML file without parsing the whole thing at once. You can do this with <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a>, which is included in the standard library, or with <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>.</p> <pre><code>for record in root.getiterator('record'): add_element_to_database(record) # Depends on your database interface. # I recommend SQLAlchemy. </code></pre>
4
2009-04-07T01:51:15Z
[ "python", "sql", "xml" ]
Import XML into SQL database
723,757
<p>I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? </p> <p>I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development release.</p> <p>Also, if I have to do any scripting I would prefer to use Python because that's what I am most familiar with. </p> <p>Thanks.</p>
5
2009-04-07T00:39:25Z
723,931
<p>It may be a common task, but maybe 20GB isn't as common with MySQL as it is with SQL Server.</p> <p>I've done this using SQL Server Integration Services and a bit of custom code. Whether you need either of those depends on what you need to do with 20GB of XML in a database. Is it going to be a single column of a single row of a table? One row per child element?</p> <p>SQL Server has an XML datatype if you simply want to store the XML as XML. This type allows you to do queries using XQuery, allows you to create XML indexes over the XML, and allows the XML column to be "strongly-typed" by referring it to a set of XML schemas, which you store in the database.</p>
0
2009-04-07T02:04:11Z
[ "python", "sql", "xml" ]
Import XML into SQL database
723,757
<p>I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? </p> <p>I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development release.</p> <p>Also, if I have to do any scripting I would prefer to use Python because that's what I am most familiar with. </p> <p>Thanks.</p>
5
2009-04-07T00:39:25Z
724,602
<p>Take a look at the <code>iterparse()</code> function from <code>ElementTree</code> or <code>cElementTree</code> (I guess cElementTree would be best if you can use it)</p> <p>This piece describes more or less what you need to do: <a href="http://effbot.org/zone/element-iterparse.htm#incremental-parsing" rel="nofollow">http://effbot.org/zone/element-iterparse.htm#incremental-parsing</a></p> <p>This will probably be the most efficient way to do it in Python. Make sure not to forget to call <code>.clear()</code> on the appropriate elements (you <em>really</em> don't want to build an in memory tree of a 20gig xml file: the <code>.getiterator()</code> method described in another answer is slightly simpler, but <em>does</em> require the whole tree first - I assume that the poster actually had <code>iterparse()</code> in mind as well)</p>
2
2009-04-07T08:13:20Z
[ "python", "sql", "xml" ]
Import XML into SQL database
723,757
<p>I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? </p> <p>I know this ability is built into MySQL 6.0, but that is not an option right now because it is an alpha development release.</p> <p>Also, if I have to do any scripting I would prefer to use Python because that's what I am most familiar with. </p> <p>Thanks.</p>
5
2009-04-07T00:39:25Z
737,002
<p>The <a href="http://dev.mysql.com/tech-resources/articles/xml-in-mysql5.1-6.0.html" rel="nofollow">MySQL documentation</a> does not seem to indicate that XML import is restricted to version 6. It apparently works with 5, too.</p>
0
2009-04-10T07:56:12Z
[ "python", "sql", "xml" ]
WSGI Authentication: Homegrown, Authkit, OpenID...?
723,856
<p>I want basic authentication for a very minimal site, all I personally need is a single superuser. While hard-coding a password and username in one of my source files is awfully tempting, especially since I'm hosting the site on my own server, I feel I'm breaking the law of the internets and I should just use a database (I'm using sqlite for blog posts and such). Which would be the <strong><em>easiest</em></strong> to setup, in terms of time and effort, out of OpenID or AuthKit (repoze just scares me.. it feels like too much overhead for what I'm trying to achieve), or should I roll my own? </p> <p>Why I brought up OpenID is, it might just solve my spam problem (I'm currently using Akismet), to just require all commentors to login with an OpenID. I have absolutely no idea how to go about integrating OpenID with my WSGI application though (it's probably dead simple, I've never actually looked into it yet).</p>
6
2009-04-07T01:23:45Z
723,890
<p>AuthKit includes a built-in OpenID module, if that helps.</p> <p>The AuthKit cookbook includes a simple example here... <a href="http://wiki.pylonshq.com/display/authkitcookbook/OpenID+Passurl" rel="nofollow">http://wiki.pylonshq.com/display/authkitcookbook/OpenID+Passurl</a> </p> <p>That said, if you only need a single login (so there's no complex user management going on), why not use Apache's built-in authentication features (<a href="http://httpd.apache.org/docs/2.0/mod/mod%5Fauth.html#authuserfile" rel="nofollow">AuthUserFile .htpasswd</a> together with <a href="http://httpd.apache.org/docs/2.0/mod/core.html#require" rel="nofollow">Require valid-user</a>)?</p>
2
2009-04-07T01:44:51Z
[ "python", "authentication", "wsgi" ]
WSGI Authentication: Homegrown, Authkit, OpenID...?
723,856
<p>I want basic authentication for a very minimal site, all I personally need is a single superuser. While hard-coding a password and username in one of my source files is awfully tempting, especially since I'm hosting the site on my own server, I feel I'm breaking the law of the internets and I should just use a database (I'm using sqlite for blog posts and such). Which would be the <strong><em>easiest</em></strong> to setup, in terms of time and effort, out of OpenID or AuthKit (repoze just scares me.. it feels like too much overhead for what I'm trying to achieve), or should I roll my own? </p> <p>Why I brought up OpenID is, it might just solve my spam problem (I'm currently using Akismet), to just require all commentors to login with an OpenID. I have absolutely no idea how to go about integrating OpenID with my WSGI application though (it's probably dead simple, I've never actually looked into it yet).</p>
6
2009-04-07T01:23:45Z
723,904
<p>You can adapt this.</p> <p><a href="http://code.activestate.com/recipes/302378/" rel="nofollow">http://code.activestate.com/recipes/302378/</a></p> <p>Or, better, adapt this.</p> <p><a href="http://devel.almad.net/trac/django-http-digest/" rel="nofollow">http://devel.almad.net/trac/django-http-digest/</a></p> <p>This is quite nice.</p>
0
2009-04-07T01:51:22Z
[ "python", "authentication", "wsgi" ]
WSGI Authentication: Homegrown, Authkit, OpenID...?
723,856
<p>I want basic authentication for a very minimal site, all I personally need is a single superuser. While hard-coding a password and username in one of my source files is awfully tempting, especially since I'm hosting the site on my own server, I feel I'm breaking the law of the internets and I should just use a database (I'm using sqlite for blog posts and such). Which would be the <strong><em>easiest</em></strong> to setup, in terms of time and effort, out of OpenID or AuthKit (repoze just scares me.. it feels like too much overhead for what I'm trying to achieve), or should I roll my own? </p> <p>Why I brought up OpenID is, it might just solve my spam problem (I'm currently using Akismet), to just require all commentors to login with an OpenID. I have absolutely no idea how to go about integrating OpenID with my WSGI application though (it's probably dead simple, I've never actually looked into it yet).</p>
6
2009-04-07T01:23:45Z
1,050,184
<p>also look at repose.who</p> <p><a href="http://static.repoze.org/whodocs/" rel="nofollow">http://static.repoze.org/whodocs/</a></p>
4
2009-06-26T17:06:48Z
[ "python", "authentication", "wsgi" ]
WSGI Authentication: Homegrown, Authkit, OpenID...?
723,856
<p>I want basic authentication for a very minimal site, all I personally need is a single superuser. While hard-coding a password and username in one of my source files is awfully tempting, especially since I'm hosting the site on my own server, I feel I'm breaking the law of the internets and I should just use a database (I'm using sqlite for blog posts and such). Which would be the <strong><em>easiest</em></strong> to setup, in terms of time and effort, out of OpenID or AuthKit (repoze just scares me.. it feels like too much overhead for what I'm trying to achieve), or should I roll my own? </p> <p>Why I brought up OpenID is, it might just solve my spam problem (I'm currently using Akismet), to just require all commentors to login with an OpenID. I have absolutely no idea how to go about integrating OpenID with my WSGI application though (it's probably dead simple, I've never actually looked into it yet).</p>
6
2009-04-07T01:23:45Z
1,448,922
<p>Opid is a very small and simple to use WSGI OpenID app: <a href="http://code.google.com/p/python-opid/" rel="nofollow">python-opid</a></p>
1
2009-09-19T16:43:04Z
[ "python", "authentication", "wsgi" ]
What's the best way to propagate information from my wx.Process back to my main thread?
723,984
<p>I'm trying to subclass <code>wx.Process</code> such that I have a customized process launcher that fires events back to the main thread with data collected from the stdout stream. Is this a good way of doing things?</p> <pre><code>class BuildProcess(wx.Process): def __init__(self, cmd, notify=None): wx.Process.__init__(self, notify) print "Constructing a build process" self.Bind(wx.EVT_IDLE, self.on_idle) self.Redirect() self.cmd = cmd self.pid = None def start(self): print "Starting the process" self.pid = wx.Execute(self.cmd, wx.EXEC_ASYNC, self) print "Started." def on_idle(self, evt): print "doing the idle thing..." stream = self.GetInputStream() if stream.CanRead(): text = stream.read() wx.PostEvent(self, BuildEvent(EVT_BUILD_UPDATE, self, data=text)) print text def OnTerminate(self, *args, **kwargs): wx.Process.OnTerminate(self, *args, **kwargs) print "Terminating" </code></pre> <p><code>BuildEvent</code> here is a custom subclass of <code>wx.PyEvent</code>. The process is starting, running, and terminating correctly, but my <code>on_idle</code> function is never executing, even though I'm sure I've bound it to the idle event. </p>
0
2009-04-07T02:38:47Z
724,491
<p>From looking the the wxProcess docs, I don't think it works that way: wxProcess will create a new, seperate process running as a child of you current process. It is not possible to run methods connected to a message in such a process.</p> <p>Maybe you can connect your idle event to a function or method in you main thread.</p> <p>Or, mayby the wxThread class is what you really want to use.</p>
0
2009-04-07T07:28:52Z
[ "python", "multithreading", "events", "process", "wxpython" ]
What's the best way to propagate information from my wx.Process back to my main thread?
723,984
<p>I'm trying to subclass <code>wx.Process</code> such that I have a customized process launcher that fires events back to the main thread with data collected from the stdout stream. Is this a good way of doing things?</p> <pre><code>class BuildProcess(wx.Process): def __init__(self, cmd, notify=None): wx.Process.__init__(self, notify) print "Constructing a build process" self.Bind(wx.EVT_IDLE, self.on_idle) self.Redirect() self.cmd = cmd self.pid = None def start(self): print "Starting the process" self.pid = wx.Execute(self.cmd, wx.EXEC_ASYNC, self) print "Started." def on_idle(self, evt): print "doing the idle thing..." stream = self.GetInputStream() if stream.CanRead(): text = stream.read() wx.PostEvent(self, BuildEvent(EVT_BUILD_UPDATE, self, data=text)) print text def OnTerminate(self, *args, **kwargs): wx.Process.OnTerminate(self, *args, **kwargs) print "Terminating" </code></pre> <p><code>BuildEvent</code> here is a custom subclass of <code>wx.PyEvent</code>. The process is starting, running, and terminating correctly, but my <code>on_idle</code> function is never executing, even though I'm sure I've bound it to the idle event. </p>
0
2009-04-07T02:38:47Z
725,462
<p>The objective is not to call methods of another process, the objective is to redirect the stdout of another process back to the parent process via "update" events fired periodically as the process executes. </p> <p>One solution is to use wx.Timer to periodically poll the output stream of the process, so that we don't rely on EVT_IDLE to do the work for us (I had trouble getting EVT_IDLE to fire)</p> <pre><code>class BuildProcess(wx.Process): def __init__(self, cmd, notify=None): wx.Process.__init__(self, notify) self.Redirect() self.cmd = cmd self.pid = None self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_timer) def start(self): wx.PostEvent(self, BuildEvent(EVT_BUILD_STARTED, self)) self.pid = wx.Execute(self.cmd, wx.EXEC_ASYNC, self) self.timer.Start(100) def on_timer(self, evt): stream = self.GetInputStream() if stream.CanRead(): text = stream.read() wx.PostEvent(self, BuildEvent(EVT_BUILD_UPDATE, self, data=text)) def OnTerminate(self, *args, **kwargs): print "terminating..." stream = self.GetInputStream() if stream.CanRead(): text = stream.read() wx.PostEvent(self, BuildEvent(EVT_BUILD_UPDATE, self, data=text)) if self.timer: self.timer.Stop() wx.PostEvent(self, BuildEvent(EVT_BUILD_FINISHED, self)) </code></pre> <p>By this method, every 100ms the output stream is read, packaged up, and shipped off as a build event.</p>
1
2009-04-07T12:32:47Z
[ "python", "multithreading", "events", "process", "wxpython" ]
How to handle unicode of an unknown encoding in Django?
724,212
<p>I want to save some text to the database using the Django ORM wrappers. The problem is, this text is generated by scraping external websites and many times it seems they are listed with the wrong encoding. I would like to store the raw bytes so I can improve my encoding detection as time goes on without redoing the scrapes. But Django seems to want everything to be stored as unicode. Can I get around that somehow?</p>
1
2009-04-07T05:18:27Z
724,955
<p>You can store data, encoded into base64, for example. Or try to analize HTTP headers from browser, may be it is simplier to get proper encoding from there.</p>
1
2009-04-07T10:18:10Z
[ "python", "django", "unicode" ]
How to handle unicode of an unknown encoding in Django?
724,212
<p>I want to save some text to the database using the Django ORM wrappers. The problem is, this text is generated by scraping external websites and many times it seems they are listed with the wrong encoding. I would like to store the raw bytes so I can improve my encoding detection as time goes on without redoing the scrapes. But Django seems to want everything to be stored as unicode. Can I get around that somehow?</p>
1
2009-04-07T05:18:27Z
724,957
<p>Create a File with the data. Use a Django <code>models.FileField</code> to hold a reference to the file.</p> <p>No it does not involve a ton of I/O. If your file is small it adds 2 or 3 I/O's (the directory read, the iNode read and the data read.) </p>
1
2009-04-07T10:20:20Z
[ "python", "django", "unicode" ]
ctypes bindings for Subversion in windows
724,580
<p>Is there a binary installer or a faq for the new ctypes bindings for Subversion 1.6 in Windows (32 and 64bit)?</p> <p>What library would you use to make an easy to deploy (both win32 and x64) svn client in python for svn version >= 1.5?</p>
0
2009-04-07T08:07:46Z
724,756
<p>You have the <a href="http://pysvn.tigris.org/project%5Fdownloads.html" rel="nofollow">pysvn</a> module which will allow you to do that:</p> <p>Binary installer based on subversion 1.5.5</p>
1
2009-04-07T09:07:13Z
[ "python", "windows", "svn", "ctypes" ]
Python distutils, how to get a compiler that is going to be used?
724,664
<p>For example, I may use <code>python setup.py build --compiler=msvc</code> or <code>python setup.py build --compiler=mingw32</code> or just <code>python setup.py build</code>, in which case the default compiler (say, <code>bcpp</code>) will be used. How can I get the compiler name inside my setup.py (e. g. <code>msvc</code>, <code>mingw32</code> and <code>bcpp</code>, respectively)?</p> <p>UPD.: I don't need the default compiler, I need the one that is <strong>actually</strong> going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse <code>sys.argv</code> to see if there's a <code>--compiler...</code> string there.</p>
22
2009-04-07T08:36:07Z
724,745
<p>import distutils.ccompiler</p> <p>compiler_name = distutils.ccompiler.get_default_compiler()</p>
0
2009-04-07T09:04:37Z
[ "python", "compiler-construction", "installation", "distutils" ]
Python distutils, how to get a compiler that is going to be used?
724,664
<p>For example, I may use <code>python setup.py build --compiler=msvc</code> or <code>python setup.py build --compiler=mingw32</code> or just <code>python setup.py build</code>, in which case the default compiler (say, <code>bcpp</code>) will be used. How can I get the compiler name inside my setup.py (e. g. <code>msvc</code>, <code>mingw32</code> and <code>bcpp</code>, respectively)?</p> <p>UPD.: I don't need the default compiler, I need the one that is <strong>actually</strong> going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse <code>sys.argv</code> to see if there's a <code>--compiler...</code> string there.</p>
22
2009-04-07T08:36:07Z
1,671,060
<p>You can subclass the <code>distutils.command.build_ext.build_ext</code> command.</p> <p>Once <code>build_ext.finalize_options()</code> method has been called, the compiler type is stored in <code>self.compiler.compiler_type</code> as a string (the same as the one passed to the <code>build_ext</code>'s <code>--compiler</code> option, e.g. 'mingw32', 'gcc', etc...).</p>
5
2009-11-04T00:37:28Z
[ "python", "compiler-construction", "installation", "distutils" ]
Python distutils, how to get a compiler that is going to be used?
724,664
<p>For example, I may use <code>python setup.py build --compiler=msvc</code> or <code>python setup.py build --compiler=mingw32</code> or just <code>python setup.py build</code>, in which case the default compiler (say, <code>bcpp</code>) will be used. How can I get the compiler name inside my setup.py (e. g. <code>msvc</code>, <code>mingw32</code> and <code>bcpp</code>, respectively)?</p> <p>UPD.: I don't need the default compiler, I need the one that is <strong>actually</strong> going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse <code>sys.argv</code> to see if there's a <code>--compiler...</code> string there.</p>
22
2009-04-07T08:36:07Z
2,002,999
<pre> #This should work pretty good def compilerName(): import re import distutils.ccompiler comp = distutils.ccompiler.get_default_compiler() getnext = False for a in sys.argv[2:]: if getnext: comp = a getnext = False continue #separated by space if a == '--compiler' or re.search('^-[a-z]*c$', a): getnext = True continue #without space m = re.search('^--compiler=(.+)', a) if m == None: m = re.search('^-[a-z]*c(.+)', a) if m: comp = m.group(1) return comp print "Using compiler " + '"' + compilerName() + '"' </pre>
1
2010-01-04T23:16:04Z
[ "python", "compiler-construction", "installation", "distutils" ]
Python distutils, how to get a compiler that is going to be used?
724,664
<p>For example, I may use <code>python setup.py build --compiler=msvc</code> or <code>python setup.py build --compiler=mingw32</code> or just <code>python setup.py build</code>, in which case the default compiler (say, <code>bcpp</code>) will be used. How can I get the compiler name inside my setup.py (e. g. <code>msvc</code>, <code>mingw32</code> and <code>bcpp</code>, respectively)?</p> <p>UPD.: I don't need the default compiler, I need the one that is <strong>actually</strong> going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse <code>sys.argv</code> to see if there's a <code>--compiler...</code> string there.</p>
22
2009-04-07T08:36:07Z
5,192,738
<p>This is an expanded version of Luper Rouch's answer that worked for me to get an openmp extension to compile using both mingw and msvc on windows. After subclassing build_ext you need to pass it to setup.py in the cmdclass arg. By subclassing build_extensions instead of finalize_options you'll have the actual compiler object to look into, so you can then get more detailed version information. You could eventually set compiler flags on a per-compiler, per-extension basis:</p> <pre><code>from distutils.core import setup, Extension from distutils.command.build_ext import build_ext copt = {'msvc': ['/openmp', '/Ox', '/fp:fast','/favor:INTEL64','/Og'] , 'mingw32' : ['-fopenmp','-O3','-ffast-math','-march=native'] } lopt = {'mingw32' : ['-fopenmp'] } class build_ext_subclass( build_ext ): def build_extensions(self): c = self.compiler.compiler_type if copt.has_key(c): for e in self.extensions: e.extra_compile_args = copt[ c ] if lopt.has_key(c): for e in self.extensions: e.extra_link_args = lopt[ c ] build_ext.build_extensions(self) mod = Extension('_wripaca', sources=['../wripaca_wrap.c', '../../src/wripaca.c'], include_dirs=['../../include'] ) setup (name = 'wripaca', ext_modules = [mod], py_modules = ["wripaca"], cmdclass = {'build_ext': build_ext_subclass } ) </code></pre>
17
2011-03-04T10:49:56Z
[ "python", "compiler-construction", "installation", "distutils" ]
Python distutils, how to get a compiler that is going to be used?
724,664
<p>For example, I may use <code>python setup.py build --compiler=msvc</code> or <code>python setup.py build --compiler=mingw32</code> or just <code>python setup.py build</code>, in which case the default compiler (say, <code>bcpp</code>) will be used. How can I get the compiler name inside my setup.py (e. g. <code>msvc</code>, <code>mingw32</code> and <code>bcpp</code>, respectively)?</p> <p>UPD.: I don't need the default compiler, I need the one that is <strong>actually</strong> going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse <code>sys.argv</code> to see if there's a <code>--compiler...</code> string there.</p>
22
2009-04-07T08:36:07Z
8,168,576
<pre><code>import sys sys.argv.extend(['--compiler', 'msvc']) </code></pre>
0
2011-11-17T14:17:00Z
[ "python", "compiler-construction", "installation", "distutils" ]
Python distutils, how to get a compiler that is going to be used?
724,664
<p>For example, I may use <code>python setup.py build --compiler=msvc</code> or <code>python setup.py build --compiler=mingw32</code> or just <code>python setup.py build</code>, in which case the default compiler (say, <code>bcpp</code>) will be used. How can I get the compiler name inside my setup.py (e. g. <code>msvc</code>, <code>mingw32</code> and <code>bcpp</code>, respectively)?</p> <p>UPD.: I don't need the default compiler, I need the one that is <strong>actually</strong> going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse <code>sys.argv</code> to see if there's a <code>--compiler...</code> string there.</p>
22
2009-04-07T08:36:07Z
10,051,724
<pre><code>class BuildWithDLLs(build): # On Windows, we install the git2.dll too. def _get_dlls(self): # return a list of of (FQ-in-name, relative-out-name) tuples. ret = [] bld_ext = self.distribution.get_command_obj('build_ext') compiler_type = bld_ext.compiler.compiler_type </code></pre> <p>You can use self.distribution.get_command_obj('build_ext') to get build_ext instance, and then get the compiler_type</p>
0
2012-04-07T04:22:45Z
[ "python", "compiler-construction", "installation", "distutils" ]
Picking out items from a python list which have specific indexes
724,856
<p>I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!</p> <p>I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.</p> <p>For example:</p> <pre><code>indexes = [2, 4, 5] main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8] </code></pre> <p>the output would be:</p> <pre><code>[9, 2, 6] </code></pre> <p>(i.e., the elements with indexes 2, 4 and 5 from main_list).</p> <p>I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension).</p>
9
2009-04-07T09:43:33Z
724,869
<pre><code>t = [] for i in indexes: t.append(main_list[i]) return t </code></pre>
2
2009-04-07T09:47:29Z
[ "python", "list", "list-comprehension" ]
Picking out items from a python list which have specific indexes
724,856
<p>I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!</p> <p>I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.</p> <p>For example:</p> <pre><code>indexes = [2, 4, 5] main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8] </code></pre> <p>the output would be:</p> <pre><code>[9, 2, 6] </code></pre> <p>(i.e., the elements with indexes 2, 4 and 5 from main_list).</p> <p>I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension).</p>
9
2009-04-07T09:43:33Z
724,880
<p>I think Yuval A's solution is a pretty clear and simple. But if you actually want a one line list comprehension:</p> <pre><code>[e for i, e in enumerate(main_list) if i in indexes] </code></pre>
1
2009-04-07T09:50:51Z
[ "python", "list", "list-comprehension" ]
Picking out items from a python list which have specific indexes
724,856
<p>I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!</p> <p>I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.</p> <p>For example:</p> <pre><code>indexes = [2, 4, 5] main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8] </code></pre> <p>the output would be:</p> <pre><code>[9, 2, 6] </code></pre> <p>(i.e., the elements with indexes 2, 4 and 5 from main_list).</p> <p>I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension).</p>
9
2009-04-07T09:43:33Z
724,881
<pre><code>[main_list[x] for x in indexes] </code></pre> <p>This will return a list of the objects, using a list comprehension.</p>
41
2009-04-07T09:50:52Z
[ "python", "list", "list-comprehension" ]
Picking out items from a python list which have specific indexes
724,856
<p>I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one!</p> <p>I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list.</p> <p>For example:</p> <pre><code>indexes = [2, 4, 5] main_list = [0, 1, 9, 3, 2, 6, 1, 9, 8] </code></pre> <p>the output would be:</p> <pre><code>[9, 2, 6] </code></pre> <p>(i.e., the elements with indexes 2, 4 and 5 from main_list).</p> <p>I have a feeling this should be doable using something like list comprehensions, but I can't figure it out (in particular, I can't figure out how to access the index of an item when using a list comprehension).</p>
9
2009-04-07T09:43:33Z
726,038
<pre><code>map(lambda x:main_list[x],indexes) </code></pre>
0
2009-04-07T14:33:09Z
[ "python", "list", "list-comprehension" ]
How to make pdb recognize that the source has changed between runs?
724,924
<p>From what I can tell, pdb does not recognize when the source code has changed between "runs". That is, if I'm debugging, notice a bug, fix that bug, and rerun the program in pdb (i.e. without exiting pdb), pdb will not recompile the code. I'll still be debugging the old version of the code, even if pdb lists the new source code.</p> <p>So, does pdb not update the compiled code as the source changes? If not, is there a way to make it do so? I'd like to be able to stay in a single pdb session in order to keep my breakpoints and such.</p> <p>FWIW, gdb will notice when the program it's debugging changes underneath it, though only on a restart of that program. This is the behavior I'm trying to replicate in pdb.</p>
4
2009-04-07T10:09:09Z
725,271
<p>What do you mean by "rerun the program in pdb?" If you've imported a module, Python won't reread it unless you explicitly ask to do so, i.e. with <code>reload(module)</code>. However, <code>reload</code> is far from bulletproof (see <a href="http://svn.python.org/projects/sandbox/trunk/xreload/xreload.py" rel="nofollow">xreload</a> for another strategy).</p> <p>There are plenty of pitfalls in Python code reloading. To more robustly solve your problem, you could wrap pdb with a class that records your breakpoint info to a file on disk, for example, and plays them back on command.</p> <p>(Sorry, ignore the first version of this answer; it's early and I didn't read your question carefully enough.)</p>
2
2009-04-07T11:44:45Z
[ "python", "debugging", "pdb" ]
How to make pdb recognize that the source has changed between runs?
724,924
<p>From what I can tell, pdb does not recognize when the source code has changed between "runs". That is, if I'm debugging, notice a bug, fix that bug, and rerun the program in pdb (i.e. without exiting pdb), pdb will not recompile the code. I'll still be debugging the old version of the code, even if pdb lists the new source code.</p> <p>So, does pdb not update the compiled code as the source changes? If not, is there a way to make it do so? I'd like to be able to stay in a single pdb session in order to keep my breakpoints and such.</p> <p>FWIW, gdb will notice when the program it's debugging changes underneath it, though only on a restart of that program. This is the behavior I'm trying to replicate in pdb.</p>
4
2009-04-07T10:09:09Z
23,207,689
<p>The following mini-module may help. If you import it in your pdb session, then you can use:</p> <pre><code>pdb&gt; pdbs.r() </code></pre> <p>at any time to force-reload all non-system modules except <strong>main</strong>. The code skips that because it throws an ImportError('Cannot re-init internal module <strong>main</strong>') exception.</p> <pre><code># pdbs.py - PDB support from __future__ import print_function def r(): """Reload all non-system modules, so a pdb restart will reload anything new """ import sys # This is likely to be OS-specific SYS_PREFIX = '/usr/lib' for k, v in sys.modules.items(): if not hasattr(v, '__file__'): continue if v.__file__.startswith(SYS_PREFIX): continue if k == '__main__': continue print('reloading %s [%s]' % (k, v.__file__)) reload(v) </code></pre>
3
2014-04-21T23:22:56Z
[ "python", "debugging", "pdb" ]
String manipulation in Python
725,364
<p>I am converting some code from another language to python. That code reads a rather large file into a string and then manipulates it by array indexing like:</p> <pre><code>str[i] = 'e' </code></pre> <p>This does not work directly in python due to the strings being immutable. What is the preferred way of doing this in python ?</p> <p>I have seen the <code>string.replace()</code> function, but it returns a copy of the string which does not sound very optimal as the string in this case is an entire file.</p>
1
2009-04-07T12:10:57Z
725,382
<pre><code>l = list(str) l[i] = 'e' str = ''.join(l) </code></pre>
9
2009-04-07T12:14:38Z
[ "python", "string", "replace" ]
String manipulation in Python
725,364
<p>I am converting some code from another language to python. That code reads a rather large file into a string and then manipulates it by array indexing like:</p> <pre><code>str[i] = 'e' </code></pre> <p>This does not work directly in python due to the strings being immutable. What is the preferred way of doing this in python ?</p> <p>I have seen the <code>string.replace()</code> function, but it returns a copy of the string which does not sound very optimal as the string in this case is an entire file.</p>
1
2009-04-07T12:10:57Z
725,388
<p>Assuming you're not using a variable-length text encoding such as UTF-8, you can use <code>array.array</code>:</p> <pre><code>&gt;&gt;&gt; import array &gt;&gt;&gt; a = array.array('c', 'foo') &gt;&gt;&gt; a[1] = 'e' &gt;&gt;&gt; a array('c', 'feo') &gt;&gt;&gt; a.tostring() 'feo' </code></pre> <p>But since you're dealing with the contents of a file, <a href="http://docs.python.org/library/mmap.html" rel="nofollow"><code>mmap</code></a> should be more efficient:</p> <pre><code>&gt;&gt;&gt; f = open('foo', 'r+') &gt;&gt;&gt; import mmap &gt;&gt;&gt; m = mmap.mmap(f.fileno(), 0) &gt;&gt;&gt; m[:] 'foo\n' &gt;&gt;&gt; m[1] = 'e' &gt;&gt;&gt; m[:] 'feo\n' &gt;&gt;&gt; exit() % cat foo feo </code></pre> <p>Here's a quick benchmarking script (you'll need to replace dd with something else for non-Unix OSes):</p> <pre><code>import os, time, array, mmap def modify(s): for i in xrange(len(s)): s[i] = 'q' def measure(func): start = time.time() func(open('foo', 'r+')) print func.func_name, time.time() - start def do_split(f): l = list(f.read()) modify(l) return ''.join(l) def do_array(f): a = array.array('c', f.read()) modify(a) return a.tostring() def do_mmap(f): m = mmap.mmap(f.fileno(), 0) modify(m) os.system('dd if=/dev/random of=foo bs=1m count=5') measure(do_mmap) measure(do_array) measure(do_split) </code></pre> <p>Output I got on my several-year-old laptop matches my intuition:</p> <pre><code>5+0 records in 5+0 records out 5242880 bytes transferred in 0.710966 secs (7374304 bytes/sec) do_mmap 1.00865888596 do_array 1.09792494774 do_split 1.20163106918 </code></pre> <p>So mmap is slightly faster but none of the suggested solutions is particularly different. If you're seeing a huge difference, try using <a href="http://docs.python.org/library/profile.html#module-pstats" rel="nofollow">cProfile</a> to see what's taking the time.</p>
12
2009-04-07T12:15:39Z
[ "python", "string", "replace" ]
String manipulation in Python
725,364
<p>I am converting some code from another language to python. That code reads a rather large file into a string and then manipulates it by array indexing like:</p> <pre><code>str[i] = 'e' </code></pre> <p>This does not work directly in python due to the strings being immutable. What is the preferred way of doing this in python ?</p> <p>I have seen the <code>string.replace()</code> function, but it returns a copy of the string which does not sound very optimal as the string in this case is an entire file.</p>
1
2009-04-07T12:10:57Z
725,392
<p>Try:</p> <pre><code>sl = list(s) sl[i] = 'e' s = ''.join(sl) </code></pre>
0
2009-04-07T12:16:05Z
[ "python", "string", "replace" ]
String manipulation in Python
725,364
<p>I am converting some code from another language to python. That code reads a rather large file into a string and then manipulates it by array indexing like:</p> <pre><code>str[i] = 'e' </code></pre> <p>This does not work directly in python due to the strings being immutable. What is the preferred way of doing this in python ?</p> <p>I have seen the <code>string.replace()</code> function, but it returns a copy of the string which does not sound very optimal as the string in this case is an entire file.</p>
1
2009-04-07T12:10:57Z
726,197
<p>Others have answered the string manipulation part of your question, but I think you ought to think about whether it would be better to parse the file and modify the data structure the text represents rather than manipulating the text directly.</p>
1
2009-04-07T14:57:50Z
[ "python", "string", "replace" ]
Finding all *rendered* images in a HTML file
725,756
<p>I need a way to find only <strong>rendered</strong> IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).</p> <p>I'm using Python on AppEngine.</p> <p>Any ideas?</p> <p>Thanks, Ivan</p>
0
2009-04-07T13:40:41Z
725,944
<p>The source code for rendered img tag are something like this:</p> <pre><code>&lt;img src="img.jpg"&gt;&lt;/img&gt; </code></pre> <p>If the img tag is displayed as text(not rendered), the html code would be like this:</p> <pre><code> &amp;lt;img src=&amp;quot;styles/BWLogo.jpg&amp;quot;&amp;gt;&amp;lt;/img&amp;gt; </code></pre> <p><code>&amp;lt;</code> is "&lt;" character, <code>&amp;gt;</code> is ">" character</p> <p>To match rendered img tag only,you can use regex to match img tag formed by &lt; and >, not <code>&amp;lt;</code> and <code>&amp;gt;</code></p> <p>Img tags in comments also need to be ignored by ingnoring characters between "<code>&lt;!--</code>" and "<code>--&gt;</code>"</p>
2
2009-04-07T14:11:57Z
[ "python", "html", "regex", "parsing" ]
Finding all *rendered* images in a HTML file
725,756
<p>I need a way to find only <strong>rendered</strong> IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).</p> <p>I'm using Python on AppEngine.</p> <p>Any ideas?</p> <p>Thanks, Ivan</p>
0
2009-04-07T13:40:41Z
727,015
<p>As image tags might be in between some &lt;pre&gt; or &lt;xmp&gt; tag you probably have to walk through the dom (= convert the html to a xml/dom tree and search through it) and find all the &lt;img&gt; nodes. There is a xml.dom class in the python standard library: <a href="http://docs.python.org/library/xml.dom.html" rel="nofollow">docs.python.org</a></p> <p>You could do that on the client aswell and report it back via ajax (this would mean more load on the server though).</p>
0
2009-04-07T18:28:30Z
[ "python", "html", "regex", "parsing" ]
Finding all *rendered* images in a HTML file
725,756
<p>I need a way to find only <strong>rendered</strong> IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).</p> <p>I'm using Python on AppEngine.</p> <p>Any ideas?</p> <p>Thanks, Ivan</p>
0
2009-04-07T13:40:41Z
727,028
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup" rel="nofollow">BeautifulSoup</a>. It is an HTML/XML parser for Python that provides simple, idiomatic ways of navigating, searching, and modifying the parse tree. It probably won't be mistaken by fake img tags.</p>
2
2009-04-07T18:31:30Z
[ "python", "html", "regex", "parsing" ]
Finding all *rendered* images in a HTML file
725,756
<p>I need a way to find only <strong>rendered</strong> IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).</p> <p>I'm using Python on AppEngine.</p> <p>Any ideas?</p> <p>Thanks, Ivan</p>
0
2009-04-07T13:40:41Z
727,122
<p>Sounds like a job for <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>:</p> <pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; doc = """ ... &lt;html&gt; ... &lt;body&gt; ... &lt;img src="test.jpg"&gt; ... &amp;lt;img src="yay.jpg"&amp;gt; ... &lt;!-- &lt;img src="ohnoes.jpg"&gt; --&gt; ... &lt;img src="hurrah.jpg"&gt; ... &lt;/body&gt; ... &lt;/html&gt; ... """ &gt;&gt;&gt; soup = BeautifulSoup(doc) &gt;&gt;&gt; soup.findAll('img') [&lt;img src="test.jpg" /&gt;, &lt;img src="hurrah.jpg" /&gt;] </code></pre> <p>As you can see, BeautifulSoup is smart enough to ignore comments and displayed HTML.</p> <p><strong>EDIT</strong>: I'm not sure what you mean by the RSS feed escaping ALL images, though. I wouldn't expect BeautifulSoup to figure out which are meant to be shown if they are all escaped. Can you clarify?</p>
2
2009-04-07T18:51:01Z
[ "python", "html", "regex", "parsing" ]
Dynamic use of a class method defined in a Cython extension module
725,777
<p>I would like to use the C implementation of a class method (generated from <a href="http://www.cython.org/" rel="nofollow">Cython</a>) if it is present, or use its Python equivalent if the C extension is not present. I first tried this:</p> <pre><code>class A(object): try: import c_ext method = c_ext.optimized_method except ImportError: def method(self): return "foo" </code></pre> <p>Where optimized_method is a function defined in a <a href="http://www.cython.org/" rel="nofollow">Cython</a> module:</p> <pre><code>def optimized_method(self): return "fasterfoo" </code></pre> <p>But this doesn't work:</p> <pre><code>&gt;&gt;&gt; A().method() exceptions.TypeError: optimized_method() takes exactly one argument (0 given) </code></pre> <p>The only way I found to make this work is:</p> <pre><code>class A(object): def method(self): try: import c_ext return c_ext.optimized_method(self) except ImportError: pass return "foo" </code></pre> <p>But checking for the module's presence at each function call seems quite suboptimal... Why isn't my first approach working ?</p> <p>[edit] : added <a href="http://www.cython.org/" rel="nofollow">Cython</a> module's contents</p>
3
2009-04-07T13:44:09Z
726,259
<p>Ok I just found the answer...</p> <p>The problem comes from the way Cython <a href="http://docs.cython.org/docs/limitations.html#behaviour-of-class-scopes" rel="nofollow">wraps the functions it exports</a>: every method is unbound regardless from where it is referenced.</p> <p>The solution is to explicitly declare a bound method:</p> <pre><code>class A(object): def method(self): return "foo" try: import c_ext import types A.method = types.MethodType(c_ext.optimized_method, None, A) except ImportError: pass </code></pre>
3
2009-04-07T15:11:47Z
[ "python", "methods", "cython" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
725,818
<p>In the example you gave, there is no difference, in terms of output, between <code>append</code> and <code>+=</code>. But there is a difference between <code>append</code> and <code>+</code> (which the question originally asked about).</p> <pre><code>&gt;&gt;&gt; a = [] &gt;&gt;&gt; id(a) 11814312 &gt;&gt;&gt; a.append("hello") &gt;&gt;&gt; id(a) 11814312 &gt;&gt;&gt; b = [] &gt;&gt;&gt; id(b) 11828720 &gt;&gt;&gt; c = b + ["hello"] &gt;&gt;&gt; id(c) 11833752 &gt;&gt;&gt; b += ["hello"] &gt;&gt;&gt; id(b) 11828720 </code></pre> <p>As you can see, <code>append</code> and <code>+=</code> have the same result; they add the item to the list, without producing a new list. Using <code>+</code> adds the two lists and produces a new list.</p>
44
2009-04-07T13:51:17Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
725,853
<pre><code> some_list2 += ["something"] </code></pre> <p>is actually </p> <pre><code> some_list2.extend(["something"]) </code></pre> <p>for one value, there is no difference. Documentation states, that:</p> <blockquote> <p><code>s.append(x)</code> same as <code>s[len(s):len(s)] = [x]</code> <br/> <code>s.extend(x)</code> same as <code>s[len(s):len(s)] = x</code></p> </blockquote> <p>Thus obviously <code>s.append(x)</code> is same as <code>s.extend([x])</code></p>
19
2009-04-07T13:54:49Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
725,863
<pre><code>&gt;&gt;&gt; a=[] &gt;&gt;&gt; a.append([1,2]) &gt;&gt;&gt; a [[1, 2]] &gt;&gt;&gt; a=[] &gt;&gt;&gt; a+=[1,2] &gt;&gt;&gt; a [1, 2] </code></pre> <p>See that append adds a single element to the list, which may be anything. <code>+=[]</code> joins the lists.</p>
36
2009-04-07T13:57:37Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
725,882
<p>For your case the only difference is performance: append is twice as fast.</p> <pre><code>Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.Timer('s.append("something")', 's = []').timeit() 0.20177424499999999 &gt;&gt;&gt; timeit.Timer('s += ["something"]', 's = []').timeit() 0.41192320500000079 Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.Timer('s.append("something")', 's = []').timeit() 0.23079359499999999 &gt;&gt;&gt; timeit.Timer('s += ["something"]', 's = []').timeit() 0.44208112500000141 </code></pre> <p>In general case <code>append</code> will add one item to the list, while <code>+=</code> will copy <em>all</em> elements of right-hand-side list into the left-hand-side list.</p> <p><strong>Update: perf analysis</strong></p> <p>Comparing bytecodes we can assume that <code>append</code> version wastes cycles in <code>LOAD_ATTR</code> + <code>CALL_FUNCTION</code>, and += version -- in <code>BUILD_LIST</code>. Apparently <code>BUILD_LIST</code> outweighs <code>LOAD_ATTR</code> + <code>CALL_FUNCTION</code>. </p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(compile("s = []; s.append('spam')", '', 'exec')) 1 0 BUILD_LIST 0 3 STORE_NAME 0 (s) 6 LOAD_NAME 0 (s) 9 LOAD_ATTR 1 (append) 12 LOAD_CONST 0 ('spam') 15 CALL_FUNCTION 1 18 POP_TOP 19 LOAD_CONST 1 (None) 22 RETURN_VALUE &gt;&gt;&gt; dis.dis(compile("s = []; s += ['spam']", '', 'exec')) 1 0 BUILD_LIST 0 3 STORE_NAME 0 (s) 6 LOAD_NAME 0 (s) 9 LOAD_CONST 0 ('spam') 12 BUILD_LIST 1 15 INPLACE_ADD 16 STORE_NAME 0 (s) 19 LOAD_CONST 1 (None) 22 RETURN_VALUE </code></pre> <p>We can improve performance even more by removing <code>LOAD_ATTR</code> overhead:</p> <pre><code>&gt;&gt;&gt; timeit.Timer('a("something")', 's = []; a = s.append').timeit() 0.15924410999923566 </code></pre>
130
2009-04-07T14:00:24Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
726,321
<p>In addition to the aspects described in the other answers, append and +[] have very different behaviors when you're trying to build a list of lists.</p> <pre><code>&gt;&gt;&gt; list1=[[1,2],[3,4]] &gt;&gt;&gt; list2=[5,6] &gt;&gt;&gt; list3=list1+list2 &gt;&gt;&gt; list3 [[1, 2], [3, 4], 5, 6] &gt;&gt;&gt; list1.append(list2) &gt;&gt;&gt; list1 [[1, 2], [3, 4], [5, 6]] </code></pre> <p>list1+['5','6'] adds '5' and '6' to the list1 as individual elements. list1.append(['5','6']) adds the list ['5','6'] to the list1 as a single element.</p>
3
2009-04-07T15:24:17Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
726,349
<p>+= is an assignment. When you use it you're really saying ‘some_list2= some_list2+['something']’. Assignments involve rebinding, so:</p> <pre><code>l= [] def a1(x): l.append(x) # works def a2(x): l= l+[x] # assign to l, makes l local # so attempt to read l for addition gives UnboundLocalError def a3(x): l+= [x] # fails for the same reason </code></pre> <p>The += operator should also normally create a new list object like list+list normally does:</p> <pre><code>&gt;&gt;&gt; l1= [] &gt;&gt;&gt; l2= l1 &gt;&gt;&gt; l1.append('x') &gt;&gt;&gt; l1 is l2 True &gt;&gt;&gt; l1= l1+['x'] &gt;&gt;&gt; l1 is l2 False </code></pre> <p>However in reality:</p> <pre><code>&gt;&gt;&gt; l2= l1 &gt;&gt;&gt; l1+= ['x'] &gt;&gt;&gt; l1 is l2 True </code></pre> <p>This is because Python lists implement <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fiadd%5F%5F">__iadd__()</a> to make a += augmented assignment short-circuit and call list.extend() instead. (It's a bit of a strange wart this: it usually does what you meant, but for confusing reasons.)</p> <p>In general, if you're appending/extended an existing list, and you want to keep the reference to the same list (instead of making a new one), it's best to be explicit and stick with the append()/extend() methods.</p>
25
2009-04-07T15:29:12Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
8,701,544
<p>The performance tests here are not correct:</p> <ol> <li>You shouldn't run the profile only once.</li> <li>If comparing append vs. += [] number of times you should declare append as a local function.</li> <li>time results are different on different python versions: 64 and 32 bit</li> </ol> <p>e.g. </p> <blockquote> <blockquote> <blockquote> <p>timeit.Timer('for i in xrange(100): app(i)', 's = [] ; app = s.append').timeit() </p> </blockquote> </blockquote> </blockquote> <p>good tests can be found here: <a href="http://markandclick.com/1/post/2012/01/python-list-append-vs.html" rel="nofollow">http://markandclick.com/1/post/2012/01/python-list-append-vs.html</a></p>
4
2012-01-02T13:42:10Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
9,694,555
<p>The rebinding behaviour mentioned in other answers does matter in certain circumstances:</p> <pre><code>&gt;&gt;&gt; a = ([],[]) &gt;&gt;&gt; a[0].append(1) &gt;&gt;&gt; a ([1], []) &gt;&gt;&gt; a[1] += [1] Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment </code></pre> <p>That's because augmented assignment always rebinds, even if the object was mutated in-place. The rebinding here happens to be <code>a[1] = *mutated list*</code>, which doesn't work for tuples.</p>
1
2012-03-14T01:03:43Z
[ "python", "list", "concatenation" ]
In Python, what is the difference between ".append()" and "+= []"?
725,782
<p>What is the difference between:</p> <pre><code>some_list1 = [] some_list1.append("something") </code></pre> <p>and</p> <pre><code>some_list2 = [] some_list2 += ["something"] </code></pre>
88
2009-04-07T13:44:24Z
24,136,781
<p>The difference is that <i><b>concatenate</b></i> will flatten the resulting list, whereas <i><b>append</b></i> will keep the levels intact:</p> <p>So for example with:</p> <pre><code>myList = [ ] listA = [1,2,3] listB = ["a","b","c"] </code></pre> <p>Using append, you end up with a list of lists:</p> <pre><code>&gt;&gt; myList.append(listA) &gt;&gt; myList.append(listB) &gt;&gt; myList [[1,2,3],['a',b','c']] </code></pre> <p>Using concatenate instead, you end up with a flat list:</p> <pre><code>&gt;&gt; myList += listA + listB &gt;&gt; myList [1,2,3,"a","b","c"] </code></pre>
2
2014-06-10T08:56:48Z
[ "python", "list", "concatenation" ]
Installing ipython with readline on the mac
726,449
<p>I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)</p> <p>I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)</p> <p>I found a <a href="http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/">blog post</a> and other sources saying this could be fixed by</p> <p><code>sudo easy_install -f <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> readline</code></p> <p>However, this leads to build errors in <code>readline.c</code> , particularly undeclared functions like <code>rl_compentry_func_t</code> and <code>rl_catch_signals</code>. </p> <p>Has anyone seen these errors? Is there another way to get ipython installed with readline?</p>
16
2009-04-07T15:55:16Z
726,611
<p>You can install everything you need with essentially one command using MacPorts. First download and install MacPorts from <a href="http://www.macports.org/">http://www.macports.org/</a>. </p> <p>Then just do the following in the terminal: 1) sudo port -v selfupdate<br /> 2) sudo port -v install py26-ipython</p> <p>That will install python2.6, ipython for python 2.6 and readline for you. The command to start ipython will be located at /opt/local/bin/ipython2.6</p>
3
2009-04-07T16:46:17Z
[ "python", "osx", "readline", "ipython" ]
Installing ipython with readline on the mac
726,449
<p>I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)</p> <p>I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)</p> <p>I found a <a href="http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/">blog post</a> and other sources saying this could be fixed by</p> <p><code>sudo easy_install -f <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> readline</code></p> <p>However, this leads to build errors in <code>readline.c</code> , particularly undeclared functions like <code>rl_compentry_func_t</code> and <code>rl_catch_signals</code>. </p> <p>Has anyone seen these errors? Is there another way to get ipython installed with readline?</p>
16
2009-04-07T15:55:16Z
727,539
<p>"I would actually like to use ipython for 2.6.1"</p> <p>It is available. I'm using it with 2.6.1 on os x. You just need to install the official python 2.6.1 distribution, then install ipython with easy_install.</p>
0
2009-04-07T20:51:21Z
[ "python", "osx", "readline", "ipython" ]
Installing ipython with readline on the mac
726,449
<p>I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)</p> <p>I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)</p> <p>I found a <a href="http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/">blog post</a> and other sources saying this could be fixed by</p> <p><code>sudo easy_install -f <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> readline</code></p> <p>However, this leads to build errors in <code>readline.c</code> , particularly undeclared functions like <code>rl_compentry_func_t</code> and <code>rl_catch_signals</code>. </p> <p>Has anyone seen these errors? Is there another way to get ipython installed with readline?</p>
16
2009-04-07T15:55:16Z
1,840,304
<p>To install ipython on Snow Leopard or Lion without using MacPorts, you can simply do:</p> <pre><code>sudo easy_install readline ipython </code></pre> <p>(Note that if you use the "pip" to install readline, then ipython won't see the readline library, not sure why).</p> <p><em>Edit:</em></p> <p>If you had ipython installed remove it with </p> <pre><code>sudo pip uninstall ipython </code></pre> <p>or</p> <pre><code>pip uninstall ipython #for virtualenvs </code></pre> <p>Then make sure you have installed readline first and reinstall iptyhon</p> <pre><code>pip install readline ipython </code></pre> <p>For some reasons, if readline wasn't present during the installation, it will install itself without support for readline or it use the default mac readline. </p>
34
2009-12-03T14:43:38Z
[ "python", "osx", "readline", "ipython" ]
Installing ipython with readline on the mac
726,449
<p>I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)</p> <p>I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)</p> <p>I found a <a href="http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/">blog post</a> and other sources saying this could be fixed by</p> <p><code>sudo easy_install -f <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> readline</code></p> <p>However, this leads to build errors in <code>readline.c</code> , particularly undeclared functions like <code>rl_compentry_func_t</code> and <code>rl_catch_signals</code>. </p> <p>Has anyone seen these errors? Is there another way to get ipython installed with readline?</p>
16
2009-04-07T15:55:16Z
4,483,997
<p>An alternative if you don't want to use ports. <strong>Caution: This is not upgrade safe.</strong></p> <p>Install <code>ipython</code> and <code>readline</code> as normal:</p> <pre><code>sudo easy_install -f http://ipython.scipy.org/dist/ readline ipython </code></pre> <p>Find the full path to your <code>readline</code> egg. For python 2.6 this will probably be:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/readline-2.5.1-py2.6-macosx-10.3-fat.egg </code></pre> <p>Edit <code>ipython</code> with your favourite text editor:</p> <pre><code>vim `which ipython` </code></pre> <p>Before the final line in the file <code>sys.exit</code>, insert:</p> <pre><code>sys.path.insert(0,'PATH_TO_READLINE_EGG') </code></pre> <p>Save and exit (<code>:wq</code>).</p> <p>Check readline is working correct:</p> <pre><code>ipython </code></pre>
1
2010-12-19T16:54:38Z
[ "python", "osx", "readline", "ipython" ]
Installing ipython with readline on the mac
726,449
<p>I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)</p> <p>I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)</p> <p>I found a <a href="http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/">blog post</a> and other sources saying this could be fixed by</p> <p><code>sudo easy_install -f <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> readline</code></p> <p>However, this leads to build errors in <code>readline.c</code> , particularly undeclared functions like <code>rl_compentry_func_t</code> and <code>rl_catch_signals</code>. </p> <p>Has anyone seen these errors? Is there another way to get ipython installed with readline?</p>
16
2009-04-07T15:55:16Z
8,749,044
<p>this worked for me (I'm using python 2.7, for other versions you'll need to edit):</p> <pre><code>cd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload sudo mv readline.so readline.so.bak </code></pre> <p>install readline however you want (pip, homebrew, macports, etc)</p> <pre><code>pip install -U readline </code></pre> <p>Success! and it works with virtualenv, and virtualenvwrapper, and no need to modify ipython :)</p>
13
2012-01-05T20:09:03Z
[ "python", "osx", "readline", "ipython" ]
Installing ipython with readline on the mac
726,449
<p>I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)</p> <p>I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)</p> <p>I found a <a href="http://www.brianberliner.com/2008/04/18/ipython-on-mac-os-x-105-leopard/">blog post</a> and other sources saying this could be fixed by</p> <p><code>sudo easy_install -f <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> readline</code></p> <p>However, this leads to build errors in <code>readline.c</code> , particularly undeclared functions like <code>rl_compentry_func_t</code> and <code>rl_catch_signals</code>. </p> <p>Has anyone seen these errors? Is there another way to get ipython installed with readline?</p>
16
2009-04-07T15:55:16Z
21,585,404
<p>The only working way on MacOS Mavericks is to:</p> <ol> <li>switch to your virtualenv <code>workon myproject_name</code></li> <li>delete readline and ipython (if you installed it before) <code>pip uninstall readline ipython</code></li> <li>install readline only via easy_install (pip - no work!) <code>easy_install readline</code></li> <li>finally install ipython with pip <code>pip install ipython</code></li> </ol> <p>It's work well on my MacOS and tested a long time.</p>
2
2014-02-05T18:25:23Z
[ "python", "osx", "readline", "ipython" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
727,438
<p>See <a href="https://cloud.google.com/appengine/docs/python/requests#Python_Logging">https://cloud.google.com/appengine/docs/python/requests#Python_Logging</a> <br/> and <a href="http://docs.python.org/library/logging.html">http://docs.python.org/library/logging.html</a></p> <p>You probably want to use something like:</p> <pre><code>logging.debug("value of my var is %s", str(var)) </code></pre>
31
2009-04-07T20:23:22Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
728,027
<p>You should also give FirePython a look. It allows you to get server log messages in firebug.</p> <p><a href="http://appengine-cookbook.appspot.com/recipe/firepython-logger-console-inside-firebug/" rel="nofollow">http://appengine-cookbook.appspot.com/recipe/firepython-logger-console-inside-firebug/</a></p>
2
2009-04-07T23:49:16Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
4,380,470
<p>@Manjoor</p> <p>You can do the same thing in java.</p> <pre><code>import java.util.logging.Logger; // ... public class MyServlet extends HttpServlet { private static final Logger log = Logger.getLogger(MyServlet.class.getName()); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("An informational message."); log.warning("A warning message."); log.severe("An error message."); } } </code></pre> <p>See "Logging" in <a href="http://code.google.com/appengine/docs/java/runtime.html">http://code.google.com/appengine/docs/java/runtime.html</a></p>
9
2010-12-07T18:54:45Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
7,239,145
<p>Check out my online Python interpreter running on Google App Engine on my website, <a href="http://www.learnpython.org" rel="nofollow">Learn Python</a>. It might be what you're looking for. Just use print repr(variable) on things you want to look at, and execute as many times as you want.</p>
1
2011-08-30T05:46:09Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
9,660,319
<p>You'll want to use the Python's standard <code>logging</code> module.</p> <pre><code>import logging logging.info("hello") logging.debug("hi") # this won't show up by default </code></pre> <p>To see calls to <code>logging.debug()</code> in the GoogleAppEngineLauncher Logs console, you have to first add the flag <code>--dev_appserver_log_level=debug</code> to your app. However, beware that you're going to see a lot of debug noise from the App Engine SDK itself. The <a href="https://cloud.google.com/appengine/docs/python/refdocs/modules/google/appengine/tools/devappserver2/devappserver2">full set of levels</a> are:</p> <ul> <li><code>debug</code></li> <li><code>info</code></li> <li><code>warning</code></li> <li><code>error</code></li> <li><code>critical</code></li> </ul> <p>You can add the flag by double clicking the app and then dropping it into the <strong>Extra Flags</strong> field.</p> <p><a href="http://i.stack.imgur.com/2LZW5.png"><img src="http://i.stack.imgur.com/2LZW5.png" alt="Adding the --dev_appserver_log_level flag to your app in the GoogleAppEngineLauncher"></a></p>
58
2012-03-12T00:23:48Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
17,842,828
<p>GAE will capture standard error and print it to the console or to a log.</p> <pre><code>print &gt;&gt; sys.stderr, "Something to log." </code></pre>
0
2013-07-24T19:10:40Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
18,987,161
<p><strong>Use log.setLevel(Level.ALL) to see messages</strong></p> <p>The default message filtering level seems to be 'error'. I didn't see any useful log messages until I used the setLevel() method to make the .info and .warning messages visible. </p> <p>Text printed to System.out wasn't showing up either. It seems to be interpreted as log.info() level messaages.</p>
0
2013-09-24T16:30:44Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
20,152,111
<p>Hello I'm using the version 1.8.6 of GoogleAppEngineLauncher, you can use a flag to set the messages log level you want to see, for example for debug messages:</p> <p><code>--dev_appserver_log_level debug</code></p> <p>Use it instead of <code>--debug</code> (see @Christopher answer).</p>
1
2013-11-22T18:37:23Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
22,467,787
<p>If you're using a more recent version of the Python Development Server (releases > 1.7.6, or Mar 2013 and later), these seem to be the right steps to use:</p> <ol> <li><p>Include the following in your script,</p> <p><code>import logging logging.debug("something I want to log")</code></p></li> <li><p>And per <a href="https://developers.google.com/appengine/docs/python/tools/old_devserver#New_Development_Server">this docs page</a>, set a flag by going to Edit > Application Settings > Launch Settings > Extra Command Line Flags, and adding, </p> <p><code>--log_level=debug</code></p></li> </ol>
4
2014-03-17T23:53:34Z
[ "python", "google-app-engine", "logging" ]
How do I write to the console in Google App Engine?
727,410
<p>Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine? </p>
42
2009-04-07T20:14:52Z
34,630,984
<p>I hope i am answering the question. The logging messages print to the AppEngine log rather than the terminal. </p> <p>You can launch it <a href="http://i.stack.imgur.com/I9wXa.png" rel="nofollow">by clicking on the logs button of the AppEngine Launcher</a></p>
0
2016-01-06T10:36:49Z
[ "python", "google-app-engine", "logging" ]
How can I convert Unicode to uppercase to print it?
727,507
<p>I have this:</p> <pre><code>&gt;&gt;&gt; print 'example' example &gt;&gt;&gt; print 'exámple' exámple &gt;&gt;&gt; print 'exámple'.upper() EXáMPLE </code></pre> <p>What I need to do to print:</p> <pre><code>EXÁMPLE </code></pre> <p><em>(Where the 'a' gets its accute accent, but in uppercase.)</em></p> <p>I'm using Python 2.6.</p>
28
2009-04-07T20:41:46Z
727,517
<p>I think it's as simple as <strong>not</strong> converting to ASCII first.</p> <pre><code> &gt;&gt;&gt; print u'exámple'.upper() EXÁMPLE </code></pre>
47
2009-04-07T20:45:53Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
How can I convert Unicode to uppercase to print it?
727,507
<p>I have this:</p> <pre><code>&gt;&gt;&gt; print 'example' example &gt;&gt;&gt; print 'exámple' exámple &gt;&gt;&gt; print 'exámple'.upper() EXáMPLE </code></pre> <p>What I need to do to print:</p> <pre><code>EXÁMPLE </code></pre> <p><em>(Where the 'a' gets its accute accent, but in uppercase.)</em></p> <p>I'm using Python 2.6.</p>
28
2009-04-07T20:41:46Z
727,571
<p>In python 2.x, just convert the string to unicode before calling upper(). Using your code, which is in utf-8 format on this webpage:</p> <pre><code>&gt;&gt;&gt; s = 'exámple' &gt;&gt;&gt; s 'ex\xc3\xa1mple' # my terminal is not utf8. c3a1 is the UTF-8 hex for á &gt;&gt;&gt; s.decode('utf-8').upper() u'EX\xc1MPLE' # c1 is the utf-16 aka unicode for á </code></pre> <p>The call to <code>decode</code> takes it from its current format to unicode. You can then convert it to some other format, like utf-8, by using encode. If the character was in, say, iso-8859-2 (Czech, etc, in this case), you would instead use <code>s.decode('iso-8859-2').upper()</code>.</p> <p>As in my case, if your terminal is not unicode/utf-8 compliant, the best you can hope for is either a hex representation of the characters (like mine) or to convert it lossily using <code>s.decode('utf-8').upper().encode('ascii', 'replace')</code>, which results in 'EX?MPLE'. If you can't make your terminal show unicode, write the output to a file in utf-8 format and open that in your favourite editor.</p>
15
2009-04-07T21:00:48Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
How can I convert Unicode to uppercase to print it?
727,507
<p>I have this:</p> <pre><code>&gt;&gt;&gt; print 'example' example &gt;&gt;&gt; print 'exámple' exámple &gt;&gt;&gt; print 'exámple'.upper() EXáMPLE </code></pre> <p>What I need to do to print:</p> <pre><code>EXÁMPLE </code></pre> <p><em>(Where the 'a' gets its accute accent, but in uppercase.)</em></p> <p>I'm using Python 2.6.</p>
28
2009-04-07T20:41:46Z
727,938
<p>I think there's a bit of background we're missing here:</p> <pre><code>&gt;&gt;&gt; type('hello') &lt;type 'str'&gt; &gt;&gt;&gt; type(u'hello') &lt;type 'unicode'&gt; </code></pre> <p>As long as you're using "unicode" strings instead of "native" strings, the operators like upper() will operate with unicode in mind. FWIW, Python 3 uses unicode by default, making the distinction largely irrelevant.</p> <p>Taking a string from <code>unicode</code> to <code>str</code> and then back to <code>unicode</code> is suboptimal in many ways, and many libraries will produce unicode output if you want it; so try to use only <code>unicode</code> objects for strings internally whenever you can.</p>
4
2009-04-07T23:09:10Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
How can I convert Unicode to uppercase to print it?
727,507
<p>I have this:</p> <pre><code>&gt;&gt;&gt; print 'example' example &gt;&gt;&gt; print 'exámple' exámple &gt;&gt;&gt; print 'exámple'.upper() EXáMPLE </code></pre> <p>What I need to do to print:</p> <pre><code>EXÁMPLE </code></pre> <p><em>(Where the 'a' gets its accute accent, but in uppercase.)</em></p> <p>I'm using Python 2.6.</p>
28
2009-04-07T20:41:46Z
3,691,817
<p>first off, i only use python 3.1 these days; its central merit is to have disambiguated byte strings from unicode objects. this makes the vast majority of text manipulations much safer than used to be the case. weighing in the trillions of user questions regarding python 2.x encoding problems, the <code>u'äbc</code> convention of python 2.1 was just a mistake; with explicit <code>bytes</code> and <code>bytearray</code>, life becomes so much easier.</p> <p>secondly, if py3k is not your flavor, then try to go with <code>from __future__ import unicode_literals</code>, as this will mimic py3k's behavior on python 2.6 and 2.7. this thing would have avoided the (easily committed) blunder you did when saying <code>print 'exámple'.upper()</code> . essentially, this is the same as in py3k: <code>print( 'exámple'.encode( 'utf-8' ).upper() )</code>. compare these versions (for py3k):</p> <pre><code>print( 'exámple'.encode( 'utf-8' ).upper() ) print( 'exámple'.encode( 'utf-8' ).upper().decode( 'utf-8' ) ) print( 'exámple'.upper() ) </code></pre> <p>The first one is, basically, what you did when used a bare string <code>'exámple'</code>, provided you set your default encoding to <code>utf-8</code> (according to a BDFL pronouncement, setting the default encoding at run time is a bad idea, so in py2 you'll have to trick it by saying <code>import sys; reload( sys ); sys.setdefaultencoding( 'utf-8' )</code>; i present a better solution for py3k below). when you look at the output of these three lines:</p> <pre><code>b'EX\xc3\xa1MPLE' EXáMPLE EXÁMPLE </code></pre> <p>you can see that when <code>upper()</code> got applied to the first text, it acted on bytes, not on characters. python allows the <code>upper()</code> method on bytes, but it is only defined on the US-ASCII interpretation of bytes. since utf-8 uses values <em>within</em> 8 bits but <em>outside</em> of US-ASCII (128 up to 255, which are not used by US-ASCII), those won't be affected by <code>upper()</code>, so when we decode back in the second line, we get that lower-case <code>á</code>. finally, the third line does it right, and yes, surprise, python seems to be aware that <code>Á</code> is the upper case letter corresponding to <code>á</code>. i ran a quick test to see what characters python 3 does not convert between upper and lower case:</p> <pre><code>for cid in range( 3000 ): my_chr = chr( cid ) if my_chr == my_chr.upper() and my_chr == my_chr.lower(): say( my_chr ) </code></pre> <p>perusing the list reveals very few incidences of latin, cyrillic, or greek letters; most of the output is non-european characters and punctuation. the only characters i could find that python got wrong are Ԥ/ԥ (\u0524, \u0525, 'cyrillic {capital|small} letter pe with descender'), so as long as you stay outside of the Latin Extended-X blocks (check out those, they might yield surprises), you might actually use that method. of course, i did not check the correctness of the mappings.</p> <p>lastly, here is what i put into my py3k application boot section: a method that redefines the encoding <code>sys.stdout</code> sees, with numerical character references (NCRs) as fallback; this has the effect that printing to standard output will never raise a unicode encoding error. when i work on ubuntu, <code>_sys.stdout.encoding</code> is <code>utf-8</code>; when the same program runs on windows, it might be something quaint like <code>cp850</code>. the output might looks starnge, but the application runs without raising an exception on those dim-witted terminals.</p> <pre><code>#=========================================================================================================== # MAKE STDOUT BEHAVE IN A FAILSAFE MANNER #----------------------------------------------------------------------------------------------------------- def _harden_stdout(): """Ensure that unprintable output to STDOUT does not cause encoding errors; use XML character references so any kind of output gets a chance to render in a decipherable way.""" global _sys_TRM _sys.stdout = _sys_TRM = _sys_io.TextIOWrapper( _sys.stdout.buffer, encoding = _sys.stdout.encoding, errors = 'xmlcharrefreplace', line_buffering = true ) #........................................................................................................... _harden_stdout() </code></pre> <p>one more piece of advice: when testing, always try to <code>print repr( x )</code> or a similar thing that reveals the identity of <code>x</code>. all kinds of misunderstandings can crop up if you just <code>print x</code> in py2 and <code>x</code> is either an octet string or a unicode object. it is very puzzling and prone to cause a lot of head-scratching. as i said, try to move at least to py26 with that from future import unicode literals incantation. </p> <p>and to close, quoting a quote: " Glyph Lefkowitz says it best in his article <a href="http://glyf.livejournal.com/39250.html">Encoding</a>:</p> <blockquote> <p>I believe that in the context of this discussion, the term "string" is meaningless. There is text, and there is byte-oriented data (which may very well represent text, but is not yet converted to it). In Python types, Text is unicode. Data is str. The idea of "non-Unicode text" is just a programming error waiting to happen."</p> </blockquote> <p>update: just found python 3 correctly converts ſ LATIN SMALL LETTER LONG S to S when uppercasing. neat!</p>
7
2010-09-11T16:52:59Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
Python __str__ and lists
727,761
<p>In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:</p> <pre><code>"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" </code></pre> <p>Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:</p> <pre><code>print 'my list is %s'%(list) </code></pre> <p>it looks something like this:</p> <pre><code>[&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;] </code></pre> <p>how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?</p>
58
2009-04-07T21:57:59Z
727,779
<p>Calling string on a python list calls the <code>__repr__</code> method on each element inside. For some items, <code>__str__</code> and <code>__repr__</code> are the same. If you want that behavior, do:</p> <pre><code>def __str__(self): ... def __repr__(self): return self.__str__() </code></pre>
84
2009-04-07T22:03:00Z
[ "python" ]
Python __str__ and lists
727,761
<p>In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:</p> <pre><code>"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" </code></pre> <p>Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:</p> <pre><code>print 'my list is %s'%(list) </code></pre> <p>it looks something like this:</p> <pre><code>[&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;] </code></pre> <p>how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?</p>
58
2009-04-07T21:57:59Z
727,780
<p>You can use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension</a> to generate a new list with each item str()'d automatically:</p> <pre><code>print([str(item) for item in mylist]) </code></pre>
14
2009-04-07T22:03:09Z
[ "python" ]
Python __str__ and lists
727,761
<p>In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:</p> <pre><code>"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" </code></pre> <p>Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:</p> <pre><code>print 'my list is %s'%(list) </code></pre> <p>it looks something like this:</p> <pre><code>[&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;] </code></pre> <p>how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?</p>
58
2009-04-07T21:57:59Z
727,783
<p>Two easy things you can do, use the <code>map</code> function or use a comprehension.</p> <p>But that gets you a list of strings, not a string. So you also have to join the strings together.</p> <pre><code>s= ",".join( map( str, myList ) ) </code></pre> <p>or</p> <pre><code>s= ",".join( [ str(element) for element in myList ] ) </code></pre> <p>Then you can print this composite string object.</p> <pre><code>print 'my list is %s'%( s ) </code></pre>
3
2009-04-07T22:03:47Z
[ "python" ]
Python __str__ and lists
727,761
<p>In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:</p> <pre><code>"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" </code></pre> <p>Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:</p> <pre><code>print 'my list is %s'%(list) </code></pre> <p>it looks something like this:</p> <pre><code>[&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;] </code></pre> <p>how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?</p>
58
2009-04-07T21:57:59Z
727,786
<p>Something like this?</p> <pre><code>a = [1, 2 ,3] [str(x) for x in a] # ['1', '2', '3'] </code></pre>
0
2009-04-07T22:04:09Z
[ "python" ]
Python __str__ and lists
727,761
<p>In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:</p> <pre><code>"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" </code></pre> <p>Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:</p> <pre><code>print 'my list is %s'%(list) </code></pre> <p>it looks something like this:</p> <pre><code>[&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;] </code></pre> <p>how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?</p>
58
2009-04-07T21:57:59Z
727,793
<p>Depending on what you want to use that output for, perhaps <code>__repr__</code> might be more appropriate:</p> <pre><code>import unittest class A(object): def __init__(self, val): self.val = val def __repr__(self): return repr(self.val) class Test(unittest.TestCase): def testMain(self): l = [A('a'), A('b')] self.assertEqual(repr(l), "['a', 'b']") if __name__ == '__main__': unittest.main() </code></pre>
2
2009-04-07T22:06:53Z
[ "python" ]
Python __str__ and lists
727,761
<p>In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:</p> <pre><code>"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" </code></pre> <p>Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:</p> <pre><code>print 'my list is %s'%(list) </code></pre> <p>it looks something like this:</p> <pre><code>[&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;] </code></pre> <p>how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?</p>
58
2009-04-07T21:57:59Z
727,944
<p>I agree with the previous answer about using list comprehensions to do this, but you could certainly hide that behind a function, if that's what floats your boat.</p> <pre><code>def is_list(value): if type(value) in (list, tuple): return True return False def list_str(value): if not is_list(value): return str(value) return [list_str(v) for v in value] </code></pre> <p>Just for fun, I made list_str() recursively str() everything contained in the list.</p>
2
2009-04-07T23:11:57Z
[ "python" ]
Transferring Python modules
727,791
<p>Basically for this case, I am using the _winreg module in Python v2.6 but the python package I have to use is v2.5. When I try to use:</p> <pre><code>_winreg.ExpandEnvironmentStrings </code></pre> <p>it complains about not having this attribute in this module. I have successfully transferred other modules like comtypes from site-packages folder.</p> <p>But the problem is I don't know which files to copy/replace. Is there a way to do this? Also is site-packages the main places for 3rd party modules?</p>
0
2009-04-07T22:05:47Z
727,808
<p>It's a compiled C extension, not pure Python, so you generally can't simply copy the DLL/so file across from one installation to another: the Python binary interface changes on 0.1 version number updates (but not 0.0.1 updates). In any case, _winreg seems to be statically build into Python.exe on the current official Windows builds rather than being dropped into the ‘DLLs’ folder.</p> <p><code>_winreg.ExpandEnvironmentStrings</code> is not available pre-2.6, but <s>you could usefully fall back to <a href="http://docs.python.org/library/os.path.html#os.path.expandvars" rel="nofollow"><code>os.path.expandvars</code></a>, which does more or less the same thing. (It also supports $VAR variables, which under Windows you might not want, but this may not be a practical problem.)</s> You're right: %-syntax for expandvars under Windows was only introduced in 2.6, how useless. Looks like you'll need the below.</p> <p>If the worst comes to the worst it's fairly simple to write by hand:</p> <pre><code>import re, os def expandEnvironmentStrings(s): r= re.compile('%([^%]+)%') return r.sub(lambda m: os.environ.get(m.group(1), m.group(0)), s) </code></pre> <p>Though either way there is always Python 2.x's inability to read Unicode envvars to worry about.</p>
2
2009-04-07T22:11:50Z
[ "python" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
727,963
<p>Since each section is a collection of multiple, independent form fields, I recommend using a custom form template. This gives you absolute full control over the layout with minimal extra work. Django's <a href="http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template" rel="nofollow">Customizing the Form Template</a> docs have the details.</p>
3
2009-04-07T23:19:00Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
727,964
<p>Even though your form is populated from a database, you should still be able to manually write out the form, or use a template. Check out the <a href="http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template" rel="nofollow">Django form documentation</a> for more details.</p>
0
2009-04-07T23:19:03Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
729,388
<p>Remember also that a Django Form object is just a collection of fields; there is no need for a 1:1 correspondence between HTML form tags and Django Form objects. If the various sections of the form are actually logically separate, you could consider splitting it up into three Forms, which you could then render in your template with any HTML you want between them (but still within a single HTML form tag).</p> <p>Whether this is a sensible solution depends quite a bit on the design of your app and the view, of course.</p>
1
2009-04-08T10:29:34Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
862,987
<p>If you want to customize the form, you don't have to render it <code>form.as_ul</code>. Django knows how to render foobar if you have set up the forms model properly...try it...no worries.</p> <p>Look at what python on the server sent your page. For example if it sent a django form like this:</p> <p><code>return respond(request, user, 'templateName', { 'myform':myform })</code></p> <p>then <em>templateName.html</em> will have:</p> <pre><code>&lt;blockquote&gt; &lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; {{myform.firstname }} &lt;p&gt;Here you enter your education data...&lt;/p&gt; {{myform.university }} &lt;p&gt; a choice field &lt;/p&gt; {{myform.foobar}} &lt;/form&gt; &lt;/blockquote&gt; </code></pre>
8
2009-05-14T12:15:26Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
1,705,229
<p>One way to do this without displaying your form in the template using form.as_ul, is with django-uni-form. First you'll have to download it <a href="http://github.com/pydanny/django-uni-form" rel="nofollow">here</a> and install it. Then the code for setting up your form could looks something like this:</p> <pre><code>from uni_form.helpers import FormHelper, Submit, Layout, Fieldset class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() # now attach a uni_form helper to display the form helper = FormHelper() # create the layout layout = Layout( # first fieldset Fieldset("Here you enter your personal data...", 'firstname', 'lastname'), Fieldset("Here you enter your education data...", 'university', 'major'), Fieldset('foobar') # and add a submit button sumbit = Submit('add', 'Submit information') helper.add_input(submit) </code></pre> <p>Now, to display this in your template you would do this:</p> <pre><code>{% load uni_form %} {% with form.helper as helper %} {% uni_form form helper %} {% endwith %} </code></pre> <p>This would output HTML (roughly) like this:</p> <pre><code>&lt;form&gt; &lt;fieldset&gt;&lt;legend&gt;Here you enter your personal data...&lt;/legend&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;/fieldset&gt; &lt;fieldset&gt;&lt;legend&gt;Here you enter your education data...&lt;/legend&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;input name='foobar'&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>For more info on uni_form, read their docs (see the link above).</p> <p>PS: I realize this reply is late, and I'm sure you already solved this problem, but I think this should be helpful for anyone just coming across this now.</p>
14
2009-11-10T02:07:41Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
2,043,716
<p>There is a <code>help_text</code> field in forms you know.</p> <p>in <em>forms.py</em>:</p> <ul> <li><code>myField = forms.myFieldType(help_text="Helping friendly text to put in your form", otherStuff=otherStuff)</code></li> </ul> <p>in <em>forms.html</em>:</p> <ul> <li><code>{{form.myField.help_text}}</code></li> </ul>
1
2010-01-11T17:55:35Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
3,343,691
<p>For those into a similar situation as the author, I recommend falling back to CSS and the <code>:before</code> and/or <code>:after</code> pseudoselectors either on the <code>input</code> or the <code>label</code> elements of the form. They work just as well and could make your life a lot easier as you can still use <code>{{ form.as_p }}</code>.</p>
0
2010-07-27T12:41:15Z
[ "python", "django", "django-forms" ]
Display some free text in between Django Form fields
727,917
<p>I have a form like the following:</p> <pre><code>class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() </code></pre> <p>Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul </p> <p>Also i wish i don't have to split the form in multiple forms for ease of mantainance</p> <p>Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?</p> <p>I'd like the form to render something like this:</p> <pre><code>&lt;form&gt; &lt;p&gt;Here you enter your personal data...&lt;/p&gt; &lt;input name='firstname'&gt; &lt;input name='lastname'&gt; &lt;p&gt;Here you enter your education data...&lt;/p&gt; &lt;input name='university'&gt; &lt;input name='major'&gt; &lt;/form&gt; </code></pre> <p>Would i need to create my own widget to be able to display those <code>&lt;P&gt;</code> tags, or is there an easier way?</p> <p>Thanks</p>
11
2009-04-07T22:59:06Z
30,424,331
<p>agreed with @mipadi, seems it's the easiest way. </p> <p>So something like </p> <pre><code>$('.selector').append('&lt;html&gt;&lt;/html&gt;') </code></pre>
1
2015-05-24T13:59:26Z
[ "python", "django", "django-forms" ]
Python: Downloading a large file to a local path and setting custom http headers
728,118
<p>I am looking to download a file from a http url to a local file. The file is large enough that I want to download it and save it chunks rather than <code>read()</code> and <code>write()</code> the whole file as a single giant string.</p> <p>The interface of <code>urllib.urlretrieve</code> is essentially what I want. However, I cannot see a way to set request headers when downloading via <code>urllib.urlretrieve</code>, which is something I need to do.</p> <p>If I use <code>urllib2</code>, I can set request headers via its <code>Request</code> object. However, I don't see an API in <code>urllib2</code> to download a file directly to a path on disk like <code>urlretrieve</code>. It seems that instead I will have to use a loop to iterate over the returned data in chunks, writing them to a file myself and checking when we are done.</p> <p>What would be the best way to build a function that works like <code>urllib.urlretrieve</code> but allows request headers to be passed in?</p>
5
2009-04-08T00:44:01Z
728,214
<p>If you want to use urllib and urlretrieve, subclass <code>urllib.URLopener</code> and use its <code>addheader()</code> method to adjust the headers (ie: <code>addheader('Accept', 'sound/basic')</code>, which I'm pulling from the docstring for urllib.addheader).</p> <p>To install your URLopener for use by urllib, see the example in the <a href="http://docs.python.org/library/urllib.html#module-urllib" rel="nofollow">urllib._urlopener</a> section of the docs (note the underscore):</p> <pre><code>import urllib class MyURLopener(urllib.URLopener): pass # your override here, perhaps to __init__ urllib._urlopener = MyURLopener </code></pre> <p>However, you'll be pleased to hear wrt your comment to the question comments, reading an empty string from <code>read()</code> is indeed the signal to stop. This is how urlretrieve handles when to stop, for example. TCP/IP and sockets abstract the reading process, blocking waiting for additional data unless the connection on the other end is EOF and closed, in which case read()ing from connection returns an empty string. An empty string means there is no data trickling in... you don't have to worry about ordered packet re-assembly as that has all been handled for you. If that's your concern for urllib2, I think you can safely use it.</p>
1
2009-04-08T01:46:37Z
[ "python", "http", "download", "urllib2", "urllib" ]
Python: Downloading a large file to a local path and setting custom http headers
728,118
<p>I am looking to download a file from a http url to a local file. The file is large enough that I want to download it and save it chunks rather than <code>read()</code> and <code>write()</code> the whole file as a single giant string.</p> <p>The interface of <code>urllib.urlretrieve</code> is essentially what I want. However, I cannot see a way to set request headers when downloading via <code>urllib.urlretrieve</code>, which is something I need to do.</p> <p>If I use <code>urllib2</code>, I can set request headers via its <code>Request</code> object. However, I don't see an API in <code>urllib2</code> to download a file directly to a path on disk like <code>urlretrieve</code>. It seems that instead I will have to use a loop to iterate over the returned data in chunks, writing them to a file myself and checking when we are done.</p> <p>What would be the best way to build a function that works like <code>urllib.urlretrieve</code> but allows request headers to be passed in?</p>
5
2009-04-08T00:44:01Z
2,028,750
<p>What is the harm in writing your own function using urllib2?</p> <pre><code>import os import sys import urllib2 def urlretrieve(urlfile, fpath): chunk = 4096 f = open(fpath, "w") while 1: data = urlfile.read(chunk) if not data: print "done." break f.write(data) print "Read %s bytes"%len(data) </code></pre> <p>and using request object to set headers</p> <pre><code>request = urllib2.Request("http://www.google.com") request.add_header('User-agent', 'Chrome XXX') urlretrieve(urllib2.urlopen(request), "/tmp/del.html") </code></pre>
2
2010-01-08T15:53:49Z
[ "python", "http", "download", "urllib2", "urllib" ]