title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
12,718,182
<p>PIL already has the option to crop an image</p> <pre><code>img = ImageOps.fit(img, size, Image.ANTIALIAS) </code></pre>
16
2012-10-03T23:11:39Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
16,689,816
<p>My ugly example.</p> <p>Function get file like: "pic[0-9a-z].[extension]", resize them to 120x120, moves section to center and save to "ico[0-9a-z].[extension]", works with portrait and landscape:</p> <pre><code>def imageResize(filepath): from PIL import Image file_dir=os.path.split(filepath) img = Image.open(filepath) if img.size[0] &gt; img.size[1]: aspect = img.size[1]/120 new_size = (img.size[0]/aspect, 120) else: aspect = img.size[0]/120 new_size = (120, img.size[1]/aspect) img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:]) img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:]) if img.size[0] &gt; img.size[1]: new_img = img.crop( ( (((img.size[0])-120)/2), 0, 120+(((img.size[0])-120)/2), 120 ) ) else: new_img = img.crop( ( 0, (((img.size[1])-120)/2), 120, 120+(((img.size[1])-120)/2) ) ) new_img.save(file_dir[0]+'/ico'+file_dir[1][3:]) </code></pre>
1
2013-05-22T10:48:36Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
30,227,474
<p>Based in @tomvon, I finished using the following:</p> <p>Resizing width:</p> <pre><code>new_width = 680 new_height = new_width * height / width </code></pre> <p>Resizing height:</p> <pre><code>new_height = 680 new_width = new_height * width / height </code></pre> <p>Then just:</p> <pre><code>img = img.resize((new_width, new_height), Image.ANTIALIAS) </code></pre>
6
2015-05-14T00:37:06Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
32,806,728
<pre><code>from PIL import Image from resizeimage import resizeimage def resize_file(in_file, out_file, size): with open(in_file) as fd: image = resizeimage.resize_thumbnail(Image.open(fd), size) image.save(out_file) image.close() resize_file('foo.tif', 'foo_small.jpg', (256, 256)) </code></pre> <p>I use this library:</p> <pre><code>pip install python-resize-image </code></pre>
2
2015-09-27T10:02:19Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
How do I resize an image using PIL and maintain its aspect ratio?
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
196
2008-11-07T23:08:04Z
36,036,843
<pre><code>from PIL import Image img = Image.open('/your iamge path/image.jpg') # image extension *.png,*.jpg new_width = 200 new_height = 300 img = img.resize((new_width, new_height), Image.ANTIALIAS) img.save('output image name.png') # format may what u want ,*.png,*jpg,*.gif </code></pre>
2
2016-03-16T13:17:46Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
UTF-8 latin-1 conversion issues, python django
274,361
<p>ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: </p> <pre><code>strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) </code></pre> <p>I get this error: </p> <blockquote> <p>chr() arg not in range(256)</p> </blockquote> <p>If I try to encode the string as latin-1 first I get this error:</p> <blockquote> <p>'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)</p> </blockquote> <p>I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!</p>
3
2008-11-08T04:24:45Z
274,403
<p>Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case.</p> <p>About the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead.</p> <pre><code>&gt;&gt;&gt; a = '\222\222\223\225' &gt;&gt;&gt; u = unicode(a,'latin-1') &gt;&gt;&gt; u u'\x92\x92\x93\x95' &gt;&gt;&gt; print u.encode('utf-8') ÂÂÂÂ &gt;&gt;&gt; print u.encode('utf-16') ÿþ &gt;&gt;&gt; print u.encode('latin-1') &gt;&gt;&gt; for c in u: ... print chr(ord(c) - 3 - 0 -30) ... q q r t &gt;&gt;&gt; for c in u: ... print chr(ord(c) - 3 -200 -30) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; ValueError: chr() arg not in range(256) </code></pre>
4
2008-11-08T05:29:37Z
[ "python", "django", "utf-8", "character-encoding" ]
UTF-8 latin-1 conversion issues, python django
274,361
<p>ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: </p> <pre><code>strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) </code></pre> <p>I get this error: </p> <blockquote> <p>chr() arg not in range(256)</p> </blockquote> <p>If I try to encode the string as latin-1 first I get this error:</p> <blockquote> <p>'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)</p> </blockquote> <p>I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!</p>
3
2008-11-08T04:24:45Z
274,412
<p>Well its because its been encrypted with some terrible scheme that just changes the ord() of the character by some request, so the string coming out of the database has been encrypted and this decrypts it. What you supplied above does not seem to work. In the database it is latin-1, django converts it to unicode, but I cannot pass it to the function as unicode, but when i try and encode it to latin-1 i see that error.</p>
0
2008-11-08T05:42:00Z
[ "python", "django", "utf-8", "character-encoding" ]
UTF-8 latin-1 conversion issues, python django
274,361
<p>ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: </p> <pre><code>strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) </code></pre> <p>I get this error: </p> <blockquote> <p>chr() arg not in range(256)</p> </blockquote> <p>If I try to encode the string as latin-1 first I get this error:</p> <blockquote> <p>'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)</p> </blockquote> <p>I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!</p>
3
2008-11-08T04:24:45Z
274,440
<p>As Vinko notes, Latin-1 or ISO 8859-1 doesn't have printable characters for the octal string you quote. According to my notes for 8859-1, "C1 Controls (0x80 - 0x9F) are from ISO/IEC 6429:1992. It does not define names for 80, 81, or 99". The code point names are as Vinko lists them:</p> <pre><code>\222 = 0x92 =&gt; PRIVATE USE TWO \223 = 0x93 =&gt; SET TRANSMIT STATE \225 = 0x95 =&gt; MESSAGE WAITING </code></pre> <p>The correct UTF-8 encoding of those is (Unicode, binary, hex):</p> <pre><code>U+0092 = %11000010 %10010010 = 0xC2 0x92 U+0093 = %11000010 %10010011 = 0xC2 0x93 U+0095 = %11000010 %10010101 = 0xC2 0x95 </code></pre> <p>The LATIN SMALL LETTER A WITH CIRCUMFLEX is ISO 8859-1 code 0xE2 and hence Unicode U+00E2; in UTF-8, that is %11000011 %10100010 or 0xC3 0xA2.</p> <p>The CENT SIGN is ISO 8859-1 code 0xA2 and hence Unicode U+00A2; in UTF-8, that is %11000011 %10000010 or 0xC3 0x82.</p> <p>So, whatever else you are seeing, you do not seem to be seeing a UTF-8 encoding of ISO 8859-1. All else apart, you are seeing but 5 bytes where you would have to see 8.</p> <p><em>Added</em>: The previous part of the answer addresses the 'UTF-8 encoding' claim, but ignores the rest of the question, which says:</p> <pre><code>Now I need to pass the string into a function that does this operation: strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) I get this error: chr() arg not in range(256). If I try to encode the string as Latin-1 first I get this error: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256). </code></pre> <p>You don't actually show us how intCounter is defined, but if it increments gently per character, sooner or later '<code>ord(c) - 3 - intCounter - 30</code>' is going to be negative (and, by the way, why not combine the constants and use '<code>ord(c) - intCounter - 33</code>'?), at which point, <code>chr()</code> is likely to complain. You would need to add 256 if the value is negative, or use a modulus operation to ensure you have a positive value between 0 and 255 to pass to <code>chr()</code>. Since we can't see how intCounter is incremented, we can't tell if it cycles from 0 to 255 or whether it increases monotonically. If the latter, then you need an expression such as:</p> <pre><code>chr(mod(ord(c) - mod(intCounter, 255) + 479, 255)) </code></pre> <p>where 256 - 33 = 223, of course, and 479 = 256 + 223. This guarantees that the value passed to <code>chr()</code> is positive and in the range 0..255 for any input character c and any value of intCounter (and, because the <code>mod()</code> function never gets a negative argument, it also works regardless of how <code>mod()</code> behaves when its arguments are negative).</p>
2
2008-11-08T06:08:07Z
[ "python", "django", "utf-8", "character-encoding" ]
How to copy a file in Python with a progress bar?
274,493
<p>When copying large files using <code>shutil.copy()</code>, you get no indication of how the operation is progressing..</p> <p>I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of <code>open().read()</code> and <code>.write()</code> to do the actual copying. It displays the progress bar using <code>sys.stdout.write("\r%s\r" % (the_progress_bar))</code> which is a little hackish, but it works.</p> <p>You can see the code (in context) <a href="http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153">on github here</a></p> <p>Is there any built-in module that will do this better? Is there any improvements that can be made to this code?</p>
8
2008-11-08T07:21:53Z
274,497
<p>Two things:</p> <ul> <li>I would make the default block size a <em>lot</em> larger than 512. I would start with 16384 and perhaps more.</li> <li>For modularity, it might be better to have the <code>copy_with_prog</code> function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress.</li> </ul> <p>Perhaps something like this:</p> <pre><code>def copy_with_prog(src, dest, callback = None): while True: # copy loop stuff if callback: callback(pos, total) prog = ProgressBar(...) copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total)) </code></pre>
14
2008-11-08T07:28:43Z
[ "python", "file-io" ]
How to copy a file in Python with a progress bar?
274,493
<p>When copying large files using <code>shutil.copy()</code>, you get no indication of how the operation is progressing..</p> <p>I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of <code>open().read()</code> and <code>.write()</code> to do the actual copying. It displays the progress bar using <code>sys.stdout.write("\r%s\r" % (the_progress_bar))</code> which is a little hackish, but it works.</p> <p>You can see the code (in context) <a href="http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153">on github here</a></p> <p>Is there any built-in module that will do this better? Is there any improvements that can be made to this code?</p>
8
2008-11-08T07:21:53Z
275,945
<p>Overkill? Perhaps. But on almost any system, Linux, Mac, and With a quick wxWidgets install on Windows, you can have the real deal, with pause and cancel buttons in a gui setup. Macs ship with wxWidgets these days, and it's a common package on Linux.</p> <p>A single file is very quick (it will immediately finish and look broken) so you might consider creating a fileSet job that ticks along once per file instead of once per block. Enjoy!</p> <p>-Jim Carroll</p> <pre><code>""" Threaded Jobs. Any class that does a long running process can inherit from ThreadedJob. This enables running as a background thread, progress notification, pause and cancel. The time remaining is also calculated by the ThreadedJob class. """ import wx.lib.newevent import thread import exceptions import time (RunEvent, EVT_RUN) = wx.lib.newevent.NewEvent() (CancelEvent, EVT_CANCEL) = wx.lib.newevent.NewEvent() (DoneEvent, EVT_DONE) = wx.lib.newevent.NewEvent() (ProgressStartEvent, EVT_PROGRESS_START) = wx.lib.newevent.NewEvent() (ProgressEvent, EVT_PROGRESS) = wx.lib.newevent.NewEvent() class InterruptedException(exceptions.Exception): def __init__(self, args = None): self.args = args # # class ThreadedJob: def __init__(self): # tell them ten seconds at first self.secondsRemaining = 10.0 self.lastTick = 0 # not running yet self.isPaused = False self.isRunning = False self.keepGoing = True def Start(self): self.keepGoing = self.isRunning = True thread.start_new_thread(self.Run, ()) self.isPaused = False # def Stop(self): self.keepGoing = False # def WaitUntilStopped(self): while self.isRunning: time.sleep(0.1) wx.SafeYield() # # def IsRunning(self): return self.isRunning # def Run(self): # this is overridden by the # concrete ThreadedJob print "Run was not overloaded" self.JobFinished() pass # def Pause(self): self.isPaused = True pass # def Continue(self): self.isPaused = False pass # def PossibleStoppingPoint(self): if not self.keepGoing: raise InterruptedException("process interrupted.") wx.SafeYield() # allow cancel while paused while self.isPaused: if not self.keepGoing: raise InterruptedException("process interrupted.") # don't hog the CPU time.sleep(0.1) # # def SetProgressMessageWindow(self, win): self.win = win # def JobBeginning(self, totalTicks): self.lastIterationTime = time.time() self.totalTicks = totalTicks if hasattr(self, "win") and self.win: wx.PostEvent(self.win, ProgressStartEvent(total=totalTicks)) # # def JobProgress(self, currentTick): dt = time.time() - self.lastIterationTime self.lastIterationTime = time.time() dtick = currentTick - self.lastTick self.lastTick = currentTick alpha = 0.92 if currentTick &gt; 1: self.secondsPerTick = dt * (1.0 - alpha) + (self.secondsPerTick * alpha) else: self.secondsPerTick = dt # if dtick &gt; 0: self.secondsPerTick /= dtick self.secondsRemaining = self.secondsPerTick * (self.totalTicks - 1 - currentTick) + 1 if hasattr(self, "win") and self.win: wx.PostEvent(self.win, ProgressEvent(count=currentTick)) # # def SecondsRemaining(self): return self.secondsRemaining # def TimeRemaining(self): if 1: #self.secondsRemaining &gt; 3: minutes = self.secondsRemaining // 60 seconds = int(self.secondsRemaining % 60.0) return "%i:%02i" % (minutes, seconds) else: return "a few" # def JobFinished(self): if hasattr(self, "win") and self.win: wx.PostEvent(self.win, DoneEvent()) # # flag we're done before we post the all done message self.isRunning = False # # class EggTimerJob(ThreadedJob): """ A sample Job that demonstrates the mechanisms and features of the Threaded Job""" def __init__(self, duration): self.duration = duration ThreadedJob.__init__(self) # def Run(self): """ This can either be run directly for synchronous use of the job, or started as a thread when ThreadedJob.Start() is called. It is responsible for calling JobBeginning, JobProgress, and JobFinished. And as often as possible, calling PossibleStoppingPoint() which will sleep if the user pauses, and raise an exception if the user cancels. """ self.time0 = time.clock() self.JobBeginning(self.duration) try: for count in range(0, self.duration): time.sleep(1.0) self.JobProgress(count) self.PossibleStoppingPoint() # except InterruptedException: # clean up if user stops the Job early print "canceled prematurely!" # # always signal the end of the job self.JobFinished() # # def __str__(self): """ The job progress dialog expects the job to describe its current state.""" response = [] if self.isPaused: response.append("Paused Counting") elif not self.isRunning: response.append("Will Count the seconds") else: response.append("Counting") # return " ".join(response) # # class FileCopyJob(ThreadedJob): """ A common file copy Job. """ def __init__(self, orig_filename, copy_filename, block_size=32*1024): self.src = orig_filename self.dest = copy_filename self.block_size = block_size ThreadedJob.__init__(self) # def Run(self): """ This can either be run directly for synchronous use of the job, or started as a thread when ThreadedJob.Start() is called. It is responsible for calling JobBeginning, JobProgress, and JobFinished. And as often as possible, calling PossibleStoppingPoint() which will sleep if the user pauses, and raise an exception if the user cancels. """ self.time0 = time.clock() try: source = open(self.src, 'rb') # how many blocks? import os (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime) = os.stat(self.src) num_blocks = st_size / self.block_size current_block = 0 self.JobBeginning(num_blocks) dest = open(self.dest, 'wb') while 1: copy_buffer = source.read(self.block_size) if copy_buffer: dest.write(copy_buffer) current_block += 1 self.JobProgress(current_block) self.PossibleStoppingPoint() else: break source.close() dest.close() except InterruptedException: # clean up if user stops the Job early dest.close() # unlink / delete the file that is partially copied os.unlink(self.dest) print "canceled, dest deleted!" # # always signal the end of the job self.JobFinished() # # def __str__(self): """ The job progress dialog expects the job to describe its current state.""" response = [] if self.isPaused: response.append("Paused Copy") elif not self.isRunning: response.append("Will Copy a file") else: response.append("Copying") # return " ".join(response) # # class JobProgress(wx.Dialog): """ This dialog shows the progress of any ThreadedJob. It can be shown Modally if the main application needs to suspend operation, or it can be shown Modelessly for background progress reporting. app = wx.PySimpleApp() job = EggTimerJob(duration = 10) dlg = JobProgress(None, job) job.SetProgressMessageWindow(dlg) job.Start() dlg.ShowModal() """ def __init__(self, parent, job): self.job = job wx.Dialog.__init__(self, parent, -1, "Progress", size=(350,200)) # vertical box sizer sizeAll = wx.BoxSizer(wx.VERTICAL) # Job status text self.JobStatusText = wx.StaticText(self, -1, "Starting...") sizeAll.Add(self.JobStatusText, 0, wx.EXPAND|wx.ALL, 8) # wxGague self.ProgressBar = wx.Gauge(self, -1, 10, wx.DefaultPosition, (250, 15)) sizeAll.Add(self.ProgressBar, 0, wx.EXPAND|wx.ALL, 8) # horiz box sizer, and spacer to right-justify sizeRemaining = wx.BoxSizer(wx.HORIZONTAL) sizeRemaining.Add((2,2), 1, wx.EXPAND) # time remaining read-only edit # putting wide default text gets a reasonable initial layout. self.remainingText = wx.StaticText(self, -1, "???:??") sizeRemaining.Add(self.remainingText, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 8) # static text: remaining self.remainingLabel = wx.StaticText(self, -1, "remaining") sizeRemaining.Add(self.remainingLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 8) # add that row to the mix sizeAll.Add(sizeRemaining, 1, wx.EXPAND) # horiz box sizer &amp; spacer sizeButtons = wx.BoxSizer(wx.HORIZONTAL) sizeButtons.Add((2,2), 1, wx.EXPAND|wx.ADJUST_MINSIZE) # Pause Button self.PauseButton = wx.Button(self, -1, "Pause") sizeButtons.Add(self.PauseButton, 0, wx.ALL, 4) self.Bind(wx.EVT_BUTTON, self.OnPauseButton, self.PauseButton) # Cancel button self.CancelButton = wx.Button(self, wx.ID_CANCEL, "Cancel") sizeButtons.Add(self.CancelButton, 0, wx.ALL, 4) self.Bind(wx.EVT_BUTTON, self.OnCancel, self.CancelButton) # Add all the buttons on the bottom row to the dialog sizeAll.Add(sizeButtons, 0, wx.EXPAND|wx.ALL, 4) self.SetSizer(sizeAll) #sizeAll.Fit(self) sizeAll.SetSizeHints(self) # jobs tell us how they are doing self.Bind(EVT_PROGRESS_START, self.OnProgressStart) self.Bind(EVT_PROGRESS, self.OnProgress) self.Bind(EVT_DONE, self.OnDone) self.Layout() # def OnPauseButton(self, event): if self.job.isPaused: self.job.Continue() self.PauseButton.SetLabel("Pause") self.Layout() else: self.job.Pause() self.PauseButton.SetLabel("Resume") self.Layout() # # def OnCancel(self, event): self.job.Stop() # def OnProgressStart(self, event): self.ProgressBar.SetRange(event.total) self.statusUpdateTime = time.clock() # def OnProgress(self, event): # update the progress bar self.ProgressBar.SetValue(event.count) self.remainingText.SetLabel(self.job.TimeRemaining()) # update the text a max of 20 times a second if time.clock() - self.statusUpdateTime &gt; 0.05: self.JobStatusText.SetLabel(str(self.job)) self.statusUpdateTime = time.clock() self.Layout() # # # when a job is done def OnDone(self, event): self.ProgressBar.SetValue(0) self.JobStatusText.SetLabel("Finished") self.Destroy() # # if __name__ == "__main__": app = wx.PySimpleApp() #job = EggTimerJob(duration = 10) job = FileCopyJob("VeryBigFile.mp4", "/tmp/test_junk.mp4", 1024*1024*10) dlg = JobProgress(None, job) job.SetProgressMessageWindow(dlg) job.Start() dlg.ShowModal() # </code></pre>
5
2008-11-09T14:08:26Z
[ "python", "file-io" ]
How to copy a file in Python with a progress bar?
274,493
<p>When copying large files using <code>shutil.copy()</code>, you get no indication of how the operation is progressing..</p> <p>I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of <code>open().read()</code> and <code>.write()</code> to do the actual copying. It displays the progress bar using <code>sys.stdout.write("\r%s\r" % (the_progress_bar))</code> which is a little hackish, but it works.</p> <p>You can see the code (in context) <a href="http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153">on github here</a></p> <p>Is there any built-in module that will do this better? Is there any improvements that can be made to this code?</p>
8
2008-11-08T07:21:53Z
24,737,210
<p>If you want to use the Windows copy dialog with progress you can use these:</p> <ul> <li><a href="https://github.com/tjguk/winshell/" rel="nofollow">https://github.com/tjguk/winshell/</a></li> <li><a href="https://github.com/frmdstryr/pywinutils" rel="nofollow">https://github.com/frmdstryr/pywinutils</a></li> </ul>
1
2014-07-14T13:05:40Z
[ "python", "file-io" ]
config_vars.mk missing in default xampp-linux installation
274,638
<p>I extracted the xampp package xampp-linux-1.6.7 on a Ubuntu 8.10 system and followed the instuctions from mod_wsgi documentation. I get the error below:</p> <pre><code>ravi@Ibex:~/mod_wsgi-2.3$ ./configure --with-apxs=/opt/lampp/bin/apxs checking Apache version... cannot open /opt/lampp/build/config_vars.mk: No such file or directory at /opt/lampp/bin/apxs line 218. cannot open /opt/lampp/build/config_vars.mk: No such file or directory at /opt/lampp/bin/apxs line 218. ./configure: line 1696: /: is a directory checking for python... /usr/bin/python cannot open /opt/lampp/build/config_vars.mk: No such file or directory at /opt/lampp/bin/apxs line 218. configure: creating ./config.status config.status: error: cannot find input file: Makefile.in </code></pre> <p>I could not google for instructions on getting mod_wsgi running on xampp. Please help.</p> <p>Solution: The solution for this is buried in the comments. Thanks to <a href="http://stackoverflow.com/users/33006/martin-v-l246wis">Martin v. Löwis</a> I was able to solve this. When apxs throws and error complaining about missing config_vars.mk it means that the build directory of Apache is missing. Fox xampp users the solution is to download xampp-dev as well and extract that to the same path.</p>
3
2008-11-08T11:31:32Z
7,552,280
<p>When apxs throws and error complaining about missing config_vars.mk it means that the build directory of Apache is missing. Fox xampp users the solution is to download xampp-dev as well and extract that to the same path.</p>
1
2011-09-26T08:10:54Z
[ "python", "apache", "xampp", "mod-wsgi" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
275,025
<p>Try the <a href="http://docs.python.org/2/library/stdtypes.html#str.rstrip">rstrip</a> method.</p> <pre><code>&gt;&gt;&gt; 'test string\n'.rstrip() 'test string' </code></pre> <p>Note that Python's rstrip method strips <em>all</em> kinds of trailing whitespace by default, not just one newline as Perl does with chomp. To strip only newlines:</p> <pre><code>&gt;&gt;&gt; 'test string \n\n'.rstrip('\n') 'test string ' </code></pre> <p>There is also the <code>lstrip</code> and <code>strip</code> methods.</p> <pre><code>&gt;&gt;&gt; s = " \n abc def " &gt;&gt;&gt; s.strip() 'abc def' &gt;&gt;&gt; s.rstrip() ' \n abc def' &gt;&gt;&gt; s.lstrip() 'abc def ' &gt;&gt;&gt; </code></pre>
963
2008-11-08T18:31:53Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
275,401
<p>The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \r or \n. Here are examples for Mac, Windows, and Unix EOL characters.</p> <pre><code>&gt;&gt;&gt; 'Mac EOL\r'.rstrip('\r\n') 'Mac EOL' &gt;&gt;&gt; 'Windows EOL\r\n'.rstrip('\r\n') 'Windows EOL' &gt;&gt;&gt; 'Unix EOL\n'.rstrip('\r\n') 'Unix EOL' </code></pre> <p>Using '\r\n' as the parameter to rstrip means that it will strip out any trailing combination of '\r' or '\n'. That's why it works in all three cases above.</p> <p>This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing '\r' as its EOL character. The Windows machine on which I was using this message had appended its own '\r\n' EOL character. Therefore, the end of each line looked like '\r\r\n'. Using rstrip('\r\n') would have taken off the entire '\r\r\n' which is not what I wanted. In that case, I simply sliced off the last two characters instead.</p> <p>Note that unlike Perl's <code>chomp</code> function, this will strip all specified characters at the end of the string, not just one:</p> <pre><code>&gt;&gt;&gt; "Hello\n\n\n".rstrip("\n") "Hello" </code></pre>
100
2008-11-09T00:11:21Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
275,659
<p>And I would say the "pythonic" way to get lines without trailing newline characters is splitlines().</p> <pre><code>&gt;&gt;&gt; text = "line 1\nline 2\r\nline 3\nline 4" &gt;&gt;&gt; text.splitlines() ['line 1', 'line 2', 'line 3', 'line 4'] </code></pre>
113
2008-11-09T05:52:43Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
326,279
<p>Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:</p> <pre><code>$x="a\n"; chomp $x </code></pre> <p>results in <code>$x</code> being <code>"a"</code>.</p> <p>but in Python:</p> <pre><code>x="a\n" x.rstrip() </code></pre> <p>will mean that the value of <code>x</code> is <strong>still</strong> <code>"a\n"</code>. Even <code>x=x.rstrip()</code> doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.</p>
86
2008-11-28T17:31:34Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
1,077,495
<p>I don't program in Python, but I came across an <a href="http://www.python.org/doc/faq/programming/#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" rel="nofollow">FAQ</a> at python.org advocating S.rstrip("\r\n") for python 2.2 or later.</p>
12
2009-07-03T01:49:19Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
2,396,894
<p>I might use something like this:</p> <pre><code>import os s = s.rstrip(os.linesep) </code></pre> <p>I think the problem with <code>rstrip("\n")</code> is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use <code>"\r\n"</code>). The other gotcha is that <code>rstrip</code> will strip out repeated whitespace. Hopefully <code>os.linesep</code> will contain the right characters. the above works for me.</p>
39
2010-03-07T16:07:27Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
5,764,202
<p>rstrip doesn't do the same thing as chomp, on so many levels. Read <a href="http://perldoc.perl.org/functions/chomp.html">http://perldoc.perl.org/functions/chomp.html</a> and see that chomp is very complex indeed.</p> <p>However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.</p> <p>Here you can see rstrip removing all the newlines:</p> <pre><code>&gt;&gt;&gt; 'foo\n\n'.rstrip(os.linesep) 'foo' </code></pre> <p>A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:</p> <pre><code>&gt;&gt;&gt; re.sub(os.linesep + r'\Z','','foo\n\n') 'foo\n' </code></pre>
14
2011-04-23T12:42:25Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
5,803,510
<p>Careful with <code>"foo".rstrip(os.linesep)</code>: That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:</p> <pre><code>$ python Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) [GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os, sys &gt;&gt;&gt; sys.platform 'linux2' &gt;&gt;&gt; "foo\r\n".rstrip(os.linesep) 'foo\r' &gt;&gt;&gt; </code></pre> <p>Use <code>"foo".rstrip("\r\n")</code> instead, as Mike says above.</p>
17
2011-04-27T11:43:20Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
8,327,143
<p>workaround solution for special case:</p> <p>if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows: </p> <pre><code>foobar= foobar[:-1] </code></pre> <p>to slice out your newline character. </p>
7
2011-11-30T14:04:19Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
9,507,807
<pre><code>"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '') &gt;&gt;&gt; 'line 1line 2...' </code></pre> <p>or you could always get geekier with regexps :)</p> <p>have fun!</p>
15
2012-02-29T22:40:11Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
16,527,062
<p>You may use <code>line = line.rstrip('\n')</code>. This will strip all newlines from the end of the string, not just one.</p>
35
2013-05-13T16:41:22Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
19,317,570
<p>If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter '\n' and then join this list into a new str(newstr).</p> <p><code>newstr = "".join(oldstr.split('\n'))</code> </p>
6
2013-10-11T11:56:21Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
19,531,239
<p>An <a href="http://docs.python.org/2/library/stdtypes.html#file.next" rel="nofollow">example in Python's documentation</a> simply uses <code>line.strip()</code>.</p> <p>Perl's <code>chomp</code> function removes one linebreak sequence from the end of a string only if it's actually there.</p> <p>Here is how I plan to do that in Python, if <code>process</code> is conceptually the function that I need in order to do something useful to each line from this file:</p> <pre><code>import os sep_pos = -len(os.linesep) with open("file.txt") as f: for line in f: if line[sep_pos:] == os.linesep: line = line[:sep_pos] process(line) </code></pre>
16
2013-10-23T01:32:11Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
21,242,117
<pre><code>import re r_unwanted = re.compile("[\n\t\r]") r_unwanted.sub("", your_text) </code></pre>
8
2014-01-20T19:07:03Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
26,554,128
<p>A catch all:</p> <pre><code>line = line.rstrip('\r|\n') </code></pre>
2
2014-10-24T18:34:12Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
27,054,136
<p>you can use strip:</p> <pre><code>line = line.strip() </code></pre> <p>demo:</p> <pre><code>&gt;&gt;&gt; "\n\n hello world \n\n".strip() 'hello world' </code></pre>
15
2014-11-21T04:29:07Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
27,890,752
<p>I find it convenient to have be able to get the chomped lines via in iterator, parallel to the way you can get the un-chomped lines from a file object. You can do so with the following code:</p> <pre><code>def chomped_lines(iter): for line in iter: yield line.rstrip("\r\n") </code></pre> <p>Sample usage:</p> <pre><code>with open("file.txt") as infile: for line in chomped_lines(infile): process(line) </code></pre>
1
2015-01-11T18:47:33Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
28,937,424
<pre><code>s = s.rstrip() </code></pre> <p>will remove all newlines at the end of the string <code>s</code>. The assignment is needed because <code>rstrip</code> returns a new string instead of modifying the original string. </p>
25
2015-03-09T08:02:55Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
32,882,948
<p>This would replicate exactly perl's chomp (minus behavior on arrays) for "\n" line terminator:</p> <pre><code>def chomp(x): if x.endswith("\r\n"): return x[:-2] if x.endswith("\n"): return x[:-1] return x[:] </code></pre> <p>(Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \r\n in account)</p>
4
2015-10-01T08:33:32Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
33,392,998
<p>If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:</p> <pre><code>import time loops = 50000000 def method1(loops=loops): test_string = 'num\n' t0 = time.time() for num in xrange(loops): out_sting = test_string[:-1] t1 = time.time() print('Method 1: ' + str(t1 - t0)) def method2(loops=loops): test_string = 'num\n' t0 = time.time() for num in xrange(loops): out_sting = test_string.rstrip() t1 = time.time() print('Method 2: ' + str(t1 - t0)) method1() method2() </code></pre> <p>Output:</p> <pre><code>Method 1: 3.92700004578 Method 2: 6.73000001907 </code></pre>
1
2015-10-28T13:56:42Z
[ "python", "newline" ]
How can I remove (chomp) a newline in Python?
275,018
<p>What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?</p>
959
2008-11-08T18:25:24Z
37,346,773
<p>Just use : </p> <pre><code>line = line.rstrip("\n") </code></pre> <p>or</p> <pre><code>line = line.strip("\n") </code></pre> <p>You don't need any of this complicated stuff</p>
2
2016-05-20T12:29:21Z
[ "python", "newline" ]
What is the regular expression for /urlchecker/http://www.google.com
275,109
<p>I'm writing a url rewrite in django that when a person goes to <a href="http://mysite.com/urlchecker/http://www.google.com" rel="nofollow">http://mysite.com/urlchecker/http://www.google.com</a> it sends the url: <a href="http://ww.google.com" rel="nofollow">http://ww.google.com</a> to a view as a string variable. </p> <p>I tried doing:</p> <pre><code>(r'^urlchecker/(?P&lt;url&gt;\w+)/$', 'mysite.main.views.urlchecker'), </code></pre> <p>But that didn't work. Anyone know what I'm doing wrong?</p> <p>Also, generally is there a good resource to learn regular expressions specifically for python/django?</p> <p>Thanks guys!</p>
1
2008-11-08T20:01:02Z
275,117
<p>Try this instead:</p> <p><code>(r'^urlchecker/(?P&lt;url&gt;.+)$', 'mysite.main.views.urlchecker'),</code></p> <p>This differs from yours in that:</p> <ul> <li>It will take anything after 'urlcheck/', not just "word" characters.</li> <li>It does not force the url to end in a slash.</li> </ul>
2
2008-11-08T20:06:29Z
[ "python", "regex", "django" ]
What is the regular expression for /urlchecker/http://www.google.com
275,109
<p>I'm writing a url rewrite in django that when a person goes to <a href="http://mysite.com/urlchecker/http://www.google.com" rel="nofollow">http://mysite.com/urlchecker/http://www.google.com</a> it sends the url: <a href="http://ww.google.com" rel="nofollow">http://ww.google.com</a> to a view as a string variable. </p> <p>I tried doing:</p> <pre><code>(r'^urlchecker/(?P&lt;url&gt;\w+)/$', 'mysite.main.views.urlchecker'), </code></pre> <p>But that didn't work. Anyone know what I'm doing wrong?</p> <p>Also, generally is there a good resource to learn regular expressions specifically for python/django?</p> <p>Thanks guys!</p>
1
2008-11-08T20:01:02Z
275,281
<p>I just learned something while grazing the Hidden Features of Python thread. <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python#143636">Python's re compiler has a debug mode</a>! (Who knew? Well, apparently someone did :-) Anyway, it's worth a read.</p>
0
2008-11-08T22:07:07Z
[ "python", "regex", "django" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
275,195
<p>I found this in the Cheetah source code (<a href="http://www.koders.com/python/fid549827F97513858275EEA43DC0135AC97AEAEF57.aspx" rel="nofollow">here</a>)</p> <pre><code>htmlCodes = [ ['&amp;', '&amp;amp;'], ['&lt;', '&amp;lt;'], ['&gt;', '&amp;gt;'], ['"', '&amp;quot;'], ] htmlCodesReversed = htmlCodes[:] htmlCodesReversed.reverse() def htmlDecode(s, codes=htmlCodesReversed): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like &lt;p&gt;. It is the inverse of htmlEncode().""" for code in codes: s = s.replace(code[1], code[0]) return s </code></pre> <p>not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)</p> <p>i noticed your title asked for encode too, so here is Cheetah's encode function.</p> <pre><code>def htmlEncode(s, codes=htmlCodes): """ Returns the HTML encoded version of the given string. This is useful to display a plain ASCII text string on a web page.""" for code in codes: s = s.replace(code[0], code[1]) return s </code></pre>
1
2008-11-08T20:58:52Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
275,246
<p>Given the Django use case, there are two answers to this. Here is its <code>django.utils.html.escape</code> function, for reference:</p> <pre><code>def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return mark_safe(force_unicode(html).replace('&amp;', '&amp;amp;').replace('&lt;', '&amp;l t;').replace('&gt;', '&amp;gt;').replace('"', '&amp;quot;').replace("'", '&amp;#39;')) </code></pre> <p>To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:</p> <pre><code>def html_decode(s): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like &lt;p&gt;. """ htmlCodes = ( ("'", '&amp;#39;'), ('"', '&amp;quot;'), ('&gt;', '&amp;gt;'), ('&lt;', '&amp;lt;'), ('&amp;', '&amp;amp;') ) for code in htmlCodes: s = s.replace(code[1], code[0]) return s unescaped = html_decode(my_string) </code></pre> <p>This, however, is not a general solution; it is only appropriate for strings encoded with <code>django.utils.html.escape</code>. More generally, it is a good idea to stick with the standard library:</p> <pre><code># Python 2.x: import HTMLParser html_parser = HTMLParser.HTMLParser() unescaped = html_parser.unescape(my_string) # Python 3.x: import html.parser html_parser = html.parser.HTMLParser() unescaped = html_parser.unescape(my_string) </code></pre> <p>As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.</p> <p>With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:</p> <pre><code>{{ context_var|safe }} {% autoescape off %} {{ context_var }} {% endautoescape %} </code></pre>
89
2008-11-08T21:40:37Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
275,463
<p>Use daniel's solution if the set of encoded characters is relatively restricted. Otherwise, use one of the numerous HTML-parsing libraries.</p> <p>I like BeautifulSoup because it can handle malformed XML/HTML :</p> <p><a href="http://www.crummy.com/software/BeautifulSoup/">http://www.crummy.com/software/BeautifulSoup/</a></p> <p>for your question, there's an example in their <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html">documentation</a> </p> <pre><code>from BeautifulSoup import BeautifulStoneSoup BeautifulStoneSoup("Sacr&amp;eacute; bl&amp;#101;u!", convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0] # u'Sacr\xe9 bleu!' </code></pre>
20
2008-11-09T01:15:21Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
312,538
<p>See at the bottom of this <a href="http://wiki.python.org/moin/EscapingHtml">page at Python wiki</a>, there are at least 2 options to "unescape" html.</p>
8
2008-11-23T13:50:40Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
449,169
<p>For html encoding, there's <strong>cgi.escape</strong> from the standard library:</p> <pre><code>&gt;&gt; help(cgi.escape) cgi.escape = escape(s, quote=None) Replace special characters "&amp;", "&lt;" and "&gt;" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. </code></pre> <p>For html decoding, I use the following:</p> <pre><code>import re from htmlentitydefs import name2codepoint # for some reason, python 2.5.2 doesn't have this one (apostrophe) name2codepoint['#39'] = 39 def unescape(s): "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml" return re.sub('&amp;(%s);' % '|'.join(name2codepoint), lambda m: unichr(name2codepoint[m.group(1)]), s) </code></pre> <p>For anything more complicated, I use BeautifulSoup.</p>
75
2009-01-16T01:12:53Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
1,619,286
<p>Daniel's comment as an answer:</p> <p>"escaping only occurs in Django during template rendering. Therefore, there's no need for an unescape - you just tell the templating engine not to escape. either {{ context_var|safe }} or {% autoescape off %}{{ context_var }}{% endautoescape %}"</p>
6
2009-10-24T22:04:16Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
3,271,650
<p>I found a fine function at: <a href="http://snippets.dzone.com/posts/show/4569">http://snippets.dzone.com/posts/show/4569</a></p> <pre><code>def decodeHtmlentities(string): import re entity_re = re.compile("&amp;(#?)(\d{1,5}|\w{1,8});") def substitute_entity(match): from htmlentitydefs import name2codepoint as n2cp ent = match.group(2) if match.group(1) == "#": return unichr(int(ent)) else: cp = n2cp.get(ent) if cp: return unichr(cp) else: return match.group() return entity_re.subn(substitute_entity, string)[0] </code></pre>
5
2010-07-17T13:27:49Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
7,088,472
<p>With the standard library:</p> <ul> <li><p>HTML Escape</p> <pre><code>try: from html import escape # python 3.x except ImportError: from cgi import escape # python 2.x print(escape("&lt;")) </code></pre></li> <li><p>HTML Unescape</p> <pre><code>try: from html import unescape # python 3.4+ except ImportError: try: from html.parser import HTMLParser # python 3.x (&lt;3.4) except ImportError: from HTMLParser import HTMLParser # python 2.x unescape = HTMLParser().unescape print(unescape("&amp;gt;")) </code></pre></li> </ul>
70
2011-08-17T05:51:23Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
8,524,552
<p>Below is a python function that uses module <code>htmlentitydefs</code>. It is not perfect. The version of <code>htmlentitydefs</code> that I have is incomplete and it assumes that all entities decode to one codepoint which is wrong for entities like <code>&amp;NotEqualTilde;</code>:</p> <p><a href="http://www.w3.org/TR/html5/named-character-references.html" rel="nofollow">http://www.w3.org/TR/html5/named-character-references.html</a></p> <blockquote> <pre><code>NotEqualTilde; U+02242 U+00338 ≂̸ </code></pre> </blockquote> <p>With those caveats though, here's the code.</p> <pre><code>def decodeHtmlText(html): """ Given a string of HTML that would parse to a single text node, return the text value of that node. """ # Fast path for common case. if html.find("&amp;") &lt; 0: return html return re.sub( '&amp;(?:#(?:x([0-9A-Fa-f]+)|([0-9]+))|([a-zA-Z0-9]+));', _decode_html_entity, html) def _decode_html_entity(match): """ Regex replacer that expects hex digits in group 1, or decimal digits in group 2, or a named entity in group 3. """ hex_digits = match.group(1) # '&amp;#10;' -&gt; unichr(10) if hex_digits: return unichr(int(hex_digits, 16)) decimal_digits = match.group(2) # '&amp;#x10;' -&gt; unichr(0x10) if decimal_digits: return unichr(int(decimal_digits, 10)) name = match.group(3) # name is 'lt' when '&amp;lt;' was matched. if name: decoding = (htmlentitydefs.name2codepoint.get(name) # Treat &amp;GT; like &amp;gt;. # This is wrong for &amp;Gt; and &amp;Lt; which HTML5 adopted from MathML. # If htmlentitydefs included mappings for those entities, # then this code will magically work. or htmlentitydefs.name2codepoint.get(name.lower())) if decoding is not None: return unichr(decoding) return match.group(0) # Treat "&amp;noSuchEntity;" as "&amp;noSuchEntity;" </code></pre>
0
2011-12-15T18:01:24Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
8,593,583
<p>If anyone is looking for a simple way to do this via the django templates, you can always use filters like this:</p> <pre><code>&lt;html&gt; {{ node.description|safe }} &lt;/html&gt; </code></pre> <p>I had some data coming from a vendor and everything I posted had html tags actually written on the rendered page as if you were looking at the source. The above code helped me greatly. Hope this helps others.</p> <p>Cheers!!</p>
3
2011-12-21T17:08:31Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
9,468,081
<p>You can also use django.utils.html.escape</p> <pre><code>from django.utils.html import escape something_nice = escape(request.POST['something_naughty']) </code></pre>
1
2012-02-27T16:01:44Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
11,273,187
<p>This is the easiest solution for this problem - </p> <pre><code>{% autoescape on %} {{ body }} {% endautoescape %} </code></pre> <p>From <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="nofollow">this page</a>.</p>
0
2012-06-30T09:56:10Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
28,268,163
<p>Even though this is a really old question, this may work.</p> <p>Django 1.5.5</p> <pre><code>In [1]: from django.utils.text import unescape_entities In [2]: unescape_entities('&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt;') Out[2]: u'&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt;' </code></pre>
0
2015-02-01T21:31:08Z
[ "python", "django", "html-encode" ]
How do I perform HTML decoding/encoding using Python/Django?
275,174
<p>I have a string that is html encoded: </p> <pre><code>&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot; style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot; src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot; alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt; </code></pre> <p>I want to change that to:</p> <pre><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>I've found how to do this in C# but not in in Python. Can someone help me out?</p> <p>Thanks.</p> <p>Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format.</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
91
2008-11-08T20:44:30Z
31,282,266
<p>In Python 3.4+:</p> <pre><code>import html html.unescape(your_string) </code></pre>
4
2015-07-08T01:54:02Z
[ "python", "django", "html-encode" ]
Python ctypes and function calls
275,207
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p> <p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p> <pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) </code></pre> <p>Now, why does this script keeps doing segmentation fault whenever I run it?</p> <p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p> <p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
7
2008-11-08T21:11:25Z
275,300
<p>Does python even allow such usage? I should learn it then...</p> <p>I think the interpreter doesn't expect any register to be changed. Try saving the registers that you use inside the function if you plan to use your assembler output like this.</p> <p>Btw, call convention of x86_64 is different than regular x86. You may have trouble if you lose stack pointer alignment and mix external objects generated with other tools.</p>
0
2008-11-08T22:21:43Z
[ "python", "c", "assembly", "ctypes", "x86-64" ]
Python ctypes and function calls
275,207
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p> <p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p> <pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) </code></pre> <p>Now, why does this script keeps doing segmentation fault whenever I run it?</p> <p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p> <p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
7
2008-11-08T21:11:25Z
275,333
<p>I think you can't freely execute any allocated memory without first setting it as executable. I never tried myself, but you might want to check the unix function <code>mprotect</code>:</p> <p><a href="http://linux.about.com/library/cmd/blcmdl2_mprotect.htm" rel="nofollow">http://linux.about.com/library/cmd/blcmdl2_mprotect.htm</a></p> <p><code>VirtualProtect</code> seems to do the same thing on windows :</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa366898" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa366898</a>(VS.85).aspx</p>
4
2008-11-08T22:51:24Z
[ "python", "c", "assembly", "ctypes", "x86-64" ]
Python ctypes and function calls
275,207
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p> <p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p> <pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) </code></pre> <p>Now, why does this script keeps doing segmentation fault whenever I run it?</p> <p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p> <p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
7
2008-11-08T21:11:25Z
275,426
<p>Done some research with my friend and found out this is a platform-specific issue. We suspect that on some platforms malloc mmaps memory without PROT_EXEC and on others it does.</p> <p>Therefore it is necessary to change the protection level with mprotect afterwards.</p> <p>Lame thing, took a while to find out what to do.</p> <pre><code>from ctypes import ( cast, CFUNCTYPE, c_long, sizeof, addressof, create_string_buffer, pythonapi ) PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC = 0, 1, 2, 4 mprotect = pythonapi.mprotect buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) pagesize = pythonapi.getpagesize() cbuffer = create_string_buffer(buffer)#c_char_p(buffer) addr = addressof(cbuffer) size = sizeof(cbuffer) mask = pagesize - 1 if mprotect(~mask&amp;addr, mask&amp;addr + size, PROT_READ|PROT_WRITE|PROT_EXEC) &lt; 0: print "mprotect failed?" else: fptr = cast(cbuffer, CFUNCTYPE(c_long, c_long)) print repr(fptr(1234)) </code></pre>
6
2008-11-09T00:29:39Z
[ "python", "c", "assembly", "ctypes", "x86-64" ]
Python ctypes and function calls
275,207
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p> <p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p> <pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) </code></pre> <p>Now, why does this script keeps doing segmentation fault whenever I run it?</p> <p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p> <p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
7
2008-11-08T21:11:25Z
275,460
<p>As <a href="http://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333">vincent</a> mentioned, this is due to the allocated page being marked as non executable. Newer processors support this <a href="http://en.wikipedia.org/wiki/NX_bit">functionality</a>, and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory.</p> <p>To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below:</p> <pre><code>libc = CDLL('libc.so') # Some constants PROT_READ = 1 PROT_WRITE = 2 PROT_EXEC = 4 def executable_code(buffer): """Return a pointer to a page-aligned executable buffer filled in with the data of the string provided. The pointer should be freed with libc.free() when finished""" buf = c_char_p(buffer) size = len(buffer) # Need to align to a page boundary, so use valloc addr = libc.valloc(size) addr = c_void_p(addr) if 0 == addr: raise Exception("Failed to allocate memory") memmove(addr, buf, size) if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC): raise Exception("Failed to set protection on buffer") return addr code_ptr = executable_code(buffer) fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long)) print fptr(1234) libc.free(code_ptr) </code></pre> <p>Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit. </p> <p>Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).</p>
7
2008-11-09T01:06:14Z
[ "python", "c", "assembly", "ctypes", "x86-64" ]
Python ctypes and function calls
275,207
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p> <p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p> <pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) </code></pre> <p>Now, why does this script keeps doing segmentation fault whenever I run it?</p> <p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p> <p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
7
2008-11-08T21:11:25Z
1,812,514
<p>There's simpler approach I've figured only but recently that doesn't involve mprotect. Plainly mmap the executable space for program directly. These days python has a module for doing exactly this, though I didn't find way to get the address of the code. In short you'd allocate memory calling mmap instead of using string buffers and setting the execution flag indirectly. This is easier and safer, you can be sure only your code can be executed now.</p>
0
2009-11-28T13:22:43Z
[ "python", "c", "assembly", "ctypes", "x86-64" ]
information seemingly coming out of mysqldb incorrectly, python django
275,541
<p>In a latin-1 database i have '<code>\222\222\223\225</code>', when I try to pull this field from the django models I get back <code>u'\u2019\u2019\u201c\u2022'</code>.</p> <pre><code>from django.db import connection (Pdb) cursor = connection.cursor() (Pdb) cursor.execute("SELECT Password from campaignusers WHERE UserID=26") (Pdb) row = cursor.fetchone() </code></pre> <p>So I step into that and get into </p> <blockquote> <p>/usr/local/python2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py(327)fetchone()->(u'\u2019...1c\u2022',) </p> </blockquote> <p>I can't step further into this because its an egg but it seems that the MySQL python driver is interpreting the data not as latin-1.</p> <p>Anyone have any clue whats going on?</p>
0
2008-11-09T03:06:06Z
276,108
<p>A little browsing of already-asked questions would have led you to <a href="http://stackoverflow.com/questions/274361/utf-8-latin-1-conversion-issues-python-django">UTF-8 latin-1 conversion issues</a>, which was asked and answered yesterday.</p> <p>BTW, I couldn't remember the exact title, so I just googled on django+'\222\222\223\225' and found it. Remember, kids, Google Is Your Friend (tm).</p>
1
2008-11-09T16:54:16Z
[ "python", "mysql", "django", "character-encoding" ]
information seemingly coming out of mysqldb incorrectly, python django
275,541
<p>In a latin-1 database i have '<code>\222\222\223\225</code>', when I try to pull this field from the django models I get back <code>u'\u2019\u2019\u201c\u2022'</code>.</p> <pre><code>from django.db import connection (Pdb) cursor = connection.cursor() (Pdb) cursor.execute("SELECT Password from campaignusers WHERE UserID=26") (Pdb) row = cursor.fetchone() </code></pre> <p>So I step into that and get into </p> <blockquote> <p>/usr/local/python2.5/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py(327)fetchone()->(u'\u2019...1c\u2022',) </p> </blockquote> <p>I can't step further into this because its an egg but it seems that the MySQL python driver is interpreting the data not as latin-1.</p> <p>Anyone have any clue whats going on?</p>
0
2008-11-09T03:06:06Z
303,448
<p>Django uses UTF-8, unless you define DEFAULT_CHARSET being something other. Be aware that defining other charset will require you to encode all your templates in this charset and this charset will pop from here to there, like email encoding, in sitemaps and feeds and so on. So, IMO, the best you can do is to go UTF-8, this will save you much headaches with Django (internally it's all unicode, the problems are on the borders of your app, like templates and input).</p>
0
2008-11-19T21:34:21Z
[ "python", "mysql", "django", "character-encoding" ]
Database change underneath SQLObject
275,572
<p>I'm starting a web project that likely should be fine with SQLite. I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready. My questions:</p> <ol> <li>How easy is it to transition from one DB (SQLite) to another (MySQL or Firebird or PostGre) under SQLObject? </li> <li>Does SQLObject provide any tools to make such a transition easier? Is it simply take the objects I've defined and call createTable? </li> <li>What about having multiple SQLite databases instead? E.g. one per visitor group? Does SQLObject provide a mechanism for handling this scenario and if so, what is the mechanism to use?</li> </ol> <p>Thanks, Sean</p>
1
2008-11-09T03:46:40Z
275,587
<p>I'm not sure I understand the question.</p> <p>The <a href="http://www.sqlobject.org/SQLObject.html#dbconnection-database-connections" rel="nofollow">SQLObject documentation</a> lists six kinds of connections available. Further, the database connection (or scheme) is specified in a connection string. Changing database connections from SQLite to MySQL is trivial. Just change the connection string.</p> <p>The <a href="http://www.sqlobject.org/SQLObject.html#declaring-a-connection" rel="nofollow">documentation</a> lists the different kinds of schemes that are supported.</p>
0
2008-11-09T04:06:02Z
[ "python", "mysql", "database", "sqlite", "sqlobject" ]
Database change underneath SQLObject
275,572
<p>I'm starting a web project that likely should be fine with SQLite. I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready. My questions:</p> <ol> <li>How easy is it to transition from one DB (SQLite) to another (MySQL or Firebird or PostGre) under SQLObject? </li> <li>Does SQLObject provide any tools to make such a transition easier? Is it simply take the objects I've defined and call createTable? </li> <li>What about having multiple SQLite databases instead? E.g. one per visitor group? Does SQLObject provide a mechanism for handling this scenario and if so, what is the mechanism to use?</li> </ol> <p>Thanks, Sean</p>
1
2008-11-09T03:46:40Z
275,676
<p>Your success with createTable() will depend on your existing underlying table schema / data types. In other words, how well SQLite maps to the database you choose and how SQLObject decides to use your data types.</p> <p>The safest option may be to create the new database by hand. Then you'll have to deal with data migration, which may be as easy as instantiating two SQLObject database connections over the same table definitions.</p> <p>Why not just start with the more full-featured database?</p>
2
2008-11-09T06:20:43Z
[ "python", "mysql", "database", "sqlite", "sqlobject" ]
Database change underneath SQLObject
275,572
<p>I'm starting a web project that likely should be fine with SQLite. I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready. My questions:</p> <ol> <li>How easy is it to transition from one DB (SQLite) to another (MySQL or Firebird or PostGre) under SQLObject? </li> <li>Does SQLObject provide any tools to make such a transition easier? Is it simply take the objects I've defined and call createTable? </li> <li>What about having multiple SQLite databases instead? E.g. one per visitor group? Does SQLObject provide a mechanism for handling this scenario and if so, what is the mechanism to use?</li> </ol> <p>Thanks, Sean</p>
1
2008-11-09T03:46:40Z
275,851
<p>3) Is quite an interesting question. In general, SQLite is pretty useless for web-based stuff. It scales fairly well for size, but scales terribly for concurrency, and so if you are planning to hit it with a few requests at the same time, you will be in trouble.</p> <p>Now your idea in part 3) of the question is to use multiple SQLite databases (eg one per user group, or even one per user). Unfortunately, SQLite will give you no help in this department. But it is possible. The one project I know that has done this before is <a href="http://www.divmod.org/trac/wiki/DivmodAxiom" rel="nofollow"><strong>Divmod's Axiom</strong></a>. So I would certainly check that out.</p> <p>Of course, it would probably be much easier to just use a good concurrent DB like the ones you mention (Firebird, PG, etc).</p> <p>For completeness:</p> <p>1 and 2) It should be straightforward without you actually writing <strong>much</strong> code. I find SQLObject a bit restrictive in this department, and would strongly recommend <a href="http://www.sqlalchemy.org/" rel="nofollow"><strong>SQLAlchemy</strong></a> instead. This is far more flexible, and if I was starting a new project today, I would certainly use it over SQLObject. It won't be moving "Objects" anywhere. There is no magic involved here, it will be transferring rows in tables in a database. Which as mentioned you could do by hand, but this might save you some time.</p>
3
2008-11-09T11:53:37Z
[ "python", "mysql", "database", "sqlite", "sqlobject" ]
How do you get a thumbnail of a movie using IMDbPy?
275,683
<p>Using <a href="http://imdbpy.sourceforge.net">IMDbPy</a> it is painfully easy to access movies from the IMDB site:</p> <pre><code>import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) </code></pre> <p>However I see no way to get the picture or thumbnail of the movie cover. Suggestions?</p>
6
2008-11-09T06:39:52Z
275,774
<p><strong>Note:</strong></p> <ul> <li>Not every movie has a cover url. (The random ID in your example doesn't.)</li> <li>Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.)</li> </ul> <p>...</p> <pre><code>import imdb access = imdb.IMDb() movie = access.get_movie(1132626) print "title: %s year: %s" % (movie['title'], movie['year']) print "Cover url: %s" % movie['cover url'] </code></pre> <p>If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url.</p> <pre><code>from BeautifulSoup import BeautifulSoup import imdb access = imdb.IMDb() movie = access.get_movie(1132626) page = urllib2.urlopen(access.get_imdbURL(movie)) soup = BeautifulSoup(page) cover_div = soup.find(attrs={"class" : "photo"}) cover_url = (photo_div.find('img'))['src'] print "Cover url: %s" % cover_url </code></pre>
10
2008-11-09T09:34:46Z
[ "python", "imdb", "imdbpy" ]
How do you get a thumbnail of a movie using IMDbPy?
275,683
<p>Using <a href="http://imdbpy.sourceforge.net">IMDbPy</a> it is painfully easy to access movies from the IMDB site:</p> <pre><code>import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) </code></pre> <p>However I see no way to get the picture or thumbnail of the movie cover. Suggestions?</p>
6
2008-11-09T06:39:52Z
275,826
<p>Response from the IMDbPy mailing list:</p> <blockquote> <p>If present, the url is accessible through movie['cover url']. Beware that it could be missing, so you must first test it with something like:<br /> if 'cover url' in movie: ...</p> <p>After that, you can use the urllib module to fetch the image itself.</p> <p>To provide a complete example, something like that should do the trick:</p> <pre><code>import urllib from imdb import IMDb ia = IMDb(#yourParameters) movie = ia.get_movie(#theMovieID) if 'cover url' in movie: urlObj = urllib.urlopen(movie['cover url']) imageData = urlObj.read() urlObj.close() # now you can save imageData in a file (open it in binary mode). </code></pre> <p>In the same way, a person's headshot is stored in person['headshot'].</p> <p>Things to be aware of:</p> <ul> <li>covers and headshots are available only fetching the data from the web server (via the 'http' or 'mobile' data access systems), and not in the plain text data files ('sql' or 'local').</li> <li>using the images, you must respect the terms of the IMDb's policy; see <a href="http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt" rel="nofollow">http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt</a></li> <li>the images you'll get will vary in size; you can use the python-imaging module to rescale them, if needed.</li> </ul> </blockquote>
2
2008-11-09T11:01:02Z
[ "python", "imdb", "imdbpy" ]
What's the difference between all of the os.popen() methods?
275,756
<p>I was looking at the <a href="http://www.python.org/doc/2.5.2/lib/module-popen2.html">Python documentation</a> and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. </p> <p>Apart from the fact that some include <em>stderr</em> while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very well.</p>
7
2008-11-09T08:50:12Z
275,758
<p>popen2 doesn't capture standard error, popen3 does capture standard error and gives a unique file handle for it. Finally, popen4 captures standard error but includes it in the same file object as standard output.</p>
9
2008-11-09T08:53:58Z
[ "python", "subprocess", "popen" ]
What's the difference between all of the os.popen() methods?
275,756
<p>I was looking at the <a href="http://www.python.org/doc/2.5.2/lib/module-popen2.html">Python documentation</a> and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. </p> <p>Apart from the fact that some include <em>stderr</em> while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very well.</p>
7
2008-11-09T08:50:12Z
275,817
<p>I would recommend to use the <code>subprocess</code> module which has all the features that these functions have and more.</p>
14
2008-11-09T10:44:40Z
[ "python", "subprocess", "popen" ]
What's the difference between all of the os.popen() methods?
275,756
<p>I was looking at the <a href="http://www.python.org/doc/2.5.2/lib/module-popen2.html">Python documentation</a> and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. </p> <p>Apart from the fact that some include <em>stderr</em> while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very well.</p>
7
2008-11-09T08:50:12Z
275,894
<p>Jason has it right. To summarize in a way that's easier to see:</p> <ul> <li>os.popen() -> stdout</li> <li>os.popen2() -> (stdin, stdout)</li> <li>os.popen3() -> (stdin, stdout, stderr)</li> <li>os.popen4() -> (stdin, stdout_and_stderr)</li> </ul>
12
2008-11-09T13:06:46Z
[ "python", "subprocess", "popen" ]
import mechanize module to python script
275,980
<p>I tried to import mechanize module to my python script like this,</p> <p>from mechanize import Browser</p> <p>But, Google appengine throws HTTP 500 when accessing my script.</p> <p>To make things more clear, Let me give you the snapshot of my package structure,</p> <pre><code>root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script </code></pre> <p>Can anyone help me out to resolve this issue?</p> <p>Thanks, Ponmalar</p>
4
2008-11-09T14:50:26Z
276,350
<p>When GAE throws a 500, you can see the actual error in the logs on your admin console. If that doesn't help, paste it here and we'll help further.</p> <p>Also, does it work on the dev_appserver?</p>
0
2008-11-09T19:27:31Z
[ "python", "google-app-engine" ]
import mechanize module to python script
275,980
<p>I tried to import mechanize module to my python script like this,</p> <p>from mechanize import Browser</p> <p>But, Google appengine throws HTTP 500 when accessing my script.</p> <p>To make things more clear, Let me give you the snapshot of my package structure,</p> <pre><code>root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script </code></pre> <p>Can anyone help me out to resolve this issue?</p> <p>Thanks, Ponmalar</p>
4
2008-11-09T14:50:26Z
276,640
<p>The mechanize main page says:</p> <blockquote> <p>mechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in turn, a subclass of urllib2.OpenerDirector</p> </blockquote> <p>My understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible.</p>
2
2008-11-09T23:09:47Z
[ "python", "google-app-engine" ]
import mechanize module to python script
275,980
<p>I tried to import mechanize module to my python script like this,</p> <p>from mechanize import Browser</p> <p>But, Google appengine throws HTTP 500 when accessing my script.</p> <p>To make things more clear, Let me give you the snapshot of my package structure,</p> <pre><code>root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script </code></pre> <p>Can anyone help me out to resolve this issue?</p> <p>Thanks, Ponmalar</p>
4
2008-11-09T14:50:26Z
281,012
<p>Thanks All for the prompt reply.</p> <p>Here is the log content got from the GAE,</p> <p>: No module named ClientForm Traceback (most recent call last): File "/base/data/home/apps/seoapp/1.28/main.py", line 10, in import mechanize File "/base/data/home/apps/seoapp/1.28/mechanize/<strong>init</strong>.py", line 85, in from _mechanize import <strong>version</strong> File "/base/data/home/apps/seoapp/1.28/mechanize/_mechanize.py", line 15, in from _useragent import UserAgentBase File "/base/data/home/apps/seoapp/1.28/mechanize/_useragent.py", line 16, in import _opener File "/base/data/home/apps/seoapp/1.28/mechanize/_opener.py", line 23, in import _http File "/base/data/home/apps/seoapp/1.28/mechanize/_http.py", line 22, in from _html import unescape, unescape_charref File "/base/data/home/apps/seoapp/1.28/mechanize/_html.py", line 12, in import sgmllib, ClientForm</p>
0
2008-11-11T14:25:59Z
[ "python", "google-app-engine" ]
import mechanize module to python script
275,980
<p>I tried to import mechanize module to my python script like this,</p> <p>from mechanize import Browser</p> <p>But, Google appengine throws HTTP 500 when accessing my script.</p> <p>To make things more clear, Let me give you the snapshot of my package structure,</p> <pre><code>root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script </code></pre> <p>Can anyone help me out to resolve this issue?</p> <p>Thanks, Ponmalar</p>
4
2008-11-09T14:50:26Z
281,097
<p>I can finally manage with GAE's urlfetch instead of mechanizer. I can able to retrieve the response using the above said utility.</p> <p>Thanks all for the great timely help.</p> <p>^Ponmalar</p>
0
2008-11-11T14:53:08Z
[ "python", "google-app-engine" ]
Remote debugging of multi threaded Python Applications
275,989
<p>How can I do remote debugging of a multi threaded Python application, running on an Embedded Linux based system, from Windows XP or Vista?</p> <p>So far I have only come across <a href="http://pyscripter.googlepages.com/" rel="nofollow">PyScripter based remote debugging</a>. How does it perform?</p>
1
2008-11-09T15:05:23Z
276,015
<p>I've never used it except a few quick trial runs, but <a href="http://winpdb.org/" rel="nofollow">winpdb</a> sounds like it does just what you want:</p> <blockquote> <p>Winpdb is a platform independent GPL Python debugger with support for multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p> </blockquote>
1
2008-11-09T15:30:08Z
[ "python", "remote-debugging" ]
How to get current CPU and RAM usage in Python?
276,052
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
150
2008-11-09T16:04:50Z
276,164
<p>I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above. </p>
0
2008-11-09T17:25:10Z
[ "python", "system", "cpu", "status", "ram" ]
How to get current CPU and RAM usage in Python?
276,052
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
150
2008-11-09T16:04:50Z
276,304
<p>"... current system status (current CPU, RAM, free disk space, etc.)" And "*nix and Windows platforms" can be a difficult combination to achieve.</p> <p>The operating systems are fundamentally different in the way they manage these resources. Indeed, they differ in core concepts like defining what counts as system and what counts as application time.</p> <p>"Free disk space"? What counts as "disk space?" All partitions of all devices? What about foreign partitions in a multi-boot environment?</p> <p>I don't think there's a clear enough consensus between Windows and *nix that makes this possible. Indeed, there may not even be any consensus between the various operating systems called Windows. Is there a single Windows API that works for both XP and Vista?</p>
3
2008-11-09T18:50:34Z
[ "python", "system", "cpu", "status", "ram" ]
How to get current CPU and RAM usage in Python?
276,052
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
150
2008-11-09T16:04:50Z
276,934
<p>Here's something I put together a while ago, it's windows only but may help you get part of what you need done.</p> <p>Derived from: "for sys available mem" <a href="http://msdn2.microsoft.com/en-us/library/aa455130.aspx">http://msdn2.microsoft.com/en-us/library/aa455130.aspx</a></p> <p>"individual process information and python script examples" <a href="http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true">http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true</a></p> <p>NOTE: the WMI interface/process is also available for performing similar tasks I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this, then may want to investigate the WMI tools a vailable.</p> <p>WMI for python:</p> <p><a href="http://tgolden.sc.sabren.com/python/wmi.html">http://tgolden.sc.sabren.com/python/wmi.html</a></p> <p>The code:</p> <pre><code>''' Monitor window processes derived from: &gt;for sys available mem http://msdn2.microsoft.com/en-us/library/aa455130.aspx &gt; individual process information and python script examples http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true NOTE: the WMI interface/process is also available for performing similar tasks I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this module, then may want to investigate the WMI tools available. WMI for python: http://tgolden.sc.sabren.com/python/wmi.html ''' __revision__ = 3 import win32com.client from ctypes import * from ctypes.wintypes import * import pythoncom import pywintypes import datetime class MEMORYSTATUS(Structure): _fields_ = [ ('dwLength', DWORD), ('dwMemoryLoad', DWORD), ('dwTotalPhys', DWORD), ('dwAvailPhys', DWORD), ('dwTotalPageFile', DWORD), ('dwAvailPageFile', DWORD), ('dwTotalVirtual', DWORD), ('dwAvailVirtual', DWORD), ] def winmem(): x = MEMORYSTATUS() # create the structure windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes return x class process_stats: '''process_stats is able to provide counters of (all?) the items available in perfmon. Refer to the self.supported_types keys for the currently supported 'Performance Objects' To add logging support for other data you can derive the necessary data from perfmon: --------- perfmon can be run from windows 'run' menu by entering 'perfmon' and enter. Clicking on the '+' will open the 'add counters' menu, From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key. --&gt; Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent) For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary, keyed by the 'Performance Object' name as mentioned above. --------- NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly. Initially the python implementation was derived from: http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true ''' def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]): '''process_names_list == the list of all processes to log (if empty log all) perf_object_list == list of process counters to log filter_list == list of text to filter print_results == boolean, output to stdout ''' pythoncom.CoInitialize() # Needed when run by the same process in a thread self.process_name_list = process_name_list self.perf_object_list = perf_object_list self.filter_list = filter_list self.win32_perf_base = 'Win32_PerfFormattedData_' # Define new datatypes here! self.supported_types = { 'NETFramework_NETCLRMemory': [ 'Name', 'NumberTotalCommittedBytes', 'NumberTotalReservedBytes', 'NumberInducedGC', 'NumberGen0Collections', 'NumberGen1Collections', 'NumberGen2Collections', 'PromotedMemoryFromGen0', 'PromotedMemoryFromGen1', 'PercentTimeInGC', 'LargeObjectHeapSize' ], 'PerfProc_Process': [ 'Name', 'PrivateBytes', 'ElapsedTime', 'IDProcess',# pid 'Caption', 'CreatingProcessID', 'Description', 'IODataBytesPersec', 'IODataOperationsPersec', 'IOOtherBytesPersec', 'IOOtherOperationsPersec', 'IOReadBytesPersec', 'IOReadOperationsPersec', 'IOWriteBytesPersec', 'IOWriteOperationsPersec' ] } def get_pid_stats(self, pid): this_proc_dict = {} pythoncom.CoInitialize() # Needed when run by the same process in a thread if not self.perf_object_list: perf_object_list = self.supported_types.keys() for counter_type in perf_object_list: strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type) colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread if len(colItems) &gt; 0: for objItem in colItems: if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess: for attribute in self.supported_types[counter_type]: eval_str = 'objItem.%s' % (attribute) this_proc_dict[attribute] = eval(eval_str) this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3] break return this_proc_dict def get_stats(self): ''' Show process stats for all processes in given list, if none given return all processes If filter list is defined return only the items that match or contained in the list Returns a list of result dictionaries ''' pythoncom.CoInitialize() # Needed when run by the same process in a thread proc_results_list = [] if not self.perf_object_list: perf_object_list = self.supported_types.keys() for counter_type in perf_object_list: strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type) colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread try: if len(colItems) &gt; 0: for objItem in colItems: found_flag = False this_proc_dict = {} if not self.process_name_list: found_flag = True else: # Check if process name is in the process name list, allow print if it is for proc_name in self.process_name_list: obj_name = objItem.Name if proc_name.lower() in obj_name.lower(): # will log if contains name found_flag = True break if found_flag: for attribute in self.supported_types[counter_type]: eval_str = 'objItem.%s' % (attribute) this_proc_dict[attribute] = eval(eval_str) this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3] proc_results_list.append(this_proc_dict) except pywintypes.com_error, err_msg: # Ignore and continue (proc_mem_logger calls this function once per second) continue return proc_results_list def get_sys_stats(): ''' Returns a dictionary of the system stats''' pythoncom.CoInitialize() # Needed when run by the same process in a thread x = winmem() sys_dict = { 'dwAvailPhys': x.dwAvailPhys, 'dwAvailVirtual':x.dwAvailVirtual } return sys_dict if __name__ == '__main__': # This area used for testing only sys_dict = get_sys_stats() stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[]) proc_results = stats_processor.get_stats() for result_dict in proc_results: print result_dict import os this_pid = os.getpid() this_proc_results = stats_processor.get_pid_stats(this_pid) print 'this proc results:' print this_proc_results </code></pre> <p><a href="http://monkut.webfactional.com/blog/archive/2009/1/21/windows-process-memory-logging-python">http://monkut.webfactional.com/blog/archive/2009/1/21/windows-process-memory-logging-python</a></p>
7
2008-11-10T02:38:51Z
[ "python", "system", "cpu", "status", "ram" ]
How to get current CPU and RAM usage in Python?
276,052
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
150
2008-11-09T16:04:50Z
2,468,983
<p><a href="https://pypi.python.org/pypi/psutil">The psutil library</a> will give you some system information (CPU / Memory usage) on a variety of platforms:</p> <blockquote> <p>psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.</p> <p>It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).</p> </blockquote>
196
2010-03-18T10:24:30Z
[ "python", "system", "cpu", "status", "ram" ]
How to get current CPU and RAM usage in Python?
276,052
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
150
2008-11-09T16:04:50Z
36,337,011
<p>You can use psutil or psmem with subprocess example code </p> <pre><code>import subprocess cmd = subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) out,error = cmd.communicate() memory = out.splitlines() </code></pre> <p>Reference <a href="http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/" rel="nofollow">http://techarena51.com/index.php/how-to-install-python-3-and-flask-on-linux/</a></p> <p><a href="https://github.com/Leo-g/python-flask-cmd" rel="nofollow">https://github.com/Leo-g/python-flask-cmd</a></p>
0
2016-03-31T14:57:48Z
[ "python", "system", "cpu", "status", "ram" ]
How to get current CPU and RAM usage in Python?
276,052
<p>What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/">PSI</a> (that currently seems not actively developed and not supported on multiple platform) or something like <a href="http://www.i-scream.org/pystatgrab/">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p></li> <li><p>Using platform specific code such as using a <code>os.popen("ps")</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p></li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
150
2008-11-09T16:04:50Z
38,984,517
<p>Use the <a href="https://pypi.python.org/pypi/psutil/4.3.0" rel="nofollow">psutil library</a>. For me on Ubuntu, pip installed 0.4.3. You can check your version of psutil by doing </p> <pre><code>from __future__ import print_function import psutil print(psutil.__versi‌​on__) </code></pre> <p>in Python.</p> <p>To get some memory and CPU stats:</p> <pre><code>from __future__ import print_function import psutil print(psutil.cpu_percent()) # for version 0.5.0 print(psutil.phymem_usage()) # physical memory usage # for version 4.3.0 print(psutil.virtual_memory()) # I think still physical memory use, # the % is the same as psutil.phymem_usage() from 0.5.0 </code></pre> <p>I also like to do:</p> <pre><code>import os import psutil pid = os.getpid() py = psutil.Process(pid) memoryUse = py.memory_info()[0]/2.**30 # memory use in GB...I think print('memory use:', memoryUse) </code></pre> <p>which gives the current memory use of your Python script.</p> <p>There are some more in-depth examples on the <a href="https://pypi.python.org/pypi/psutil/4.3.0" rel="nofollow">pypi page for 4.3.0</a> and <a href="http://pypi.python.org/pypi/psutil/0.5.0" rel="nofollow">0.5.0</a>.</p> <p>For Ubuntu 16 and 14, installing from pip gave me version 4.3.0, which doesn't have the phymem_usage() method. To get 0.5.0, <a href="http://pypi.python.org/pypi/psutil/0.5.0" rel="nofollow">download the tar.gz file</a>, then do </p> <pre><code>tar -xvzf psutil-0.5.0.tar.gz‌​ cd psutil-0.5.0 sudo python setup.py install </code></pre>
0
2016-08-16T21:07:35Z
[ "python", "system", "cpu", "status", "ram" ]
WCF and Python
276,184
<p>Is there any example code of a <a href="http://www.python.org/">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
20
2008-11-09T17:41:15Z
276,545
<p>Even if there is not a specific example of calling WCF from Python, you should be able to make a fully SOAP compliant service with WCF. Then all you have to do is find some examples of how to call a normal SOAP service from Python.</p> <p>The simplest thing will be to use the BasicHttpBinding in WCF and then you can support your own sessions by passing a session token with each request and response.</p>
0
2008-11-09T22:03:59Z
[ "python", "wcf" ]
WCF and Python
276,184
<p>Is there any example code of a <a href="http://www.python.org/">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
20
2008-11-09T17:41:15Z
707,911
<p>WCF needs to expose functionality through a communication protocol. I think the most commonly used protocol is probably SOAP over HTTP. Let's assume that's what you're using then.</p> <p>Take a look at <a href="http://www.diveintopython.net/soap_web_services/index.html">this chapter in Dive Into Python</a>. It will show you how to make SOAP calls.</p> <p>I know of no unified way of calling a WCF service in Python, regardless of communication protocol.</p>
7
2009-04-02T00:56:04Z
[ "python", "wcf" ]
WCF and Python
276,184
<p>Is there any example code of a <a href="http://www.python.org/">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
20
2008-11-09T17:41:15Z
822,320
<p>I do not know of any direct examples, but if the WCF service is REST enabled you could access it through POX (Plain Old XML) via the REST methods/etc (if the service has any). If you are in control of the service you could expose endpoints via REST as well. </p>
1
2009-05-04T22:07:26Z
[ "python", "wcf" ]
WCF and Python
276,184
<p>Is there any example code of a <a href="http://www.python.org/">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
20
2008-11-09T17:41:15Z
3,000,418
<p>if you need binary serialized communication over tcp then consider implementing solution like Thrift.</p>
1
2010-06-08T19:04:43Z
[ "python", "wcf" ]
WCF and Python
276,184
<p>Is there any example code of a <a href="http://www.python.org/">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
20
2008-11-09T17:41:15Z
3,865,315
<p>I used <a href="/questions/tagged/suds" class="post-tag" title="show questions tagged 'suds'" rel="tag">suds</a>.</p> <pre><code>from suds.client import Client print "Connecting to Service..." wsdl = "http://serviceurl.com/service.svc?WSDL" client = Client(wsdl) result = client.service.Method(variable1, variable2) print result </code></pre> <p>That should get you started. I'm able to connect to exposed services from WCF and a RESTful layer. There needs to be some data massaging to help do what you need, especially if you need to bind to several namespaces.</p>
16
2010-10-05T15:42:35Z
[ "python", "wcf" ]
WCF and Python
276,184
<p>Is there any example code of a <a href="http://www.python.org/">cpython</a> (not IronPython) client which can call Windows Communication Foundation (WCF) service?</p>
20
2008-11-09T17:41:15Z
36,152,458
<p>Just to help someone to access WCF SOAP 1.2 service with WS-Addressing using suds. Main problem is to inject action name in every message.</p> <p>This example for python 3 and suds port <a href="https://bitbucket.org/jurko/suds" rel="nofollow">https://bitbucket.org/jurko/suds</a>.</p> <p>Example uses custom authentification based on HTTP headers, i leave it as is.</p> <p>TODO: Automatically get api_direct_url from WSDL (at now it is hard coded).</p> <pre><code>from suds.plugin import MessagePlugin from suds.sax.text import Text from suds.wsse import Security, UsernameToken from suds.sax.element import Element from suds.sax.attribute import Attribute from suds.xsd.sxbasic import Import api_username = 'some' api_password = 'none' class api(object): api_direct_url = 'some/mex' api_url = 'some.svc?singleWsdl|Wsdl' NS_WSA = ('wsa', 'http://www.w3.org/2005/08/addressing') _client_instance = None @property def client(self): if self._client_instance: return self._client_instance from suds.bindings import binding binding.envns = ('SOAP-ENV', 'http://www.w3.org/2003/05/soap-envelope') api_inst = self class _WSAPlugin(MessagePlugin): def marshalled(self, context): api_inst._marshalled_message(context) self._client_instance = Client(self.api_url, plugins=[_WSAPlugin()], headers={'Content-Type': 'application/soap+xml', 'login':api_username, 'password': api_password} ) headers = [] headers.append(Element('To', ns=self.NS_WSA).setText(self.api_direct_url)) headers.append(Element('Action', ns=self.NS_WSA).setText('Blank')) self._client_instance.set_options(soapheaders=headers) cache = self._client_instance.options.cache cache.setduration(days=10) return self._client_instance def _marshalled_message(self, context): def _children(r): if hasattr(r, 'children'): for c in r.children: yield from _children(c) yield c for el in _children(context.envelope): if el.name == 'Action': el.text = Text(self._current_action) return _current_action = None def _invoke(self, method, *args): try: self._current_action = method.method.soap.action.strip('"') return method(*args) finally: self._current_action = None def GetRequestTypes(self): return self._invoke(self.client.service.GetRequestTypes)[0] def GetTemplateByRequestType(self, request_type_id): js = self._invoke(self.client.service.GetTemplateByRequestType, request_type_id) return json.loads(js) def GetRequestStatus(self, request_guid): return self._invoke(self.client.service.GetRequestStatus, request_guid) def SendRequest(self, request_type_id, request_json): r = json.dumps(request_json, ensure_ascii=False) return self._invoke(self.client.service.SendRequest, request_type_id, r) </code></pre>
0
2016-03-22T10:53:14Z
[ "python", "wcf" ]
What's a cross platform way to play a sound file in python?
276,266
<p>I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.</p> <blockquote> <p>The error is "IOError: [Errorno Invalid output device (no default output device)] -9996</p> </blockquote> <p>Is there another library I could try to use? Another method?</p>
17
2008-11-09T18:28:42Z
276,322
<p>Have you looked at pymedia? It looks as easy as this to play a WAV file:</p> <pre><code>import time, wave, pymedia.audio.sound as sound f= wave.open('YOUR FILE NAME', 'rb') sampleRate= f.getframerate() channels= f.getnchannels() format= sound.AFMT_S16_LE snd= sound.Output(sampleRate, channels, format) s= f.readframes(300000) snd.play(s) while snd.isPlaying(): time.sleep(0.05) </code></pre> <p>Ref: <a href="http://pymedia.org/tut/play_wav.html" rel="nofollow">http://pymedia.org/tut/play_wav.html</a></p> <p>Of course, you can have a look at the Python wiki under Audio (<a href="http://wiki.python.org/moin/Audio/" rel="nofollow">http://wiki.python.org/moin/Audio/</a>) for other libraries such as <a href="https://docs.python.org/library/wave.html" rel="nofollow">https://docs.python.org/library/wave.html</a> or again in Python's wiki under Game Libraries (<a href="http://wiki.python.org/moin/PythonGameLibraries" rel="nofollow">http://wiki.python.org/moin/PythonGameLibraries</a>) that will point you to bindings to OpenAL or Pygame that has sound modules.</p> <p>And finally, although I don't know the limitations of pyaudio, your error message sounds more like the library is not able to find the default output device more than the device is in use by another process. Maybe have a look at what output device is returned by the <code>get_default_output_device_info</code> of pyaudio and compare it to whatever's your default setting in Ubuntu.</p>
4
2008-11-09T19:05:47Z
[ "python", "cross-platform", "audio" ]
What's a cross platform way to play a sound file in python?
276,266
<p>I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.</p> <blockquote> <p>The error is "IOError: [Errorno Invalid output device (no default output device)] -9996</p> </blockquote> <p>Is there another library I could try to use? Another method?</p>
17
2008-11-09T18:28:42Z
277,274
<p>You can use <a href="http://wxpython.org/">wxPython</a></p> <pre><code>sound = wx.Sound('sound.wav') sound.Play(wx.SOUND_SYNC) </code></pre> <p>or</p> <pre><code>sound.Play(wx.SOUND_ASYNC) </code></pre> <p><a href="http://svn.wxwidgets.org/viewvc/wx/wxPython/tags/wxPy-2.8.9.1/wxPython/demo/Sound.py?view=markup">Here</a> is an example from the wxPython demo.</p>
12
2008-11-10T07:21:59Z
[ "python", "cross-platform", "audio" ]
What's a cross platform way to play a sound file in python?
276,266
<p>I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.</p> <blockquote> <p>The error is "IOError: [Errorno Invalid output device (no default output device)] -9996</p> </blockquote> <p>Is there another library I could try to use? Another method?</p>
17
2008-11-09T18:28:42Z
277,429
<p>I'm not absolutely sure if that fulfills your requirements, but I immediately thought PyGame</p> <p><a href="http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound" rel="nofollow" title="PyGame Sound Module">http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound</a></p> <pre><code>from pygame import mixer mixer.init() s = mixer.Sound('sound.wav') s.play() </code></pre>
1
2008-11-10T09:37:33Z
[ "python", "cross-platform", "audio" ]
What's a cross platform way to play a sound file in python?
276,266
<p>I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.</p> <blockquote> <p>The error is "IOError: [Errorno Invalid output device (no default output device)] -9996</p> </blockquote> <p>Is there another library I could try to use? Another method?</p>
17
2008-11-09T18:28:42Z
36,284,017
<p>You can try <a href="http://simpleaudio.readthedocs.org/en/latest/index.html" rel="nofollow">Simpleaudio</a>:</p> <pre><code>&gt; pip install simpleaudio </code></pre> <p>Then:</p> <pre><code>import simpleaudio as sa wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav") play_obj = wave_obj.play() play_obj.wait_done() </code></pre>
2
2016-03-29T12:16:08Z
[ "python", "cross-platform", "audio" ]
CPU Usage Per Process in Python
276,281
<p>Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?</p> <p>Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?</p> <p>Target platform is *nix, however I would like to do it on a Win host also.</p>
14
2008-11-09T18:35:14Z
276,289
<p>The <code>resource</code> module provides <a href="http://www.python.org/doc/2.5.2/lib/node522.html"><code>getrusage</code></a> which can give you the information you need, at least for Unix-like platforms.</p> <p>Note that CPU usage as a percentage is always measured over a time interval. Essentially, it is the amount of time taken by your program doing something divided by the interval time.</p> <p>For example, if your application takes 2 seconds of CPU time over a 5 second period, then it can be said to be using 40% of the CPU.</p> <p>Note that this calculation, as simple as it seems, can get tricky when using a multiprocessor system. If your application uses 7 seconds of CPU time in 5 seconds of wall clock time on a two-processor system, do you say it is uses 140% or 70% CPU?</p> <p>Update: As <a href="http://stackoverflow.com/questions/276281/cpu-usage-per-process-in-python#276295">gimel</a> mentions, the <code>os.times</code> function also provides this information in a platform-independent way. The above calculation notes still apply, of course.</p>
6
2008-11-09T18:40:07Z
[ "python", "monitoring", "cpu-usage" ]
CPU Usage Per Process in Python
276,281
<p>Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?</p> <p>Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?</p> <p>Target platform is *nix, however I would like to do it on a Win host also.</p>
14
2008-11-09T18:35:14Z
276,295
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.times() (1.296875, 0.765625, 0.0, 0.0, 0.0) &gt;&gt;&gt; print os.times.__doc__ times() -&gt; (utime, stime, cutime, cstime, elapsed_time) Return a tuple of floating point numbers indicating process times. </code></pre> <p>From the (2.5) manual:</p> <blockquote> <p>times( ) </p> <p>Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows. </p> </blockquote>
23
2008-11-09T18:44:10Z
[ "python", "monitoring", "cpu-usage" ]
CPU Usage Per Process in Python
276,281
<p>Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?</p> <p>Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?</p> <p>Target platform is *nix, however I would like to do it on a Win host also.</p>
14
2008-11-09T18:35:14Z
4,815,145
<p>Use <code>time.clock()</code> to get the CPU time. To get the percentage of CPU usage do CPU time elapsed/time elapsed</p> <p>For example, if CPU time elapsed is 0.2 and time elapsed is 1 then the cpu usage is 20%.</p> <p>Note:You have to divide by by number of processers you have. If you have 2 i.e. a dual core:</p> <pre><code>import decimal,timeit decimal.getcontext().prec=1000 def torture(): decimal.Decimal(2).sqrt() time.sleep(0.1) import time clock=time.clock() while 1: clock=timeit.timeit(torture,number=10) tclock=time.clock() print((tclock-clock)*p) clock=tclock </code></pre>
0
2011-01-27T10:24:24Z
[ "python", "monitoring", "cpu-usage" ]
CPU Usage Per Process in Python
276,281
<p>Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?</p> <p>Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?</p> <p>Target platform is *nix, however I would like to do it on a Win host also.</p>
14
2008-11-09T18:35:14Z
6,265,475
<p>By using <a href="http://code.google.com/p/psutil" rel="nofollow">psutil</a>:</p> <pre><code>&gt;&gt;&gt; import psutil &gt;&gt;&gt; p = psutil.Process() &gt;&gt;&gt; p.cpu_times() cputimes(user=0.06, system=0.03) &gt;&gt;&gt; p.cpu_percent(interval=1) 0.0 &gt;&gt;&gt; </code></pre>
12
2011-06-07T12:55:38Z
[ "python", "monitoring", "cpu-usage" ]
How to show the visitor a moved web page AND return a 301 redirect HTTP response status code in Django?
276,286
<p>When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in <a href="http://djangoproject.com/" rel="nofollow">Django</a>?</p>
0
2008-11-09T18:39:37Z
276,323
<p>You can't.</p> <p>301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page <em>must</em> have a 200 code.</p> <p>One small variant is to detect search engine spiders (by IP and/or user agent) and give <em>them</em> the 301. That way the search results point to your new page.</p>
3
2008-11-09T19:08:06Z
[ "python", "django", "http", "redirect", "http-headers" ]
How to show the visitor a moved web page AND return a 301 redirect HTTP response status code in Django?
276,286
<p>When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in <a href="http://djangoproject.com/" rel="nofollow">Django</a>?</p>
0
2008-11-09T18:39:37Z
276,326
<pre><code> from django import http return http.HttpResponsePermanentRedirect('/yournewpage.html') </code></pre> <p>the browser will get the 301, and go to <code>/yournewpage.html</code> as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood:</p> <pre><code>Browser Python HTTP -------------------&gt; GET /youroldpage.html HTTP/1.1 &lt;------------------- HTTP/1.1 301 Moved Permanently Location: /yournewpage.html -------------------&gt; GET /yournewpage.html HTTP/1.1 </code></pre>
8
2008-11-09T19:13:21Z
[ "python", "django", "http", "redirect", "http-headers" ]
Syntax error whenever I put Python code inside a Django template
276,345
<p>I'm trying to do the following in my Django template:</p> <pre><code> {% for embed in embeds %} {% embed2 = embed.replace("&amp;lt;", "&lt;") %} {{embed2}}&lt;br /&gt; {% endfor %} </code></pre> <p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p> <p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p> <p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p> <pre><code>embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&amp;lt;", "&lt;")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) </code></pre> <p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
2
2008-11-09T19:24:41Z
276,372
<p>I am quite sure that Django templates does not support that. For your replace operation I would look into different filters.</p> <p>You really should try to keep as much logic as you can in your views and not in the templates.</p>
7
2008-11-09T19:44:06Z
[ "python", "django", "templates", "django-templates" ]
Syntax error whenever I put Python code inside a Django template
276,345
<p>I'm trying to do the following in my Django template:</p> <pre><code> {% for embed in embeds %} {% embed2 = embed.replace("&amp;lt;", "&lt;") %} {{embed2}}&lt;br /&gt; {% endfor %} </code></pre> <p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p> <p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p> <p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p> <pre><code>embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&amp;lt;", "&lt;")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) </code></pre> <p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
2
2008-11-09T19:24:41Z
276,387
<p>Django templates use their own syntax, not like <a href="http://en.wikipedia.org/wiki/Kid%5F%28templating%5Flanguage%29" rel="nofollow">Kid</a> or <a href="http://en.wikipedia.org/wiki/Genshi%5F%28templating%5Flanguage%29" rel="nofollow">Genshi</a>.</p> <p>You have to roll your own <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">Custom Template Tag</a>.</p> <p>I guess the main reason is enforcing good practice. In my case, I've already a hard time explaining those special templates tags to the designer on our team. If it was plain Python I'm pretty sure we wouldn't have chosen Django at all. I think there's also a performance issue, Django templates benchmarks are fast, while last time I checked genshi was much slower. I don't know if it's due to freely embedded Python, though.</p> <p>You either need to review your approach and write your own custom templates (more or less synonyms to "helpers" in Ruby on Rails), or try another template engine.</p> <p>For your edit, there's a better syntax in Python:</p> <pre><code>embed_list.append(embed.replace("&amp;lt;", "&lt;")) </code></pre> <p>I don't know if it'll fix your error, but at least it's less JavaScriptesque ;-)</p> <p>Edit 2: Django automatically escapes all variables. You can enforce raw HTML with |safe filter : <code>{{embed|safe}}</code>.</p> <p>You'd better take some time reading the documentation, which is really great and useful.</p>
2
2008-11-09T19:58:50Z
[ "python", "django", "templates", "django-templates" ]
Syntax error whenever I put Python code inside a Django template
276,345
<p>I'm trying to do the following in my Django template:</p> <pre><code> {% for embed in embeds %} {% embed2 = embed.replace("&amp;lt;", "&lt;") %} {{embed2}}&lt;br /&gt; {% endfor %} </code></pre> <p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p> <p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p> <p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p> <pre><code>embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&amp;lt;", "&lt;")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) </code></pre> <p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
2
2008-11-09T19:24:41Z
276,394
<p>Instead of using a slice assignment to grow a list</p> <p><code>embed_list[len(embed_list):] = [foo]</code></p> <p>you should probably just do</p> <p><code>embed_list.append(foo)</code></p> <p>But really you should try unescaping html with a library function rather than doing it yourself.</p> <p>That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.</p>
2
2008-11-09T20:04:55Z
[ "python", "django", "templates", "django-templates" ]
Syntax error whenever I put Python code inside a Django template
276,345
<p>I'm trying to do the following in my Django template:</p> <pre><code> {% for embed in embeds %} {% embed2 = embed.replace("&amp;lt;", "&lt;") %} {{embed2}}&lt;br /&gt; {% endfor %} </code></pre> <p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p> <p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p> <p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p> <pre><code>embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&amp;lt;", "&lt;")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) </code></pre> <p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
2
2008-11-09T19:24:41Z
276,395
<p>I don't see why you'd get "NoneType object is not callable". That should mean that somewhere on the line is an expression like "foo(...)", and it means foo is None.</p> <p>BTW: You are trying to extend the embed_list, and it's easier to do it like this:</p> <pre><code>embed_list = [] for embed in embeds: embed_list.append(embed.replace("&amp;lt;", "&lt;")) #this is line 35 return render_to_response("scanvideos.html", {"embed_list":embed_list}) </code></pre> <p>and even easier to use a list comprehension:</p> <pre><code>embed_list = [embed.replace("&amp;lt;", "&lt;") for embed in embeds] </code></pre>
3
2008-11-09T20:04:59Z
[ "python", "django", "templates", "django-templates" ]
Syntax error whenever I put Python code inside a Django template
276,345
<p>I'm trying to do the following in my Django template:</p> <pre><code> {% for embed in embeds %} {% embed2 = embed.replace("&amp;lt;", "&lt;") %} {{embed2}}&lt;br /&gt; {% endfor %} </code></pre> <p>However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?</p> <p>Edit: the exact error is: <code>Invalid block tag: 'embed2'</code></p> <p>Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:</p> <pre><code>embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&amp;lt;", "&lt;")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) </code></pre> <p>However, I now get an error: <code>'NoneType' object is not callable" on line 35</code>.</p>
2
2008-11-09T19:24:41Z
276,838
<p>Django's template language is deliberately hobbled. When used by non-programming designers, this is definitely a Good Thing, but there are times when you <em>need</em> to do a little programming. (No, I don't want to argue about that. This has come up several times on django-users and django-dev.)</p> <p>Two ways to accomplish what you were trying:</p> <ul> <li>Use a different template engine. See <a href="http://jinja.pocoo.org/2/">Jinja2</a> for a good example that is fully explained for integrating with Django.</li> <li>Use a template tag that permits you to do Python expressions. See <a href="http://www.djangosnippets.org/snippets/9/">limodou's Expr tag</a>.</li> </ul> <p>I have used the expr tag in several places and it has made life <em>much</em> easier. My next major Django site will use jinja2.</p>
6
2008-11-10T01:25:36Z
[ "python", "django", "templates", "django-templates" ]
Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?
276,656
<p>So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code:</p> <pre><code>class SomeEntity(models.Model): some_field = models.CharField(max_length=50, db_index=True, unique=True) </code></pre> <p>I've got the admin interface setup and everything appears to be working fine except that I can create two SomeEntity records, one with some_field='some value' and one with some_field='Some Value' because the unique constraint on some_field appears to be case sensitive.</p> <p>Is there some way to force sqlite to perform a case <em>in</em>sensitive comparison when checking for uniqueness?</p> <p>I can't seem to find an option for this in Django's docs and I'm wondering if there's something that I can do directly to sqlite to get it to behave the way I want. :-)</p>
11
2008-11-09T23:20:13Z
276,708
<p>Perhaps you can create and use a custom model field; it would be a subclass of CharField but providing a <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#db_type" rel="nofollow">db_type</a> method returning "text collate nocase"</p>
3
2008-11-10T00:00:26Z
[ "python", "django", "sqlite", "django-models" ]
Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?
276,656
<p>So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code:</p> <pre><code>class SomeEntity(models.Model): some_field = models.CharField(max_length=50, db_index=True, unique=True) </code></pre> <p>I've got the admin interface setup and everything appears to be working fine except that I can create two SomeEntity records, one with some_field='some value' and one with some_field='Some Value' because the unique constraint on some_field appears to be case sensitive.</p> <p>Is there some way to force sqlite to perform a case <em>in</em>sensitive comparison when checking for uniqueness?</p> <p>I can't seem to find an option for this in Django's docs and I'm wondering if there's something that I can do directly to sqlite to get it to behave the way I want. :-)</p>
11
2008-11-09T23:20:13Z
471,066
<p>Yes this can easily be done by adding a unique index to the table with the following command:</p> <p>CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE)</p> <p>If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following:</p> <p>The following example shows a custom collation that sorts “the wrong way”:</p> <pre><code>import sqlite3 def collate_reverse(string1, string2): return -cmp(string1, string2) con = sqlite3.connect(":memory:") con.create_collation("reverse", collate_reverse) cur = con.cursor() cur.execute("create table test(x)") cur.executemany("insert into test(x) values (?)", [("a",), ("b",)]) cur.execute("select x from test order by x collate reverse") for row in cur: print row con.close() </code></pre> <p>Additional python documentation for sqlite3 shown <a href="http://docs.python.org/library/sqlite3.html">here</a></p>
8
2009-01-22T22:18:21Z
[ "python", "django", "sqlite", "django-models" ]
How to import a python file in python script more than once
276,679
<p>Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks</p> <p><strong>edit:</strong> Resolved myself thanks</p>
1
2008-11-09T23:40:27Z
276,692
<p>The easiest answer is to put the code you are trying to run inside a function like this</p> <p>(inside your module that you are importing now):</p> <pre><code>def main(): # All the code that currently does work goes in here # rather than just in the module </code></pre> <p>(The module that does the importing)</p> <pre><code>import your_module #used to do the work your_module.main() # now does the work (and you can call it multiple times) # some other code your_module.main() # do the work again </code></pre>
4
2008-11-09T23:50:30Z
[ "python" ]
How to import a python file in python script more than once
276,679
<p>Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks</p> <p><strong>edit:</strong> Resolved myself thanks</p>
1
2008-11-09T23:40:27Z
276,694
<p>The import statement -- by definition -- only imports once. </p> <p>You can, if you want, try to use <code>execfile()</code> (or <code>eval()</code>) to execute a separate file more than once. </p>
1
2008-11-09T23:51:31Z
[ "python" ]