title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Binary array in python
751,055
<p>How to create big array in python, how efficient creating that</p> <p>in C/C++:</p> <pre><code>byte *data = (byte*)memalloc(10000); </code></pre> <p>or</p> <pre><code>byte *data = new byte[10000]; </code></pre> <p>in python...?</p>
4
2009-04-15T10:21:22Z
751,071
<p>Typically with python, you'd just create a list</p> <pre><code>mylist = [] </code></pre> <p>and use it as an array. Alternatively, I think you might be looking for the array module. See <a href="http://docs.python.org/library/array.html" rel="nofollow">http://docs.python.org/library/array.html</a>.</p>
0
2009-04-15T10:27:30Z
[ "python" ]
Binary array in python
751,055
<p>How to create big array in python, how efficient creating that</p> <p>in C/C++:</p> <pre><code>byte *data = (byte*)memalloc(10000); </code></pre> <p>or</p> <pre><code>byte *data = new byte[10000]; </code></pre> <p>in python...?</p>
4
2009-04-15T10:21:22Z
751,080
<p>Have a look at the <a href="http://docs.python.org/library/array.html">array module</a>:</p> <pre><code>import array array.array('B', [0] * 10000) </code></pre> <p>Instead of passing a list to initialize it, you can pass a generator, which is more memory efficient.</p>
7
2009-04-15T10:29:37Z
[ "python" ]
Binary array in python
751,055
<p>How to create big array in python, how efficient creating that</p> <p>in C/C++:</p> <pre><code>byte *data = (byte*)memalloc(10000); </code></pre> <p>or</p> <pre><code>byte *data = new byte[10000]; </code></pre> <p>in python...?</p>
4
2009-04-15T10:21:22Z
751,087
<p>You can pre-allocate a list with:</p> <pre><code>l = [0] * 10000 </code></pre> <p>which will be slightly faster than .appending to it (as it avoids intermediate reallocations). However, this will generally allocate space for a list of pointers to integer objects, which will be larger than an array of bytes in C.</p> <p>If you need memory efficiency, you could use an array object. ie:</p> <pre><code>import array, itertools a = array.array('b', itertools.repeat(0, 10000)) </code></pre> <p>Note that these may be slightly slower to use in practice, as there is an unboxing process when accessing elements (they must first be converted to a python <code>int</code> object).</p>
6
2009-04-15T10:31:49Z
[ "python" ]
Binary array in python
751,055
<p>How to create big array in python, how efficient creating that</p> <p>in C/C++:</p> <pre><code>byte *data = (byte*)memalloc(10000); </code></pre> <p>or</p> <pre><code>byte *data = new byte[10000]; </code></pre> <p>in python...?</p>
4
2009-04-15T10:21:22Z
751,096
<p>You can efficiently create big array with <strong>array</strong> module, but using it won't be as fast as C. If you intend to do some math, you'd be better off with <strong>numpy.array</strong></p> <p>Check <a href="http://stackoverflow.com/questions/111983/python-array-versus-numpy-array">this question</a> for comparison.</p>
0
2009-04-15T10:37:23Z
[ "python" ]
How do I use the wx.lib.docview package?
751,159
<p>I'm currently working on a simple wxPython app that's essentially document based. So far I've been manually implementing the usual open/save/undo/redo etc etc stuff.</p> <p>It occurred to me that wxPython must have something to help me out and after a bit of searching revealed the <a href="http://www.wxpython.org/docs/api/wx.lib.docview-module.html" rel="nofollow">docview package</a>.</p> <p>At this point though I'm just not quite sure how to hook everything up and get things started. Anyone got any good links or hints about places to start?</p> <p>The docs seems to be a little thin about this and Robin Dunn's wxPython book doesn't really cover this package at all.</p>
2
2009-04-15T11:00:46Z
819,173
<p>You might take a look at the docviewdemo.py from the <a href="http://wxpython.org/download.php" rel="nofollow">wxPython Docs and Demos</a>:</p> <p>on my machine they are located:</p> <ul> <li>C:\Program Files\wxPython2.8 Docs and Demos\samples\pydocview\</li> <li>C:\Program Files\wxPython2.8 Docs and Demos\samples\docview\</li> </ul>
1
2009-05-04T07:52:38Z
[ "python", "user-interface", "wxpython", "docview" ]
How do I use the wx.lib.docview package?
751,159
<p>I'm currently working on a simple wxPython app that's essentially document based. So far I've been manually implementing the usual open/save/undo/redo etc etc stuff.</p> <p>It occurred to me that wxPython must have something to help me out and after a bit of searching revealed the <a href="http://www.wxpython.org/docs/api/wx.lib.docview-module.html" rel="nofollow">docview package</a>.</p> <p>At this point though I'm just not quite sure how to hook everything up and get things started. Anyone got any good links or hints about places to start?</p> <p>The docs seems to be a little thin about this and Robin Dunn's wxPython book doesn't really cover this package at all.</p>
2
2009-04-15T11:00:46Z
1,499,852
<p>In addition to the ones mentioned, there is quite an extensive example docview/pydocview in the samples\ide. If you want it to run you will have to make a few code corrections (I have submitted a ticket that outlines the fixes at trac.wxwidgets.org #11237). It is pretty complex but I found it handy to figure out how to do some more complex things. For example, samples\ide\activegrid\tools\ProjectEditor.py is built from scratch and has undo support etc rather than just relying on a control that does everything for you already. That way you can see how things are supposed to be done at the detailed level. The documentation is rather useless in that regard.</p> <p>If you have decided against using docview/pydocview I have a spreadsheet application built on wxPython that you may find useful as an example. While it does not implement a document view framework it does have some characteristics of it and I've implemented an undo/redo system. Check it out at <a href="http://www.missioncognition.net/pysheet/" rel="nofollow">http://www.missioncognition.net/pysheet/</a> I'm currently working on a pydocview based app so I expect that to be up on my site eventually.</p>
1
2009-09-30T18:22:46Z
[ "python", "user-interface", "wxpython", "docview" ]
Why does this pyd file not import on some computers?
751,339
<p>My python project has a C++ component which is compiled and distributed as a .pyd file inside a Python egg. I've noticed that it seems to be incompatible with only some of our our brand new 64 bit Windows servers. We have 4 (allegedly) identically provisioned machines - each of them runs Windows 2003 server 64 bit edition, but 2 of these machines do not allow me to call functions in the egg.</p> <p>After some experimentation I was able to find a recipe for <a href="http://pastebin.com/m6d6aef7e">producing a reproducible error</a>. The problem seems to occur when Python tries to import the pyd file.</p> <p>I copied the pyd to a temp folder and ran Python.exe from that location, incidentally we are still using the 32bit edition of Python 2.4.4 since none of our libraries have been ported to 64 bit architecture yet. Next I try to import my module (called pyccalyon). The first time I try this I get an error message: </p> <pre><code>"ImportError: DLL load failed: The specified module could not be found" </code></pre> <p>Next time I try this the python interpreter crashes out: no stacktrace at all! </p> <p>Naturally you are suspecting my PYD - the odd thing about this is that it's already in use on thousands of PCs and 10s of other servers, many of which are identical spec'd 64 bit machines. The project is continuously tested both in development and after release, so if this thing were so tinder-box unstable we'd have known about it a very long time ago. This component is considered to be stable code so it's surprising that it's breaking so spectacularly. </p> <p>Any suggestions to what I can do to debug this troublesome library? Crazy ideas welcome at this point because we've exhausted all the sensible ones.</p> <p>Thanks!</p> <p><strong>Update 0</strong>: Okay using Process monitor I was able to compare one 64bit server that fails with another that works just fine. I found that the breakage seems to occur due to a missing DLL, SysWOW64/mscoreee.dll - any idea what this component is and where I can get it? I can refer this back to our IT provisioning people who can install stuff.</p>
6
2009-04-15T11:45:05Z
751,353
<p>Have you tried checking which DLLs that PYD links? You can do that for example with either with <a href="http://www.dependencywalker.com/" rel="nofollow">Dependency Walker</a> or VS's depends.exe.</p>
4
2009-04-15T11:49:07Z
[ "python", "windows" ]
Why does this pyd file not import on some computers?
751,339
<p>My python project has a C++ component which is compiled and distributed as a .pyd file inside a Python egg. I've noticed that it seems to be incompatible with only some of our our brand new 64 bit Windows servers. We have 4 (allegedly) identically provisioned machines - each of them runs Windows 2003 server 64 bit edition, but 2 of these machines do not allow me to call functions in the egg.</p> <p>After some experimentation I was able to find a recipe for <a href="http://pastebin.com/m6d6aef7e">producing a reproducible error</a>. The problem seems to occur when Python tries to import the pyd file.</p> <p>I copied the pyd to a temp folder and ran Python.exe from that location, incidentally we are still using the 32bit edition of Python 2.4.4 since none of our libraries have been ported to 64 bit architecture yet. Next I try to import my module (called pyccalyon). The first time I try this I get an error message: </p> <pre><code>"ImportError: DLL load failed: The specified module could not be found" </code></pre> <p>Next time I try this the python interpreter crashes out: no stacktrace at all! </p> <p>Naturally you are suspecting my PYD - the odd thing about this is that it's already in use on thousands of PCs and 10s of other servers, many of which are identical spec'd 64 bit machines. The project is continuously tested both in development and after release, so if this thing were so tinder-box unstable we'd have known about it a very long time ago. This component is considered to be stable code so it's surprising that it's breaking so spectacularly. </p> <p>Any suggestions to what I can do to debug this troublesome library? Crazy ideas welcome at this point because we've exhausted all the sensible ones.</p> <p>Thanks!</p> <p><strong>Update 0</strong>: Okay using Process monitor I was able to compare one 64bit server that fails with another that works just fine. I found that the breakage seems to occur due to a missing DLL, SysWOW64/mscoreee.dll - any idea what this component is and where I can get it? I can refer this back to our IT provisioning people who can install stuff.</p>
6
2009-04-15T11:45:05Z
751,364
<p>You could try something like <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow">Process Monitor</a>, to watch what DLLs it tries to load. I'd assume that one of the other DLLs it relies on can't be found.</p> <p>Edit: It looks like you've already managed to get some useful info out of it, but I'll clarify how you could reduce the deluge of information that procmon produces.</p> <p>Use the filter function to specify the command line (in this case, require that the command line contains python). This will show you messages only from the process you're interested in. Then you can filter out all success results, so you can see which DLL it's looking for.</p> <p>Obviously there are lots of other things you can filter on, but this is how I've got results in the past. It's a really handy tool for working out what's going on in situations like this.</p> <p>(Tools like depends or DependencyWalker are also good for finding out what DLLs a library relies on - they give the static information while procmon will show you the dynamic view. Both of them can be useful.)</p>
4
2009-04-15T11:53:12Z
[ "python", "windows" ]
Why does this pyd file not import on some computers?
751,339
<p>My python project has a C++ component which is compiled and distributed as a .pyd file inside a Python egg. I've noticed that it seems to be incompatible with only some of our our brand new 64 bit Windows servers. We have 4 (allegedly) identically provisioned machines - each of them runs Windows 2003 server 64 bit edition, but 2 of these machines do not allow me to call functions in the egg.</p> <p>After some experimentation I was able to find a recipe for <a href="http://pastebin.com/m6d6aef7e">producing a reproducible error</a>. The problem seems to occur when Python tries to import the pyd file.</p> <p>I copied the pyd to a temp folder and ran Python.exe from that location, incidentally we are still using the 32bit edition of Python 2.4.4 since none of our libraries have been ported to 64 bit architecture yet. Next I try to import my module (called pyccalyon). The first time I try this I get an error message: </p> <pre><code>"ImportError: DLL load failed: The specified module could not be found" </code></pre> <p>Next time I try this the python interpreter crashes out: no stacktrace at all! </p> <p>Naturally you are suspecting my PYD - the odd thing about this is that it's already in use on thousands of PCs and 10s of other servers, many of which are identical spec'd 64 bit machines. The project is continuously tested both in development and after release, so if this thing were so tinder-box unstable we'd have known about it a very long time ago. This component is considered to be stable code so it's surprising that it's breaking so spectacularly. </p> <p>Any suggestions to what I can do to debug this troublesome library? Crazy ideas welcome at this point because we've exhausted all the sensible ones.</p> <p>Thanks!</p> <p><strong>Update 0</strong>: Okay using Process monitor I was able to compare one 64bit server that fails with another that works just fine. I found that the breakage seems to occur due to a missing DLL, SysWOW64/mscoreee.dll - any idea what this component is and where I can get it? I can refer this back to our IT provisioning people who can install stuff.</p>
6
2009-04-15T11:45:05Z
751,372
<p>Maybe you're missing the C++ runtime/standard-library DLLs on the machines where it doesn't work, and the module is trying to use them?</p>
1
2009-04-15T11:54:28Z
[ "python", "windows" ]
Why does this pyd file not import on some computers?
751,339
<p>My python project has a C++ component which is compiled and distributed as a .pyd file inside a Python egg. I've noticed that it seems to be incompatible with only some of our our brand new 64 bit Windows servers. We have 4 (allegedly) identically provisioned machines - each of them runs Windows 2003 server 64 bit edition, but 2 of these machines do not allow me to call functions in the egg.</p> <p>After some experimentation I was able to find a recipe for <a href="http://pastebin.com/m6d6aef7e">producing a reproducible error</a>. The problem seems to occur when Python tries to import the pyd file.</p> <p>I copied the pyd to a temp folder and ran Python.exe from that location, incidentally we are still using the 32bit edition of Python 2.4.4 since none of our libraries have been ported to 64 bit architecture yet. Next I try to import my module (called pyccalyon). The first time I try this I get an error message: </p> <pre><code>"ImportError: DLL load failed: The specified module could not be found" </code></pre> <p>Next time I try this the python interpreter crashes out: no stacktrace at all! </p> <p>Naturally you are suspecting my PYD - the odd thing about this is that it's already in use on thousands of PCs and 10s of other servers, many of which are identical spec'd 64 bit machines. The project is continuously tested both in development and after release, so if this thing were so tinder-box unstable we'd have known about it a very long time ago. This component is considered to be stable code so it's surprising that it's breaking so spectacularly. </p> <p>Any suggestions to what I can do to debug this troublesome library? Crazy ideas welcome at this point because we've exhausted all the sensible ones.</p> <p>Thanks!</p> <p><strong>Update 0</strong>: Okay using Process monitor I was able to compare one 64bit server that fails with another that works just fine. I found that the breakage seems to occur due to a missing DLL, SysWOW64/mscoreee.dll - any idea what this component is and where I can get it? I can refer this back to our IT provisioning people who can install stuff.</p>
6
2009-04-15T11:45:05Z
751,620
<p>According to <a href="http://support.microsoft.com/kb/316091" rel="nofollow">Microsoft's Knowledgebase</a>, mscoree.dll is part of the .NET Framework. To be exact, it's the Microsoft .NET Runtime Execution Engine.</p> <p>The way to get it would be to (re)install the .NET Framework.</p>
2
2009-04-15T13:10:49Z
[ "python", "windows" ]
Why does this pyd file not import on some computers?
751,339
<p>My python project has a C++ component which is compiled and distributed as a .pyd file inside a Python egg. I've noticed that it seems to be incompatible with only some of our our brand new 64 bit Windows servers. We have 4 (allegedly) identically provisioned machines - each of them runs Windows 2003 server 64 bit edition, but 2 of these machines do not allow me to call functions in the egg.</p> <p>After some experimentation I was able to find a recipe for <a href="http://pastebin.com/m6d6aef7e">producing a reproducible error</a>. The problem seems to occur when Python tries to import the pyd file.</p> <p>I copied the pyd to a temp folder and ran Python.exe from that location, incidentally we are still using the 32bit edition of Python 2.4.4 since none of our libraries have been ported to 64 bit architecture yet. Next I try to import my module (called pyccalyon). The first time I try this I get an error message: </p> <pre><code>"ImportError: DLL load failed: The specified module could not be found" </code></pre> <p>Next time I try this the python interpreter crashes out: no stacktrace at all! </p> <p>Naturally you are suspecting my PYD - the odd thing about this is that it's already in use on thousands of PCs and 10s of other servers, many of which are identical spec'd 64 bit machines. The project is continuously tested both in development and after release, so if this thing were so tinder-box unstable we'd have known about it a very long time ago. This component is considered to be stable code so it's surprising that it's breaking so spectacularly. </p> <p>Any suggestions to what I can do to debug this troublesome library? Crazy ideas welcome at this point because we've exhausted all the sensible ones.</p> <p>Thanks!</p> <p><strong>Update 0</strong>: Okay using Process monitor I was able to compare one 64bit server that fails with another that works just fine. I found that the breakage seems to occur due to a missing DLL, SysWOW64/mscoreee.dll - any idea what this component is and where I can get it? I can refer this back to our IT provisioning people who can install stuff.</p>
6
2009-04-15T11:45:05Z
32,173,541
<p>Just had the same problem and depends.exe showed me that <code>foo.pyd</code> was build with <code>python25.lib</code> instead of <code>python27.lib</code>. So it couldn't find <code>python25.dll</code>.</p>
0
2015-08-24T02:02:34Z
[ "python", "windows" ]
dispatcher python
751,455
<p>hy all, I have the following "wrong" dispatcher:</p> <pre><code>def _load_methods(self): import os, sys, glob sys.path.insert(0, 'modules\commands') for c in glob.glob('modules\commands\Command*.py'): if os.path.isdir(c): continue c = os.path.splitext(c)[0] parts = c.split(os.path.sep ) module, name = '.'.join( parts ), parts[-1:] module = __import__( module, globals(), locals(), name ) _cmdClass = __import__(module).Command for method_name in list_public_methods(_cmdClass): self._methods[method_name] = getattr(_cmdClass(), method_name) sys.path.pop(0) </code></pre> <p>It produces the following error:</p> <p>ImportError: No module named commands.CommandAntitheft</p> <p>where Command*.py is placed into modules\commands\ folder</p> <p>can someone help me?</p> <p>One Possible solution (It works!!!) is:</p> <pre><code> def _load_methods(self): import os, sys, glob, imp for file in glob.glob('modules/commands/Command*.py'): if os.path.isdir(file): continue module = os.path.splitext(file)[0].rsplit(os.sep, 1)[1] fd, filename, desc = imp.find_module(module, ['./modules/commands']) try: _cmdClass = imp.load_module( module, fd, filename, desc).Command finally: fd.close() for method_name in list_public_methods(_cmdClass): self._methods[method_name] = getattr(_cmdClass(), method_name) </code></pre> <p>It still remains all risks suggested by bobince (tanks :-) )but now I'm able to load commands at "runtime"</p>
0
2009-04-15T12:22:08Z
751,712
<blockquote> <p>sys.path.insert(0, 'modules\commands')</p> </blockquote> <p>It's best not to put a relative path into sys.path. If the current directory changes during execution it'll break.</p> <p>Also if you are running from a different directory to the script it won't work. If you want to make it relative to the script's location, use <strong>file</strong>.</p> <p>Also the ‘\’ character should be escaped to ‘\\’ for safety, and really it ought to be using <code>os.path.join()</code> instead of relying on Windows path rules.</p> <pre><code>sys.path.insert(0, os.path.abspath(os.path.join(__file__, 'modules'))) </code></pre> <blockquote> <p>sys.path.pop(0)</p> </blockquote> <p>Dangerous. If another imported script has played with sys.path (and it might), you'll have pulled the wrong path off. Also reloads of your own modules will break. Best leave the path where it is.</p> <blockquote> <p>module, name = '.'.join( parts ), parts[-1:]</p> </blockquote> <p>Remember your path includes the segment ‘modules’. So you're effectively trying to:</p> <pre><code>import modules.commands.CommandSomething </code></pre> <p>but since ‘modules.commands’ is already in the path you added to search what you really want is just:</p> <pre><code>import CommandSomething </code></pre> <blockquote> <p>__import__( module, globals(), locals(), name )</p> </blockquote> <p>Also ‘fromlist’ is a list, so it should be ‘[name]’ if you really want to have it write ‘CommandSomething’ to your local variables. (You almost certainly don't want this; leave the fromlist empty.)</p> <blockquote> <p>_cmdClass = __import__(module).Command</p> </blockquote> <p>Yeah, that won't work, module is a module object and __import__ wants a module name. You already have the module object; why not just “module.Command”?</p> <p>My reaction to all this is simple: <em>Too Much Magic</em>.</p> <p>You're making this overly difficult for yourself and creating a lot of potential problems and fragility by messing around with the internals of the import system. This is tricky stuff even for experienced Python programmers.</p> <p>You would almost certainly be better off using plain old Python modules which you import explicitly. Hard-coding the list of commands is really no great hardship; having all your commands in a package, with __init__.py saying:</p> <pre><code>__all__= ['ThisCommand', 'ThatCommand', 'TheOtherCommand'] </code></pre> <p>may repeat the filenames once, but is much simpler and more robust than a surfeit of magic.</p>
1
2009-04-15T13:33:23Z
[ "python" ]
dispatcher python
751,455
<p>hy all, I have the following "wrong" dispatcher:</p> <pre><code>def _load_methods(self): import os, sys, glob sys.path.insert(0, 'modules\commands') for c in glob.glob('modules\commands\Command*.py'): if os.path.isdir(c): continue c = os.path.splitext(c)[0] parts = c.split(os.path.sep ) module, name = '.'.join( parts ), parts[-1:] module = __import__( module, globals(), locals(), name ) _cmdClass = __import__(module).Command for method_name in list_public_methods(_cmdClass): self._methods[method_name] = getattr(_cmdClass(), method_name) sys.path.pop(0) </code></pre> <p>It produces the following error:</p> <p>ImportError: No module named commands.CommandAntitheft</p> <p>where Command*.py is placed into modules\commands\ folder</p> <p>can someone help me?</p> <p>One Possible solution (It works!!!) is:</p> <pre><code> def _load_methods(self): import os, sys, glob, imp for file in glob.glob('modules/commands/Command*.py'): if os.path.isdir(file): continue module = os.path.splitext(file)[0].rsplit(os.sep, 1)[1] fd, filename, desc = imp.find_module(module, ['./modules/commands']) try: _cmdClass = imp.load_module( module, fd, filename, desc).Command finally: fd.close() for method_name in list_public_methods(_cmdClass): self._methods[method_name] = getattr(_cmdClass(), method_name) </code></pre> <p>It still remains all risks suggested by bobince (tanks :-) )but now I'm able to load commands at "runtime"</p>
0
2009-04-15T12:22:08Z
753,115
<p>Do you actually need to import things as modules? If you're just loading code from arbitrary positions in the filesystem, then rather than fiddling with the module path etc, you could just use <a href="http://docs.python.org/library/functions.html#execfile" rel="nofollow"><code>execfile</code></a>.</p> <p>ie. </p> <pre><code>for file in glob.glob('modules/commands/Command*.py'): if os.path.isdir(file): continue moddict={} execfile(file, moddict) _cmdClass = moddict['Command'] ... </code></pre>
1
2009-04-15T18:41:04Z
[ "python" ]
can a method call be chained to the 'set()' built-in? (and why not?)
751,457
<p>If I try:</p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>set(['three', 'words']) </code></pre> <p>which is what I expect. Whereas If I try: </p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>None </code></pre> <p>Why?</p> <p>I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:</p> <pre><code>KeyError: 'big' </code></pre>
3
2009-04-15T12:23:08Z
751,495
<p>Are you sure that the <code>remove</code> function returns a value?</p>
0
2009-04-15T12:33:33Z
[ "python" ]
can a method call be chained to the 'set()' built-in? (and why not?)
751,457
<p>If I try:</p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>set(['three', 'words']) </code></pre> <p>which is what I expect. Whereas If I try: </p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>None </code></pre> <p>Why?</p> <p>I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:</p> <pre><code>KeyError: 'big' </code></pre>
3
2009-04-15T12:23:08Z
751,497
<p><code>set.remove</code> returns nothing (None).</p> <p>Your code assigns the return value of <code>set.remove</code> to the variable <code>mi_set</code>. Therefore, mi_set is None.</p>
20
2009-04-15T12:33:57Z
[ "python" ]
can a method call be chained to the 'set()' built-in? (and why not?)
751,457
<p>If I try:</p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>set(['three', 'words']) </code></pre> <p>which is what I expect. Whereas If I try: </p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>None </code></pre> <p>Why?</p> <p>I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:</p> <pre><code>KeyError: 'big' </code></pre>
3
2009-04-15T12:23:08Z
751,535
<p>The way to go, in your case, would be to use the <strong>difference</strong> member:</p> <pre><code>&gt;&gt;&gt; a = set(["a", "b", "c"]) &gt;&gt;&gt; a = a.difference(["a"]) &gt;&gt;&gt; print a set(['c', 'b']) </code></pre> <p>The difference is that <strong>remove</strong> acts on the current set (python library object member functions that modify an instance usually return None), whereas <strong>difference</strong> creates and returns a new set.</p>
1
2009-04-15T12:48:02Z
[ "python" ]
can a method call be chained to the 'set()' built-in? (and why not?)
751,457
<p>If I try:</p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>set(['three', 'words']) </code></pre> <p>which is what I expect. Whereas If I try: </p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>None </code></pre> <p>Why?</p> <p>I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:</p> <pre><code>KeyError: 'big' </code></pre>
3
2009-04-15T12:23:08Z
751,576
<p>Why does it return <code>None</code>? Because .remove, .add, etc. return <code>None</code> :) That's it. They do not support chaining.</p> <p><code>set</code> is using methods that change it in place. You could create your own version of set that uses chaining, but that can cause some problems:</p> <pre><code>class chain_set(set): def chain_add(self, x): newself = self.copy() newself.add(x) return newself cs = chain_set([1,2,3,4]) cs.chain_add(5) # chain_set([1, 2, 3, 4, 5]) cs.chain_add(7) # chain_set([1, 2, 3, 4, 7]) cs.chain_add(7).chain_add(8) # chain_set([1, 2, 3, 4, 7, 8]) </code></pre> <p>The problem is - do you expect <code>cs</code> itself to change?</p> <p>Do you always want to modify the original set (might create some hard to find bugs) or do you want to copy the set every time (might be slow with bigger sets). If you know what behaviour you need and you remember about it - just go ahead with your own set implementation.</p>
1
2009-04-15T13:00:11Z
[ "python" ]
can a method call be chained to the 'set()' built-in? (and why not?)
751,457
<p>If I try:</p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>set(['three', 'words']) </code></pre> <p>which is what I expect. Whereas If I try: </p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>None </code></pre> <p>Why?</p> <p>I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:</p> <pre><code>KeyError: 'big' </code></pre>
3
2009-04-15T12:23:08Z
753,944
<p>There is a general convention in python that <em>methods which cause <a href="http://en.wikipedia.org/wiki/Side%5Feffect%5F%28computer%5Fscience%29">side-effects</a> return None</em>. Examples include list.sort, list.append, set.add, set.remove, dict.update, etc.</p> <p>This is essentially to help you avoid bugs. Say you had a set called mi_set. If you could write:</p> <pre><code>mi_set2 = mi_set.remove('small') </code></pre> <p>then a reader might think: "<code>mi_set2</code> is different from <code>mi_set</code>". But this would not be the case! And the confusion might lead to subtle bugs caused by mistakenly sharing data structures. So by returning <code>None</code>, python forces you to remember that methods like those I listed above modify objects, rather than creating new ones.</p> <p>See also long discussion <a href="http://mail.python.org/pipermail/python-list/2004-August/277901.html">here</a>. Although note that methods like <code>sorted()</code> and <code>reversed()</code> have been added since that thread.</p> <p>[note that list.pop is an exception to this rule, for historical reasons – it lets you use a list like a stack. And even then, it returns the object removed, rather than the list.]</p>
8
2009-04-15T22:11:55Z
[ "python" ]
can a method call be chained to the 'set()' built-in? (and why not?)
751,457
<p>If I try:</p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>set(['three', 'words']) </code></pre> <p>which is what I expect. Whereas If I try: </p> <pre><code>mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set </code></pre> <p>I get: </p> <pre><code>None </code></pre> <p>Why?</p> <p>I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:</p> <pre><code>KeyError: 'big' </code></pre>
3
2009-04-15T12:23:08Z
755,136
<p>remove modifies the original set without returning anything (or rather, it returns None). This example shows what happens to the original object when you call remove on it:</p> <pre><code>Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; lst = [1,2,3] &gt;&gt;&gt; s1 = set(lst) &gt;&gt;&gt; s1 {1, 2, 3} &gt;&gt;&gt; s2 = s1.remove(2) # instead of reassigning s1, I save the result of remove to s2 &gt;&gt;&gt; s1 {1, 3} # *** 2 is not an element in the original set *** &gt;&gt;&gt; s2 # s2 is not a set at all! &gt;&gt;&gt; </code></pre> <p>To answer the other part of your question, the exception indicates that remove tried to remove the argument from the set, but couldn't because the argument is not in the set. Conversely, remove returns None to indicate success.</p>
0
2009-04-16T07:50:46Z
[ "python" ]
Parse shell file output with Python
751,557
<p>I have a file with data. The file is the output generated from a shell scripting file:</p> <pre><code>|a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f |3337 </code></pre> <p>How can I get a = 869 from this?</p>
4
2009-04-15T12:55:18Z
751,587
<p>You can also use <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv</a> module with delimiter <code>|</code>.</p>
3
2009-04-15T13:02:19Z
[ "python" ]
Parse shell file output with Python
751,557
<p>I have a file with data. The file is the output generated from a shell scripting file:</p> <pre><code>|a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f |3337 </code></pre> <p>How can I get a = 869 from this?</p>
4
2009-04-15T12:55:18Z
751,596
<p>You could do this:</p> <pre><code>output = {} for line in open("myfile"): parts = line.split('|') output[parts[1].strip()] = parts[2].strip() print output['a'] // prints 869 print output['f'] // prints 3337 </code></pre> <p>Or, using the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv</a> module, as suggested by <a href="#751587" rel="nofollow">Eugene Morozov</a>:</p> <pre><code>import csv output = {} reader = csv.reader(open("C:/output.txt"), delimiter='|') for line in reader: output[line[1].strip()] = line[2].strip() print output['a'] // prints 869 print output['f'] // prints 3337 </code></pre>
9
2009-04-15T13:04:10Z
[ "python" ]
Parse shell file output with Python
751,557
<p>I have a file with data. The file is the output generated from a shell scripting file:</p> <pre><code>|a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f |3337 </code></pre> <p>How can I get a = 869 from this?</p>
4
2009-04-15T12:55:18Z
751,613
<pre><code>lines = file("test.txt").readlines() d = dict([[i.strip() for i in l.split("|")[1:3]] for l in lines if l.strip()]) </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; lines = file("test.txt").readlines() &gt;&gt;&gt; d = dict([[i.strip() for i in l.split("|")[1:3]] for l in lines if l.strip()]) &gt;&gt;&gt; d['a'] '869' </code></pre>
4
2009-04-15T13:09:13Z
[ "python" ]
Parse shell file output with Python
751,557
<p>I have a file with data. The file is the output generated from a shell scripting file:</p> <pre><code>|a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f |3337 </code></pre> <p>How can I get a = 869 from this?</p>
4
2009-04-15T12:55:18Z
751,633
<p>Maybe not the most Pythonic way, but this should work if your shell output is stored in f.txt and you are looking for every line to be processed:</p> <pre><code>h = open("f.txt", "rt") inp = h.readline() while inp: flds = inp.split('|') str = flds[1].strip() + " = " + flds[2].strip() print str inp = h.readline() </code></pre>
0
2009-04-15T13:13:08Z
[ "python" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
752,329
<pre><code>def splitter(A): B = A[0:len(A)//2] C = A[len(A)//2:] return (B,C) </code></pre> <p>I tested, and the double slash is required to force int division in python 3. My original post was correct, although wysiwyg broke in Opera, for some reason.</p>
6
2009-04-15T15:49:40Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
752,330
<pre><code>A = [1,2,3,4,5,6] B = A[:len(A)/2] C = A[len(A)/2:] </code></pre> <p>If you want a function:</p> <pre><code>def split_list(a_list): half = len(a_list)/2 return a_list[:half], a_list[half:] A = [1,2,3,4,5,6] B, C = split_list(A) </code></pre>
85
2009-04-15T15:49:42Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
752,333
<p><code>B,C=A[:len(A)/2],A[len(A)/2:]</code></p>
9
2009-04-15T15:50:08Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
752,553
<p>Using <a href="http://docs.python.org/tutorial/introduction.html#lists" rel="nofollow">list slicing</a>. The syntax is basically <code>my_list[start_index:end_index]</code></p> <pre><code>&gt;&gt;&gt; i = [0,1,2,3,4,5] &gt;&gt;&gt; i[:3] # same as i[0:3] - grabs from first to third index (0-&gt;2) [0, 1, 2] &gt;&gt;&gt; i[3:] # same as i[3:len(i)] - grabs from fourth index to end [3, 4, 5] </code></pre> <p>To get the first half of the list, you slice from the first index to <code>len(i)/2</code>...</p> <pre><code>&gt;&gt;&gt; i[:len(i)/2] [0, 1, 2] </code></pre> <p>..and the swap the values around to get the second half:</p> <pre><code>&gt;&gt;&gt; i[len(i)/2:] [3, 4, 5] </code></pre>
2
2009-04-15T16:28:30Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
752,562
<p>A little more generic solution (you can specify the number of parts you want, not just split 'in half'):</p> <p><strong>EDIT</strong>: updated post to handle odd list lengths</p> <p><strong>EDIT2</strong>: update post again based on Brians informative comments </p> <pre><code>def split_list(alist, wanted_parts=1): length = len(alist) return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] for i in range(wanted_parts) ] A = [0,1,2,3,4,5,6,7,8,9] print split_list(A, wanted_parts=1) print split_list(A, wanted_parts=2) print split_list(A, wanted_parts=8) </code></pre>
44
2009-04-15T16:30:41Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
753,229
<p>While the answers above are more or less correct, you may run into trouble if the size of your array isn't divisible by 2, as the result of <code>a / 2</code>, a being odd, is a float in python 3.0, and in earlier version if you specify <code>from __future__ import division</code> at the beginning of your script. You are in any case better off going for integer division, i.e. <code>a // 2</code>, in order to get "forward" compatibility of your code.</p>
2
2009-04-15T19:03:34Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
2,215,676
<pre><code>f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)] f(A) </code></pre> <p><code>n</code> - the predefined length of result arrays </p>
23
2010-02-07T02:30:56Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
5,750,112
<p>There is an official Python receipe for the more generalized case of splitting an array into smaller arrays of size <code>n</code>.</p> <pre><code>from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --&gt; ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) </code></pre> <p>This code snippet is from the <a href="http://docs.python.org/library/itertools.html" rel="nofollow">python itertools doc page</a>.</p>
3
2011-04-21T21:44:10Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
6,328,533
<p>If you don't care about the order... </p> <pre><code>def split(list): return list[::2], list[1::2] </code></pre> <p><code>list[::2]</code> gets every second element in the list starting from the 0th element.<br> <code>list[1::2]</code> gets every second element in the list starting from the 1st element.</p>
3
2011-06-13T09:11:54Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
11,574,640
<p>Here is a common solution, split arr into count part</p> <pre><code>def split(arr, count): return [arr[i::count] for i in range(count)] </code></pre>
3
2012-07-20T07:17:29Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
11,771,019
<p>With hints from @ChristopheD</p> <pre><code>def line_split(N, K=1): length = len(N) return [N[i*length/K:(i+1)*length/K] for i in range(K)] A = [0,1,2,3,4,5,6,7,8,9] print line_split(A,1) print line_split(A,2) </code></pre>
0
2012-08-02T04:24:25Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
23,148,997
<pre><code>def split(arr, size): arrs = [] while len(arr) &gt; size: pice = arr[:size] arrs.append(pice) arr = arr[size:] arrs.append(arr) return arrs </code></pre> <p>Test:</p> <pre><code>x=[1,2,3,4,5,6,7,8,9,10,11,12,13] print(split(x,5)) </code></pre> <p>result:</p> <pre><code>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]] </code></pre>
5
2014-04-18T06:54:33Z
[ "python", "list", "split" ]
Split list into smaller lists
752,308
<p>I am looking for a way to easily split a python list in half.</p> <p>So that if I have an array:</p> <pre><code>A = [0,1,2,3,4,5] </code></pre> <p>I would be able to get:</p> <pre><code>B = [0,1,2] C = [3,4,5] </code></pre>
57
2009-04-15T15:44:40Z
23,895,329
<p>This is similar to other solutions, but a little faster.</p> <pre><code># Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5]) def split_half(a): half = len(a) &gt;&gt; 1 return a[:half], a[half:] </code></pre>
0
2014-05-27T17:17:30Z
[ "python", "list", "split" ]
Has anyone here tried using the iSeries Python port?
752,349
<p>I found <a href="http://www.iseriespython.com/" rel="nofollow">http://www.iseriespython.com/</a>, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:</p> <p>Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?</p> <p>Does the iSeries database access layer work well, creating usable objects from table definitions?</p>
9
2009-04-15T15:52:06Z
753,006
<p>It sounds like it is would work as expected. Support for other libraries might be pretty limited, though.</p> <p>Timothy Prickett talks about some Python ports for the iSeries in this article:</p> <p><a href="http://www.itjungle.com/tfh/tfh041706-story02.html" rel="nofollow">http://www.itjungle.com/tfh/tfh041706-story02.html</a></p> <p>Also, some discussion popped up in the Python mailing archives:</p> <p><a href="http://mail.python.org/pipermail/python-list/2004-January/245276.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2004-January/245276.html</a></p>
5
2009-04-15T18:13:31Z
[ "python", "ibm-midrange" ]
Has anyone here tried using the iSeries Python port?
752,349
<p>I found <a href="http://www.iseriespython.com/" rel="nofollow">http://www.iseriespython.com/</a>, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:</p> <p>Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?</p> <p>Does the iSeries database access layer work well, creating usable objects from table definitions?</p>
9
2009-04-15T15:52:06Z
753,731
<p>Another place to look is on the mailing list <a href="http://lists.midrange.com/listinfo/midrange-l" rel="nofollow">MIDRANGE-L</a> or search the archives for the list at <a href="http://archive.midrange.com/midrange-l/index.htm" rel="nofollow">midrange.com</a>. I know they have talked about this a while back.</p>
0
2009-04-15T21:08:52Z
[ "python", "ibm-midrange" ]
Has anyone here tried using the iSeries Python port?
752,349
<p>I found <a href="http://www.iseriespython.com/" rel="nofollow">http://www.iseriespython.com/</a>, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:</p> <p>Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?</p> <p>Does the iSeries database access layer work well, creating usable objects from table definitions?</p>
9
2009-04-15T15:52:06Z
788,298
<p>From what I have seen so far, it works pretty well. Note that I'm using iSeries Python 2.3.3. The fact that strings are natively EBCDIC can be a problem; it's definitely one of the reasons many third-party packages won't work as-is, even if they are pure Python. (In some cases they can be tweaked and massaged into working with judicious use of encoding and decoding.) Supposedly 2.5 uses ASCII natively, which would in principle improve compatibility, but I have no way to test this because I'm on a too-old version of OS/400.</p> <p>Partly because of EBCDIC and partly because OS/400 and the QSYS file system are neither Unix-like nor Windows-like, there are some pieces of the standard library that are not implemented or are imperfectly implemented. How badly this would affect you depends on what you're trying to do.</p> <p>On the plus side, the iSeries-specific features work quite well. It's very easy to work with physical files as well as stream files. Calling CL or RPG programs from Python is fairly painless. On balance, I find iSeries Python to be highly usable and very worthwhile.</p> <p><strong>Update:</strong> A lot of work has gone into iSeries Python since this question was asked. <a href="http://sourceforge.net/projects/iseriespython/" rel="nofollow">Version 2.7</a> is now available, meaning it's up-to-date as far as 2.x versions go. A few participants of the <a href="http://www.iseriespython.com/app/ispMain.py/Start?job=Posts&amp;testing=" rel="nofollow">forum</a> are reasonably active and provide amazing support. One of them has gotten Django working on the i. As expected, the move to native ASCII strings solves a lot of the EBCDIC problems and greatly increases compatibility with third-party packages. I enthusiastically recommend iSeries Python 2.7 for anyone on V5R3 or later. (I still strongly recommend iSeries Python 2.3.3 for those who are on earlier versions of the operating system.)</p>
7
2009-04-25T05:35:36Z
[ "python", "ibm-midrange" ]
Has anyone here tried using the iSeries Python port?
752,349
<p>I found <a href="http://www.iseriespython.com/" rel="nofollow">http://www.iseriespython.com/</a>, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:</p> <p>Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?</p> <p>Does the iSeries database access layer work well, creating usable objects from table definitions?</p>
9
2009-04-15T15:52:06Z
2,552,847
<p>I got permission to install iSeries Python on a box about 3 years ago. I found that it worked pretty much as advertised. I contacted the developer and he was very good about answering questions. However, before I could think about using it in production, I had to approach the developer regarding a support contract. That really isn't his gig, so he said no and we scrapped the idea. The main limitation I found is that it is several releases behind Python on other platforms.</p> <p>I have also had very good experience with Jython on the iSeries. Java is completely supported on the iSeries. Theoretically, everything you can do in RPG on the iSeries, you can do in Java, which means you can do it in Jython. I was sending email from an AS/400 (old name for iSeries) via JPython (old name for Jython) and smtplib.py in 1999 or 2000. </p>
3
2010-03-31T12:31:20Z
[ "python", "ibm-midrange" ]
Has anyone here tried using the iSeries Python port?
752,349
<p>I found <a href="http://www.iseriespython.com/" rel="nofollow">http://www.iseriespython.com/</a>, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:</p> <p>Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?</p> <p>Does the iSeries database access layer work well, creating usable objects from table definitions?</p>
9
2009-04-15T15:52:06Z
3,139,913
<p>iSeriesPython is working very well. We are usning it since 2005 (or earlier) in our Development and Production Environments as an utility language, for generating of COBOL source code, generating of PCML interfaces, sending SMS, validating/correcting some data ... etc. With iSeriesPython you can access the iSeries database at 2 ways: using File400 and/or db2 module. You can execute OS/400 commands and you can work with both QSYS.LIB members and IFS stream files. IMHO, iSeries Python is very powerful tool, more better than REXX included with iSeries. Try it!</p>
4
2010-06-29T10:47:07Z
[ "python", "ibm-midrange" ]
Is it safe to rely on condition evaluation order in if statements?
752,373
<p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p> <pre><code>if my_var and 'something' in my_var: #do something </code></pre> <p>*The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.*</p> <p>Or should I use:</p> <pre><code>if my_var: if 'something' in my_var: #do something </code></pre> <p>or </p> <pre><code>try: if 'something' in my_var: #do something except TypeError: pass </code></pre> <p>To rephrase the question, which of the above is the best practice in Python (if any)?</p> <p>Alternatives are welcome!</p>
39
2009-04-15T15:57:19Z
752,390
<p>It's safe to depend on the order of conditionals (<a href="http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not">Python reference here</a>), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.</p> <p>This sort of code pops up in most languages:</p> <pre><code>IF exists(variable) AND variable.doSomething() THEN ... </code></pre>
49
2009-04-15T15:59:25Z
[ "python", "if-statement" ]
Is it safe to rely on condition evaluation order in if statements?
752,373
<p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p> <pre><code>if my_var and 'something' in my_var: #do something </code></pre> <p>*The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.*</p> <p>Or should I use:</p> <pre><code>if my_var: if 'something' in my_var: #do something </code></pre> <p>or </p> <pre><code>try: if 'something' in my_var: #do something except TypeError: pass </code></pre> <p>To rephrase the question, which of the above is the best practice in Python (if any)?</p> <p>Alternatives are welcome!</p>
39
2009-04-15T15:57:19Z
752,392
<p>It's perfectly safe and I do it all the time.</p>
1
2009-04-15T15:59:43Z
[ "python", "if-statement" ]
Is it safe to rely on condition evaluation order in if statements?
752,373
<p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p> <pre><code>if my_var and 'something' in my_var: #do something </code></pre> <p>*The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.*</p> <p>Or should I use:</p> <pre><code>if my_var: if 'something' in my_var: #do something </code></pre> <p>or </p> <pre><code>try: if 'something' in my_var: #do something except TypeError: pass </code></pre> <p>To rephrase the question, which of the above is the best practice in Python (if any)?</p> <p>Alternatives are welcome!</p>
39
2009-04-15T15:57:19Z
752,396
<p>I would go with the try/except, but it depends on what you know about the variable.</p> <p>If you are expecting that the variable will exist most of the time, then a try/except is less operations. If you are expecting the variable to be None most of the time, then an IF statement will be less operations.</p>
1
2009-04-15T16:00:04Z
[ "python", "if-statement" ]
Is it safe to rely on condition evaluation order in if statements?
752,373
<p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p> <pre><code>if my_var and 'something' in my_var: #do something </code></pre> <p>*The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.*</p> <p>Or should I use:</p> <pre><code>if my_var: if 'something' in my_var: #do something </code></pre> <p>or </p> <pre><code>try: if 'something' in my_var: #do something except TypeError: pass </code></pre> <p>To rephrase the question, which of the above is the best practice in Python (if any)?</p> <p>Alternatives are welcome!</p>
39
2009-04-15T15:57:19Z
752,447
<p>Yes it is safe, it's explicitly and very clearly defined in the language reference:</p> <blockquote> <p>The expression <code>x and y</code> first evaluates <code>x</code>; if <code>x</code> is <code>false</code>, its value is returned; otherwise, <code>y</code> is evaluated and the resulting value is returned.</p> <p>The expression <code>x or y</code> first evaluates <code>x</code>; if <code>x</code> is true, its value is returned; otherwise, <code>y</code> is evaluated and the resulting value is returned.</p> </blockquote>
22
2009-04-15T16:08:21Z
[ "python", "if-statement" ]
Is it safe to rely on condition evaluation order in if statements?
752,373
<p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p> <pre><code>if my_var and 'something' in my_var: #do something </code></pre> <p>*The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.*</p> <p>Or should I use:</p> <pre><code>if my_var: if 'something' in my_var: #do something </code></pre> <p>or </p> <pre><code>try: if 'something' in my_var: #do something except TypeError: pass </code></pre> <p>To rephrase the question, which of the above is the best practice in Python (if any)?</p> <p>Alternatives are welcome!</p>
39
2009-04-15T15:57:19Z
955,865
<p>It's not that simple. As a C# dude I am very used to doing something like:</p> <pre><code>if(x != null &amp;&amp; ! string.isnullorempty(x.Name)) { //do something } </code></pre> <p>The above works great and is evaluated as expected. However in VB.Net the following would produce a result you were NOT expecting:</p> <pre><code>If Not x Is Nothing **And** Not String.IsNullOrEmpty(x.Name) Then 'do something End If </code></pre> <p>The above will generate an exception. The correct syntax should be</p> <pre><code>If Not x Is Nothing **AndAlso** Not String.IsNullOrEmpty(x.Name) Then 'do something End If </code></pre> <p>Note the very subtle difference. This had me confused for about 10 minutes (way too long) and is why C# (and other) dudes needs to be very careful when coding in other languages.</p>
1
2009-06-05T13:31:51Z
[ "python", "if-statement" ]
Is it safe to rely on condition evaluation order in if statements?
752,373
<p>Is it bad practice to use the following format when <code>my_var</code> can be None?</p> <pre><code>if my_var and 'something' in my_var: #do something </code></pre> <p>*The issue is that <code>'something' in my_var</code> will throw a TypeError if my_var is None.*</p> <p>Or should I use:</p> <pre><code>if my_var: if 'something' in my_var: #do something </code></pre> <p>or </p> <pre><code>try: if 'something' in my_var: #do something except TypeError: pass </code></pre> <p>To rephrase the question, which of the above is the best practice in Python (if any)?</p> <p>Alternatives are welcome!</p>
39
2009-04-15T15:57:19Z
1,361,992
<p>I may be being a little pedantic here, but I would say the best answer is</p> <pre><code>if my_var is not None and 'something' in my_var: #do something </code></pre> <p>The difference being the explicit check for <code>None</code>, rather than the implicit conversion of <code>my_var</code> to <code>True</code> or <code>False</code>.</p> <p>While I'm sure in your case the distinction isn't important, in the more general case it would be quite possible for the variable to not be <code>None</code> but still evaluate to <code>False</code>, for example an integer value of <code>0</code> or an empty list.</p> <p>So contrary to most of the other posters' assertions that it's safe, I'd say that it's safe as long as you're explicit. If you're not convinced then consider this very contrived class:</p> <pre><code>class Contrived(object): def __contains__(self, s): return True def __nonzero__(self): return False my_var = Contrived() if 'something' in my_var: print "Yes the condition is true" if my_var and 'something' in my_var: print "But this statement won't get reached." if my_var is not None and 'something' in my_var: print "Whereas this one will." </code></pre> <p>Yes I know that's not a realistic example, but variations do happen in real code, especially when <code>None</code> is used to indicate a default function argument.</p>
1
2009-09-01T11:37:32Z
[ "python", "if-statement" ]
Can I compile numpy & scipy as eggs for free on Windows32?
752,482
<p>I've been asked to provide Numpy &amp; Scipy as python egg files. Unfortunately Numpy and Scipy do not make official releases of their product in .egg form for a Win32 platform - that means if I want eggs then I have to compile them myself.</p> <p>At the moment my employer provides Visual Studio.Net 2003, which will compile no version of Numpy later than 1.1.1 - every version released subsequently cannot be compiled with VS2003. </p> <p>What I'd really like is some other compiler I can use, perhaps for free, but at a push as a free time-limited trial... I can use that to compile the eggs. Is anybody aware of another compiler that I can get and use without paying anything and will definitely compile Numpy on Windows?</p> <p><strong>Please only suggest something if you know for a fact that that it will compile Numpy - no speculation!</strong></p> <p>Thanks</p> <p>Notes: I work for an organization which is very sensitive about legal matters, so everything I do has to be totally legit. I've got to do everything according to licensed terms, and will be audited. </p> <p>My environment:</p> <ul> <li>Windows 32</li> <li>Standard C Python 2.4.4</li> </ul>
1
2009-04-15T16:14:35Z
752,536
<p>Try compiling the whole Python stack with <a href="http://www.mingw.org/" rel="nofollow">MinGW32.</a> This is a GCC-Win32 development environment that can be used to build Python and a wide variety of software. You will probably have to compile the whole Python distribution with it. <a href="http://uucode.com/texts/python-mingw/python-mingw.html" rel="nofollow">Here</a> is a guide to compiling Python with MinGW. Note that you will probably have to provide a python distribution that is compiled with MinGW32 as well.</p> <p>If recompiling the Python distro is not a goer I believe that Python 2.4 is compiled using VS2003. You are probably stuck with back-porting Scipy and Numpy to VS2003 or paying a consultant to do it. I would dig out the relevant mailing lists or contact the maintainers and get some view of the effort that would be required to do it. </p> <p>Another alternative would be to upgrade the version of Python to a more recent one but you will probably have to regression test your application and upgrade the version of Visual Studio to 2005 or 2008.</p>
2
2009-04-15T16:24:41Z
[ "python", "windows", "numpy", "scipy" ]
Can I compile numpy & scipy as eggs for free on Windows32?
752,482
<p>I've been asked to provide Numpy &amp; Scipy as python egg files. Unfortunately Numpy and Scipy do not make official releases of their product in .egg form for a Win32 platform - that means if I want eggs then I have to compile them myself.</p> <p>At the moment my employer provides Visual Studio.Net 2003, which will compile no version of Numpy later than 1.1.1 - every version released subsequently cannot be compiled with VS2003. </p> <p>What I'd really like is some other compiler I can use, perhaps for free, but at a push as a free time-limited trial... I can use that to compile the eggs. Is anybody aware of another compiler that I can get and use without paying anything and will definitely compile Numpy on Windows?</p> <p><strong>Please only suggest something if you know for a fact that that it will compile Numpy - no speculation!</strong></p> <p>Thanks</p> <p>Notes: I work for an organization which is very sensitive about legal matters, so everything I do has to be totally legit. I've got to do everything according to licensed terms, and will be audited. </p> <p>My environment:</p> <ul> <li>Windows 32</li> <li>Standard C Python 2.4.4</li> </ul>
1
2009-04-15T16:14:35Z
752,550
<p>You could try <a href="http://gcc.gnu.org/install/specific.html#windows" rel="nofollow">GCC for Windows</a>. GCC is the compiler most often used for compiling Numpy/Scipy (or anything else, really) on Linux, so it seems reasonable that it should work on Windows too. (Never tried it myself, though)</p> <p>And of course it's distributed under the GPL, so there shouldn't be any legal barriers.</p>
1
2009-04-15T16:27:43Z
[ "python", "windows", "numpy", "scipy" ]
Can I compile numpy & scipy as eggs for free on Windows32?
752,482
<p>I've been asked to provide Numpy &amp; Scipy as python egg files. Unfortunately Numpy and Scipy do not make official releases of their product in .egg form for a Win32 platform - that means if I want eggs then I have to compile them myself.</p> <p>At the moment my employer provides Visual Studio.Net 2003, which will compile no version of Numpy later than 1.1.1 - every version released subsequently cannot be compiled with VS2003. </p> <p>What I'd really like is some other compiler I can use, perhaps for free, but at a push as a free time-limited trial... I can use that to compile the eggs. Is anybody aware of another compiler that I can get and use without paying anything and will definitely compile Numpy on Windows?</p> <p><strong>Please only suggest something if you know for a fact that that it will compile Numpy - no speculation!</strong></p> <p>Thanks</p> <p>Notes: I work for an organization which is very sensitive about legal matters, so everything I do has to be totally legit. I've got to do everything according to licensed terms, and will be audited. </p> <p>My environment:</p> <ul> <li>Windows 32</li> <li>Standard C Python 2.4.4</li> </ul>
1
2009-04-15T16:14:35Z
752,551
<p>If you just need the compiler, it is part of the .NET framework.</p> <p>For instance, you can find the 3.5 framework (Which is used be visual studio 2008) in:</p> <pre><code>"C:\Windows\Microsoft.NET\Framework\v3.5" </code></pre>
0
2009-04-15T16:27:58Z
[ "python", "windows", "numpy", "scipy" ]
"Slicing" in Python Expressions documentation
752,602
<p>I don't understand the following part of the Python docs:</p> <p><a href="http://docs.python.org/reference/expressions.html#slicings">http://docs.python.org/reference/expressions.html#slicings</a></p> <p>Is this referring to list slicing ( <code>x=[1,2,3,4]; x[0:2]</code> )..? Particularly the parts referring to ellipsis..</p> <pre><code>slice_item ::= expression | proper_slice | ellipsis </code></pre> <blockquote> <p>The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object.</p> </blockquote>
10
2009-04-15T16:39:42Z
752,693
<p>What happens is this. See <a href="http://docs.python.org/reference/datamodel.html#types">http://docs.python.org/reference/datamodel.html#types</a> and <a href="http://docs.python.org/library/functions.html#slice">http://docs.python.org/library/functions.html#slice</a></p> <blockquote> <p>Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function.</p> <p>Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type.</p> </blockquote> <pre><code>x=[1,2,3,4] x[0:2] </code></pre> <p>The "0:2" is transformed into a <code>Slice</code> object with start of 0, stop of 2 and a step of None.</p> <p>This <code>Slice</code> object is provided to <code>x</code>'s <code>__getitem__</code> method of classes you define.</p> <pre><code>&gt;&gt;&gt; class MyClass( object ): def __getitem__( self, key ): print type(key), key &gt;&gt;&gt; x=MyClass() &gt;&gt;&gt; x[0:2] &lt;type 'slice'&gt; slice(0, 2, None) </code></pre> <p>For the build-in list class, however, a special <code>__getslice__</code> method must be overridden.</p> <pre><code>class MyList( list ): def __getslice__( self, i, j=None, k=None ): # decode various parts of the slice values </code></pre> <p>The ellipsis is a special "ignore this dimension" syntax provided to multi-dimensional slices.</p> <p>Also see <a href="http://docs.python.org/library/itertools.html#itertools.islice">http://docs.python.org/library/itertools.html#itertools.islice</a> for even more information.</p>
7
2009-04-15T16:56:45Z
[ "python", "syntax", "documentation" ]
"Slicing" in Python Expressions documentation
752,602
<p>I don't understand the following part of the Python docs:</p> <p><a href="http://docs.python.org/reference/expressions.html#slicings">http://docs.python.org/reference/expressions.html#slicings</a></p> <p>Is this referring to list slicing ( <code>x=[1,2,3,4]; x[0:2]</code> )..? Particularly the parts referring to ellipsis..</p> <pre><code>slice_item ::= expression | proper_slice | ellipsis </code></pre> <blockquote> <p>The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object.</p> </blockquote>
10
2009-04-15T16:39:42Z
752,895
<p>Defining simple test class that just prints what is being passed:</p> <pre><code>&gt;&gt;&gt; class TestGetitem(object): ... def __getitem__(self, item): ... print type(item), item ... &gt;&gt;&gt; t = TestGetitem() </code></pre> <p>Expression example:</p> <pre><code>&gt;&gt;&gt; t[1] &lt;type 'int'&gt; 1 &gt;&gt;&gt; t[3-2] &lt;type 'int'&gt; 1 &gt;&gt;&gt; t['test'] &lt;type 'str'&gt; test &gt;&gt;&gt; t[t] &lt;class '__main__.TestGetitem'&gt; &lt;__main__.TestGetitem object at 0xb7e9bc4c&gt; </code></pre> <p>Slice example:</p> <pre><code>&gt;&gt;&gt; t[1:2] &lt;type 'slice'&gt; slice(1, 2, None) &gt;&gt;&gt; t[1:'this':t] &lt;type 'slice'&gt; slice(1, 'this', &lt;__main__.TestGetitem object at 0xb7e9bc4c&gt;) </code></pre> <p>Ellipsis example:</p> <pre><code>&gt;&gt;&gt; t[...] &lt;type 'ellipsis'&gt; Ellipsis </code></pre> <p>Tuple with ellipsis and slice:</p> <pre><code>&gt;&gt;&gt; t[...,1:] &lt;type 'tuple'&gt; (Ellipsis, slice(1, None, None)) </code></pre>
11
2009-04-15T17:42:17Z
[ "python", "syntax", "documentation" ]
"Slicing" in Python Expressions documentation
752,602
<p>I don't understand the following part of the Python docs:</p> <p><a href="http://docs.python.org/reference/expressions.html#slicings">http://docs.python.org/reference/expressions.html#slicings</a></p> <p>Is this referring to list slicing ( <code>x=[1,2,3,4]; x[0:2]</code> )..? Particularly the parts referring to ellipsis..</p> <pre><code>slice_item ::= expression | proper_slice | ellipsis </code></pre> <blockquote> <p>The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object.</p> </blockquote>
10
2009-04-15T16:39:42Z
753,260
<p><a href="http://docs.python.org/dev/library/constants.html#Ellipsis">Ellipsis</a> is used mainly by the <a href="http://numpy.scipy.org/">numeric python</a> extension, which adds a multidementional array type. Since there are more than one dimensions, <a href="http://numpy.scipy.org/">slicing</a> becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimentions as well. eg, given a 4x4 array, the top left area would be defined by the slice "[:2,:2]"</p> <pre><code>&gt;&gt;&gt; a array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) &gt;&gt;&gt; a[:2,:2] # top left array([[1, 2], [5, 6]]) </code></pre> <p>Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for dimensions not specified, so for a 3d array, <code>a[...,0]</code> is the same as <code>a[:,:,0]</code> and for 4d, <code>a[:,:,:,0]</code>.</p> <p>Note that the actual Ellipsis literal (...) is not usable outside the slice syntax in python2, though there is a builtin Ellipsis object. This is what is meant by "The conversion of an ellipsis slice item is the built-in Ellipsis object." ie. "<code>a[...]</code>" is effectively sugar for "<code>a[Ellipsis]</code>". In python3, <code>...</code> denotes Ellipsis anywhere, so you can write:</p> <pre><code>&gt;&gt;&gt; ... Ellipsis </code></pre> <p>If you're not using numpy, you can pretty much ignore all mention of Ellipsis. None of the builtin types use it, so really all you have to care about is that lists get passed a single slice object, that contains "<code>start</code>","<code>stop</code>" and "<code>step</code>" members. ie:</p> <pre><code>l[start:stop:step] # proper_slice syntax from the docs you quote. </code></pre> <p>is equivalent to calling:</p> <pre><code>l.__getitem__(slice(start, stop, step)) </code></pre>
15
2009-04-15T19:12:07Z
[ "python", "syntax", "documentation" ]
How to work with unicode in Python
752,998
<p>I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) </code></pre> <p>The actual line of code was </p> <pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>Anyway-I decided that I needed to preface it with an r so I ran this line of code:</p> <pre><code>s=unicodestring.replace(r'\xa0','') </code></pre> <p>It runs without error but I when I look at a slice of s I see that the \xaO is still there</p>
14
2009-04-15T18:11:45Z
753,019
<p>Look at the <a href="http://docs.python.org/library/codecs.html" rel="nofollow">codecs</a> standard library, specifically the <strong>encode</strong> and <strong>decode</strong> methods provided in the Codec base class.</p> <p>There's also a good article <a href="http://boodebr.org/main/python/all-about-python-and-unicode" rel="nofollow">here</a> that puts it all together.</p>
4
2009-04-15T18:17:29Z
[ "python", "string", "unicode", "replace", "unicode-string" ]
How to work with unicode in Python
752,998
<p>I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) </code></pre> <p>The actual line of code was </p> <pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>Anyway-I decided that I needed to preface it with an r so I ran this line of code:</p> <pre><code>s=unicodestring.replace(r'\xa0','') </code></pre> <p>It runs without error but I when I look at a slice of s I see that the \xaO is still there</p>
14
2009-04-15T18:11:45Z
753,027
<p>Just a note regarding HTML cleaning. It is very very hard, since</p> <pre><code>&lt; body &gt; </code></pre> <p>Is a valid way to write HTML. Just an fyi.</p>
1
2009-04-15T18:18:02Z
[ "python", "string", "unicode", "replace", "unicode-string" ]
How to work with unicode in Python
752,998
<p>I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) </code></pre> <p>The actual line of code was </p> <pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>Anyway-I decided that I needed to preface it with an r so I ran this line of code:</p> <pre><code>s=unicodestring.replace(r'\xa0','') </code></pre> <p>It runs without error but I when I look at a slice of s I see that the \xaO is still there</p>
14
2009-04-15T18:11:45Z
753,028
<p>You can convert it to unicode in this way:</p> <pre><code>print u'Hello, \xa0World' # print Hello, World </code></pre>
0
2009-04-15T18:18:07Z
[ "python", "string", "unicode", "replace", "unicode-string" ]
How to work with unicode in Python
752,998
<p>I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) </code></pre> <p>The actual line of code was </p> <pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>Anyway-I decided that I needed to preface it with an r so I ran this line of code:</p> <pre><code>s=unicodestring.replace(r'\xa0','') </code></pre> <p>It runs without error but I when I look at a slice of s I see that the \xaO is still there</p>
14
2009-04-15T18:11:45Z
753,044
<p>may be you should be doing</p> <pre><code>s=unicodestring.replace(u'\xa0',u'') </code></pre>
23
2009-04-15T18:22:48Z
[ "python", "string", "unicode", "replace", "unicode-string" ]
How to work with unicode in Python
752,998
<p>I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) </code></pre> <p>The actual line of code was </p> <pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>Anyway-I decided that I needed to preface it with an r so I ran this line of code:</p> <pre><code>s=unicodestring.replace(r'\xa0','') </code></pre> <p>It runs without error but I when I look at a slice of s I see that the \xaO is still there</p>
14
2009-04-15T18:11:45Z
753,578
<pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>..is trying to create the unicode character <code>\xa0</code>, which is not valid in an ASCII sctring (the default string type in Python until version 3.x)</p> <p>The reason <code>r'\xa0'</code> did not error is because in a raw string, escape sequences have no effect. Rather than trying to encode <code>\xa0</code> into the unicode character, it saw the string as a "literal backslash", "literal x" and so on..</p> <p>The following are the same:</p> <pre><code>&gt;&gt;&gt; r'\xa0' '\\xa0' &gt;&gt;&gt; '\\xa0' '\\xa0' </code></pre> <p>This is something resolved in Python v3, as the default string type is unicode, so you can just do..</p> <pre><code>&gt;&gt;&gt; '\xa0' '\xa0' </code></pre> <blockquote> <p>I am trying to clean all of the HTML out of a string so the final output is a text file</p> </blockquote> <p>I would strongly recommend <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> for this. Writing an HTML cleaning tool is difficult (given how horrible most HTML is), and BeautifulSoup does a great job at both parsing HTML, and dealing with Unicode..</p> <pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup("&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hi&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;") &gt;&gt;&gt; print soup.prettify() &lt;html&gt; &lt;body&gt; &lt;h1&gt; Hi &lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
6
2009-04-15T20:33:03Z
[ "python", "string", "unicode", "replace", "unicode-string" ]
How to work with unicode in Python
752,998
<p>I am trying to clean all of the HTML out of a string so the final output is a text file. I have some some research on the various 'converters' and am starting to lean towards creating my own dictionary for the entities and symbols and running a replace on the string. I am considering this because I want to automate the process and there is a lot of variability in the quality of the underlying html. To begin comparing the speed of my solution and one of the alternatives for example pyparsing I decided to test replace of \xa0 using the string method replace. I get a </p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) </code></pre> <p>The actual line of code was </p> <pre><code>s=unicodestring.replace('\xa0','') </code></pre> <p>Anyway-I decided that I needed to preface it with an r so I ran this line of code:</p> <pre><code>s=unicodestring.replace(r'\xa0','') </code></pre> <p>It runs without error but I when I look at a slice of s I see that the \xaO is still there</p>
14
2009-04-15T18:11:45Z
12,407,255
<p>Instead of this, it's better to use standard python features.</p> <p>For example:</p> <pre><code>string = unicode('Hello, \xa0World', 'utf-8', 'replace') </code></pre> <p>or </p> <pre><code>string = unicode('Hello, \xa0World', 'utf-8', 'ignore') </code></pre> <p>where <code>replace</code> will replace <code>\xa0</code> to <code>\\xa0</code>.</p> <p>But if <code>\xa0</code> is really not meaningful for you and you want to remove it then use <code>ignore</code>.</p>
2
2012-09-13T13:19:28Z
[ "python", "string", "unicode", "replace", "unicode-string" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
753,083
<p>You can use either a different HTML parser (<a href="http://codespeak.net/lxml/" rel="nofollow">like lxml</a>, or <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>) -- one that offers functions to extract just text. Or, you can run a regex on your line string that strips out the tags. See <a href="http://www.amk.ca/python/howto/regex/" rel="nofollow">http://www.amk.ca/python/howto/regex/</a> for more.</p>
2
2009-04-15T18:31:01Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
925,630
<p>I always used this function to strip HTML tags, as it requires only the Python stdlib:</p> <p>On Python 2</p> <pre><code>from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() </code></pre> <p>For Python 3</p> <pre><code>from html.parser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.strict = False self.convert_charrefs= True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() </code></pre> <p><strong>Note</strong>: this works only for 3.1. For 3.2 or above, you need to call the parent class's <strong>init</strong> function. See <a href="http://stackoverflow.com/q/11061058/3416774">Using HTMLParser in Python 3.2</a></p>
282
2009-05-29T11:47:41Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
3,856,657
<p>You can write your own function:</p> <pre><code>def StripTags(text): finished = 0 while not finished: finished = 1 start = text.find("&lt;") if start &gt;= 0: stop = text[start:].find("&gt;") if stop &gt;= 0: text = text[:start] + text[start+stop+1:] finished = 0 return text </code></pre>
1
2010-10-04T15:26:49Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
4,869,782
<p>I haven't thought much about the cases it will miss, but you can do a simple regex:</p> <pre><code>re.sub('&lt;[^&lt;]+?&gt;', '', text) </code></pre> <p>For those that don't understand regex, this searches for a string <code>&lt;...&gt;</code>, where the inner content is made of one or more (<code>+</code>) characters that isn't a <code>&lt;</code>. The <code>?</code> means that it will match the smallest string it can find. For example given <code>&lt;p&gt;Hello&lt;/p&gt;</code>, it will match <code>&lt;'p&gt;</code> and <code>&lt;/p&gt;</code> separately with the <code>?</code>. Without it, it will match the entire string <code>&lt;..Hello..&gt;</code>.</p> <p>If non-tag <code>&lt;</code> appears in html (eg. <code>2 &lt; 3</code>), it should be written as an escape sequence <code>&amp;...</code> anyway so the <code>^&lt;</code> may be unnecessary.</p>
98
2011-02-02T01:09:16Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
4,869,866
<p>This method works flawlessly for me and requires no additional installations:</p> <pre><code>import re import htmlentitydefs def convertentity(m): if m.group(1)=='#': try: return unichr(int(m.group(2))) except ValueError: return '&amp;#%s;' % m.group(2) try: return htmlentitydefs.entitydefs[m.group(2)] except KeyError: return '&amp;%s;' % m.group(2) def converthtml(s): return re.sub(r'&amp;(#?)(.+?);',convertentity,s) html = converthtml(html) html.replace("&amp;nbsp;", " ") ## Get rid of the remnants of certain formatting(subscript,superscript,etc). </code></pre>
-1
2011-02-02T01:23:05Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
7,778,368
<p>I needed a way to strip tags <em>and</em> decode HTML entities to plain text. The following solution is based on Eloff's answer (which I couldn't use because it strips entities).</p> <pre><code>from HTMLParser import HTMLParser import htmlentitydefs class HTMLTextExtractor(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.result = [ ] def handle_data(self, d): self.result.append(d) def handle_charref(self, number): codepoint = int(number[1:], 16) if number[0] in (u'x', u'X') else int(number) self.result.append(unichr(codepoint)) def handle_entityref(self, name): codepoint = htmlentitydefs.name2codepoint[name] self.result.append(unichr(codepoint)) def get_text(self): return u''.join(self.result) def html_to_text(html): s = HTMLTextExtractor() s.feed(html) return s.get_text() </code></pre> <p>A quick test:</p> <pre><code>html = u'&lt;a href="#"&gt;Demo &lt;em&gt;(&amp;not; \u0394&amp;#x03b7;&amp;#956;&amp;#x03CE;)&lt;/em&gt;&lt;/a&gt;' print repr(html_to_text(html)) </code></pre> <p>Result:</p> <pre><code>u'Demo (\xac \u0394\u03b7\u03bc\u03ce)' </code></pre> <p>Error handling:</p> <ul> <li>Invalid HTML structure may cause an <a href="http://docs.python.org/library/htmlparser.html#HTMLParser.HTMLParseError" rel="nofollow">HTMLParseError</a>.</li> <li>Invalid named HTML entities (such as <code>&amp;#apos;</code>, which is valid in XML and XHTML, but not plain HTML) will cause a <code>ValueError</code> exception.</li> <li>Numeric HTML entities specifying code points outside the Unicode range acceptable by Python (such as, on some systems, characters outside the <a href="http://en.wikipedia.org/wiki/Basic_Multilingual_Plane" rel="nofollow">Basic Multilingual Plane</a>) will cause a <code>ValueError</code> exception.</li> </ul> <p><strong>Security note:</strong> Do not confuse HTML stripping (converting HTML into plain text) with HTML sanitizing (converting plain text into HTML). This answer will remove HTML and decode entities into plain text – that does not make the result safe to use in a HTML context.</p> <p>Example: <code>&amp;lt;script&amp;gt;alert("Hello");&amp;lt;/script&amp;gt;</code> will be converted to <code>&lt;script&gt;alert("Hello");&lt;/script&gt;</code>, which is 100% correct behavior, but obviously not sufficient if the resulting plain text is inserted into a HTML page.</p> <p>The rule is not hard: <em>Any time</em> you insert a plain-text string into HTML output, you should <em>always</em> HTML escape it (using <code>cgi.escape(s, True)</code>), even if you "know" that it doesn't contain HTML (e.g. because you stripped HTML content).</p> <p>(However, the OP asked about printing the result to the console, in which case no HTML escaping is needed.)</p>
22
2011-10-15T14:19:55Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
11,086,026
<p>I have used Eloff's answer successfully for Python 3.1 [many thanks!].</p> <p>I upgraded to Python 3.2.3, and ran into errors. </p> <p>The solution, provided <a href="http://stackoverflow.com/questions/11061058/using-htmlparser-in-python-3-2">here</a> thanks to the responder Thomas K, is to insert <code>super().__init__()</code> into the following code:</p> <pre><code>def __init__(self): self.reset() self.fed = [] </code></pre> <p>... in order to make it look like this:</p> <pre><code>def __init__(self): super().__init__() self.reset() self.fed = [] </code></pre> <p>... and it will work for Python 3.2.3.</p> <p>Again, thanks to Thomas K for the fix and for Eloff's original code provided above!</p>
1
2012-06-18T15:29:15Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
13,703,994
<p>If you need to preserve HTML entities (i.e. <code>&amp;amp;</code>), I added "handle_entityref" method to <a href="http://stackoverflow.com/a/925630/1094246">Eloff's answer</a>.</p> <pre><code>from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append('&amp;%s;' % name) def get_data(self): return ''.join(self.fed) def html_to_text(html): s = MLStripper() s.feed(html) return s.get_data() </code></pre>
16
2012-12-04T13:25:42Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
14,464,381
<p>There's a simple way to this:</p> <pre><code>def remove_html_markup(s): tag = False quote = False out = "" for c in s: if c == '&lt;' and not quote: tag = True elif c == '&gt;' and not quote: tag = False elif (c == '"' or c == "'") and tag: quote = not quote elif not tag: out = out + c return out </code></pre> <p>The idea is explained here: <a href="http://youtu.be/2tu9LTDujbw">http://youtu.be/2tu9LTDujbw</a></p> <p>You can see it working here: <a href="http://youtu.be/HPkNPcYed9M?t=35s">http://youtu.be/HPkNPcYed9M?t=35s</a></p> <p>PS - If you're interested in the class(about smart debugging with python) I give you a link: <a href="http://www.udacity.com/overview/Course/cs259/CourseRev/1">http://www.udacity.com/overview/Course/cs259/CourseRev/1</a>. It's free! </p> <p>You're welcome! :)</p>
9
2013-01-22T17:22:29Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
14,603,269
<p>If you want to strip all HTML tags the easiest way I found is using BeautifulSoup:</p> <pre><code>from bs4 import BeautifulSoup # Or from BeautifulSoup import BeautifulSoup def stripHtmlTags(self, htmlTxt): if htmlTxt is None: return None else: return ''.join(BeautifulSoup(htmlTxt).findAll(text=True)) </code></pre> <p>I tried the code of the accepted answer but I was getting "RuntimeError: maximum recursion depth exceeded", which didn't happen with the above block of code.</p>
8
2013-01-30T11:47:49Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
19,730,306
<h2>Short version!</h2> <pre><code>import re, cgi tag_re = re.compile(r'(&lt;!--.*?--&gt;|&lt;[^&gt;]*&gt;)') # Remove well-formed tags, fixing mistakes by legitimate users no_tags = tag_re.sub('', user_input) # Clean up anything else by escaping ready_for_web = cgi.escape(no_tags) </code></pre> <p><a href="https://github.com/mitsuhiko/markupsafe/blob/0.23/markupsafe/__init__.py#L21" rel="nofollow">Regex source: MarkupSafe</a>. Their version handles HTML entities too, while this quick one doesn't.</p> <h2>Why can't I just strip the tags and leave it?</h2> <p>It's one thing to keep people from <code>&lt;i&gt;italicizing&lt;/i&gt;</code> things, without leaving <code>i</code>s floating around. But it's another to take arbitrary input and make it completely harmless. Most of the techniques on this page will leave things like unclosed comments (<code>&lt;!--</code>) and angle-brackets that aren't part of tags (<code>blah &lt;&lt;&lt;&gt;&lt;blah</code>) intact. The HTMLParser version can even leave complete tags in, if they're inside an unclosed comment.</p> <p>What if your template is <code>{{ firstname }} {{ lastname }}</code>? <code>firstname = '&lt;a'</code> and <code>lastname = 'href="http://evil.com/"&gt;'</code> will be let through by every tag stripper on this page (except @Medeiros!), because they're not complete tags on their own. Stripping out normal HTML tags is not enough.</p> <p>Django's <code>strip_tags</code>, an improved (see next heading) version of the top answer to this question, gives the following warning:</p> <blockquote> <p>Absolutely NO guarantee is provided about the resulting string being HTML safe. So NEVER mark safe the result of a <code>strip_tags</code> call without escaping it first, for example with <code>escape()</code>.</p> </blockquote> <p>Follow their advice!</p> <h2>To strip tags with HTMLParser, you have to run it multiple times.</h2> <p><strong>It's easy to circumvent the top answer to this question.</strong></p> <p>Look at this string (<a href="https://www.mehmetince.net/django-strip_tags-bypass-vulnerability-exploit/" rel="nofollow">source and discussion</a>):</p> <pre><code>&lt;img&lt;!-- --&gt; src=x onerror=alert(1);//&gt;&lt;!-- --&gt; </code></pre> <p>The first time HTMLParser sees it, it can't tell that the <code>&lt;img...&gt;</code> is a tag. It looks broken, so HTMLParser doesn't get rid of it. It only takes out the <code>&lt;!-- comments --&gt;</code>, leaving you with</p> <pre><code>&lt;img src=x onerror=alert(1);//&gt; </code></pre> <p>This problem was disclosed to the Django project in March, 2014. Their old <code>strip_tags</code> was essentially the same as the top answer to this question. <a href="https://github.com/django/django/blob/1.7.7/django/utils/html.py#L170" rel="nofollow">Their new version</a> basically runs it in a loop until running it again doesn't change the string:</p> <pre><code># _strip_once runs HTMLParser once, pulling out just the text of all the nodes. def strip_tags(value): """Returns the given HTML with all tags stripped.""" # Note: in typical case this loop executes _strip_once once. Loop condition # is redundant, but helps to reduce number of executions of _strip_once. while '&lt;' in value and '&gt;' in value: new_value = _strip_once(value) if len(new_value) &gt;= len(value): # _strip_once was not able to detect more tags break value = new_value return value </code></pre> <p>Of course, none of this is an issue if you always escape the result of <code>strip_tags()</code>.</p> <p><strong>Update 19 March, 2015</strong>: There was a bug in Django versions before 1.4.20, 1.6.11, 1.7.7, and 1.8c1. These versions could enter an infinite loop in the strip_tags() function. The fixed version is reproduced above. <a href="https://www.djangoproject.com/weblog/2015/mar/18/security-releases/" rel="nofollow">More details here</a>.</p> <h2>Good things to copy or use</h2> <p>My example code doesn't handle HTML entities - the Django and MarkupSafe packaged versions do.</p> <p>My example code is pulled from the excellent <a href="https://pypi.python.org/pypi/MarkupSafe" rel="nofollow">MarkupSafe</a> library for cross-site scripting prevention. It's convenient and fast (with C speedups to its native Python version). It's included in <a href="https://developers.google.com/appengine/docs/python/tools/libraries27" rel="nofollow">Google App Engine</a>, and used by <a href="http://jinja.pocoo.org/docs/intro/#markupsafe-dependency" rel="nofollow">Jinja2 (2.7 and up)</a>, Mako, Pylons, and more. It works easily with Django templates from Django 1.7.</p> <p>Django's strip_tags and other html utilities <em>from a recent version</em> are good, but I find them less convenient than MarkupSafe. They're pretty self-contained, you could copy what you need from <a href="https://github.com/django/django/blob/1.7.1/django/utils/html.py" rel="nofollow">this file</a>.</p> <p>If you need to strip <em>almost</em> all tags, the <a href="http://bleach.readthedocs.org/en/latest/" rel="nofollow">Bleach</a> library is good. You can have it enforce rules like "my users can italicize things, but they can't make iframes."</p> <p>Understand the properties of your tag stripper! Run fuzz tests on it! <a href="https://gist.github.com/tgs/5b6bba6891565762fe39" rel="nofollow">Here is the code</a> I used to do the research for this answer.</p> <p><em>sheepish note</em> - The question itself is about printing to the console, but this is the top Google result for "python strip html from string", so that's why this answer is 99% about the web.</p>
14
2013-11-01T15:51:12Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
21,333,355
<p>The solutions with HTML-Parser are all breakable, if they run only once:</p> <pre><code>html_to_text('&lt;&lt;b&gt;script&gt;alert("hacked")&lt;&lt;/b&gt;/script&gt; </code></pre> <p>results in:</p> <pre><code>&lt;script&gt;alert("hacked")&lt;/script&gt; </code></pre> <p>what you intend to prevent. if you use a HTML-Parser, count the Tags until zero are replaced:</p> <pre><code>from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] self.containstags = False def handle_starttag(self, tag, attrs): self.containstags = True def handle_data(self, d): self.fed.append(d) def has_tags(self): return self.containstags def get_data(self): return ''.join(self.fed) def strip_tags(html): must_filtered = True while ( must_filtered ): s = MLStripper() s.feed(html) html = s.get_data() must_filtered = s.has_tags() return html </code></pre>
1
2014-01-24T12:58:15Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
31,869,361
<p>This is a quick fix and can be even more optimized but it will work fine. This code will replace all non empty tags with "" and strips all html tags form a given input text .You can run it using ./file.py input output</p> <pre><code> #!/usr/bin/python import sys def replace(strng,replaceText): rpl = 0 while rpl &gt; -1: rpl = strng.find(replaceText) if rpl != -1: strng = strng[0:rpl] + strng[rpl + len(replaceText):] return strng lessThanPos = -1 count = 0 listOf = [] try: #write File writeto = open(sys.argv[2],'w') #read file and store it in list f = open(sys.argv[1],'r') for readLine in f.readlines(): listOf.append(readLine) f.close() #remove all tags for line in listOf: count = 0; lessThanPos = -1 lineTemp = line for char in lineTemp: if char == "&lt;": lessThanPos = count if char == "&gt;": if lessThanPos &gt; -1: if line[lessThanPos:count + 1] != '&lt;&gt;': lineTemp = replace(lineTemp,line[lessThanPos:count + 1]) lessThanPos = -1 count = count + 1 lineTemp = lineTemp.replace("&amp;lt","&lt;") lineTemp = lineTemp.replace("&amp;gt","&gt;") writeto.write(lineTemp) writeto.close() print "Write To --- &gt;" , sys.argv[2] except: print "Help: invalid arguments or exception" print "Usage : ",sys.argv[0]," inputfile outputfile" </code></pre>
1
2015-08-07T03:45:42Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
34,532,382
<p>Why all of you do it the hard way? You can use BeautifulSoup <code>get_text()</code> feature.</p> <pre><code>from bs4 import BeautifulSoup text = ''' &lt;td&gt;&lt;a href="http://www.fakewebsite.com"&gt;Please can you strip me?&lt;/a&gt; &lt;br/&gt;&lt;a href="http://www.fakewebsite.com"&gt;I am waiting....&lt;/a&gt; &lt;/td&gt; ''' soup = BeautifulSoup(text) print(soup.get_text()) </code></pre>
1
2015-12-30T15:31:13Z
[ "python", "html" ]
Strip HTML from strings in Python
753,052
<pre><code>from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line </code></pre> <p>When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds <code>'&lt;a href="whatever.com"&gt;some text&lt;/a&gt;'</code>, it will only print 'some text', <code>'&lt;b&gt;hello&lt;/b&gt;'</code> prints 'hello', etc. How would one go about doing this?</p>
166
2009-04-15T18:24:26Z
34,564,725
<p>I'm parsing Github readmes and I find that the following really works well:</p> <pre><code>import re import lxml.html def strip_markdown(x): links_sub = re.sub(r'\[(.+)\]\([^\)]+\)', r'\1', x) bold_sub = re.sub(r'\*\*([^*]+)\*\*', r'\1', links_sub) emph_sub = re.sub(r'\*([^*]+)\*', r'\1', bold_sub) return emph_sub def strip_html(x): return lxml.html.fromstring(x).text_content() if x else '' </code></pre> <p>And then</p> <pre><code>readme = """&lt;img src="https://raw.githubusercontent.com/kootenpv/sky/master/resources/skylogo.png" /&gt; sky is a web scraping framework, implemented with the latest python versions in mind (3.4+). It uses the asynchronous `asyncio` framework, as well as many popular modules and extensions. Most importantly, it aims for **next generation** web crawling where machine intelligence is used to speed up the development/maintainance/reliability of crawling. It mainly does this by considering the user to be interested in content from *domains*, not just a collection of *single pages* ([templating approach](#templating-approach)).""" strip_markdown(strip_html(readme)) </code></pre> <p>Removes all markdown and html correctly. </p>
0
2016-01-02T10:10:52Z
[ "python", "html" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
753,832
<p>Well, now I'm using ImageMagick. I save my frames as PNG files and then invoke ImageMagick's convert.exe from Python to create an animated GIF. The nice thing about this approach is I can specify a frame duration for each frame individually. Unfortunately this depends on ImageMagick being installed on the machine. They have a Python wrapper but it looks pretty crappy and unsupported. Still open to other suggestions.</p>
29
2009-04-15T21:34:42Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
753,979
<p>It's not a python library, but mencoder can do that: <a href="http://www.mplayerhq.hu/DOCS/HTML/en/menc-feat-enc-images.html" rel="nofollow">Encoding from multiple input image files</a>. You can execute mencoder from python like this:</p> <pre><code>import os os.system("mencoder ...") </code></pre>
4
2009-04-15T22:24:43Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
777,713
<p>Have you tried <a href="http://pymedia.org/" rel="nofollow">PyMedia</a>? I am not 100% sure but it looks like <a href="http://pymedia.org/tut/src/make%5Fvideo.py.html" rel="nofollow">this tutorial example</a> targets your problem.</p>
4
2009-04-22T15:08:02Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
1,204,455
<p>To create a video, you could use <a href="http://sourceforge.net/projects/opencvlibrary/">opencv</a>,</p> <pre><code>#load your frames frames = ... #create a video writer writer = cvCreateVideoWriter(filename, -1, fps, frame_size, is_color=1) #and write your frames in a loop if you want cvWriteFrame(writer, frames[i]) </code></pre>
17
2009-07-30T04:29:45Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
2,376,032
<p>As of June 2009 the originally cited blog post has a method to create animated GIFs <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/#comment-197921" rel="nofollow">in the comments</a>. Download the script <a href="https://pypi.python.org/pypi/images2gif" rel="nofollow">images2gif.py</a> (formerly <a href="http://sites.google.com/site/almarklein/files-1/images2gif.py" rel="nofollow">images2gif.py</a>, update courtesy of @geographika).</p> <p>Then, to reverse the frames in a gif, for instance:</p> <pre><code>#!/usr/bin/env python from PIL import Image, ImageSequence import sys, os filename = sys.argv[1] im = Image.open(filename) original_duration = im.info['duration'] frames = [frame.copy() for frame in ImageSequence.Iterator(im)] frames.reverse() from images2gif import writeGif writeGif("reverse_" + os.path.basename(filename), frames, duration=original_duration/1000.0, dither=0) </code></pre>
38
2010-03-04T00:13:13Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
10,376,713
<p>I used <a href="http://sites.google.com/site/almarklein/files-1/images2gif.py">images2gif.py</a> which was easy to use. It did seem to double the file size though..</p> <p>26 110kb PNG files, I expected 26*110kb = 2860kb, but my_gif.GIF was 5.7mb</p> <p>Also because the GIF was 8bit, the nice png's became a little fuzzy in the GIF</p> <p>Here is the code I used:</p> <pre><code>__author__ = 'Robert' from images2gif import writeGif from PIL import Image import os file_names = sorted((fn for fn in os.listdir('.') if fn.endswith('.png'))) #['animationframa.png', 'animationframb.png', 'animationframc.png', ...] " images = [Image.open(fn) for fn in file_names] print writeGif.__doc__ # writeGif(filename, images, duration=0.1, loops=0, dither=1) # Write an animated gif from the specified images. # images should be a list of numpy arrays of PIL images. # Numpy images of type float should have pixels between 0 and 1. # Numpy images of other types are expected to have values between 0 and 255. #images.extend(reversed(images)) #infinit loop will go backwards and forwards. filename = "my_gif.GIF" writeGif(filename, images, duration=0.2) #54 frames written # #Process finished with exit code 0 </code></pre> <p>Here are 3 of the 26 frames:</p> <p><img src="http://i.stack.imgur.com/4cZ7A.gif" alt="Here are 3 of the 26 frames"></p> <p>shrinking the images reduced the size:</p> <pre><code>size = (150,150) for im in images: im.thumbnail(size, Image.ANTIALIAS) </code></pre> <p><img src="http://i.stack.imgur.com/Sb15U.gif" alt="smaller gif"></p>
23
2012-04-29T22:51:44Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
12,092,932
<p>The matplotlib user manual has a solution example using mencoder.</p> <p><a href="http://matplotlib.sourceforge.net/faq/howto_faq.html#make-a-movie" rel="nofollow">http://matplotlib.sourceforge.net/faq/howto_faq.html#make-a-movie</a></p>
2
2012-08-23T13:38:49Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
28,275,187
<p>The task can be completed by running the two line python script from the same folder as the sequence of picture files. For png formatted files the script is - </p> <pre><code>from scitools.std import movie movie('*.png',fps=1,output_file='thisismygif.gif') </code></pre>
2
2015-02-02T10:07:11Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
32,978,565
<p>Old question, lots of good answers, but there might still be interest in another alternative...</p> <p>The <code>numpngw</code> module that I recently put up on github (<a href="https://github.com/WarrenWeckesser/numpngw" rel="nofollow">https://github.com/WarrenWeckesser/numpngw</a>) can write animated PNG files from numpy arrays. (<em>Update</em>: <code>numpngw</code> is now on pypi: <a href="https://pypi.python.org/pypi/numpngw" rel="nofollow">https://pypi.python.org/pypi/numpngw</a>.)</p> <p>For example, this script:</p> <pre><code>import numpy as np import numpngw img0 = np.zeros((64, 64, 3), dtype=np.uint8) img0[:32, :32, :] = 255 img1 = np.zeros((64, 64, 3), dtype=np.uint8) img1[32:, :32, 0] = 255 img2 = np.zeros((64, 64, 3), dtype=np.uint8) img2[32:, 32:, 1] = 255 img3 = np.zeros((64, 64, 3), dtype=np.uint8) img3[:32, 32:, 2] = 255 seq = [img0, img1, img2, img3] for img in seq: img[16:-16, 16:-16] = 127 img[0, :] = 127 img[-1, :] = 127 img[:, 0] = 127 img[:, -1] = 127 numpngw.write_apng('foo.png', seq, delay=250, use_palette=True) </code></pre> <p>creates:</p> <p><a href="http://i.stack.imgur.com/TKR5R.png" rel="nofollow"><img src="http://i.stack.imgur.com/TKR5R.png" alt="animated png"></a></p> <p>You'll need a browser that supports animated PNG to see the animation. Firefox does, Safari doesn't, and Chrome has a plugin for it.</p>
2
2015-10-06T19:55:45Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
34,555,939
<p>With windows7, python2.7, opencv 3.0, the following works for me:</p> <pre><code>import cv2 import os vvw = cv2.VideoWriter('mymovie.avi',cv2.VideoWriter_fourcc('X','V','I','D'),24,(640,480)) frameslist = os.listdir('.\\frames') howmanyframes = len(frameslist) print('Frames count: '+str(howmanyframes)) #just for debugging for i in range(0,howmanyframes): print(i) theframe = cv2.imread('.\\frames\\'+frameslist[i]) vvw.write(theframe) </code></pre>
4
2016-01-01T12:02:05Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
35,943,809
<p>I'd recommend not using images2gif from visvis because it has problems with PIL/Pillow and is not actively maintained (I should know, because I am the author).</p> <p>Instead, please use <a href="http://imageio.github.io">imageio</a>, which was developed to solve this problem and more, and is intended to stay.</p> <p>Quick and dirty solution:</p> <pre><code>import imageio images = [] for filename in filenames: images.append(imageio.imread(filename)) imageio.mimsave('/path/to/movie.gif', images) </code></pre> <p>For longer movies, use the streaming approach:</p> <pre><code>import imageio with imageio.get_writer('/path/to/movie.gif', mode='I') as writer: for filename in filenames: image = imageio.imread(filename) writer.append_data(image) </code></pre>
23
2016-03-11T15:19:07Z
[ "python", "video", "wxpython", "animated-gif" ]
Programmatically generate video or animated GIF in Python?
753,190
<p>I have a series of images that I want to create a video from. Ideally I could specify a frame duration for each frame but a fixed frame rate would be fine too. I'm doing this in wxPython, so I can render to a wxDC or I can save the images to files, like PNG. Is there a Python library that will allow me to create either a video (AVI, MPG, etc) or an animated GIF from these frames?</p> <p>Edit: I've already tried PIL and it doesn't seem to work. Can someone correct me with this conclusion or suggest another toolkit? This link seems to backup my conclusion regarding PIL: <a href="http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/">http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/</a></p>
83
2009-04-15T18:57:14Z
37,758,902
<p>Like Warren said <em>last year</em>, this is an old question. Since people still seem to be viewing the page, I'd like to redirect them to a more modern solution. Like blakev said <a href="http://stackoverflow.com/questions/24688802/saving-an-animated-gif-in-pillow">here</a>, there is a Pillow example on <a href="https://github.com/python-pillow/Pillow/blob/master/Scripts/gifmaker.py" rel="nofollow">github</a>.</p> <pre><code> import ImageSequence import Image import gifmaker sequence = [] im = Image.open(....) # im is your original image frames = [frame.copy() for frame in ImageSequence.Iterator(im)] # write GIF animation fp = open("out.gif", "wb") gifmaker.makedelta(fp, frames) fp.close() </code></pre>
1
2016-06-11T00:46:10Z
[ "python", "video", "wxpython", "animated-gif" ]
Accessing the class that owns a decorated method from the decorator
753,537
<p>I'm writing a decorator for methods that must inspect the parent methods (the methods of the same name in the parents of the class in which I'm decorating).</p> <p>Example (from the fourth example of <a href="http://www.python.org/dev/peps/pep-0318/#examples" rel="nofollow" title="here">PEP 318</a>):</p> <pre><code>def returns(rtype): def check_returns(f): def new_f(*args, **kwds): result = f(*args, **kwds) assert isinstance(result, rtype), \ "return value %r does not match %s" % (result,rtype) return result new_f.func_name = f.func_name # here I want to reach the class owning the decorated method f, # it should give me the class A return new_f return check_returns class A(object): @returns(int) def compute(self, value): return value * 3 </code></pre> <p>So I'm looking for the code to type in place of <strong># here I want...</strong></p> <p>Thanks.</p>
4
2009-04-15T20:23:35Z
753,617
<blockquote> <p>here I want to reach the class owning the decorated method f</p> </blockquote> <p>You can't because at the point of decoration, no class owns the method f.</p> <pre><code>class A(object): @returns(int) def compute(self, value): return value * 3 </code></pre> <p>Is the same as saying:</p> <pre><code>class A(object): pass @returns(int) def compute(self, value): return value*3 A.compute= compute </code></pre> <p>Clearly, the <code>returns()</code> decorator is built before the function is assigned to an owner class.</p> <p>Now when you write a function to a class (either inline, or explicitly like this) it becomes an unbound method object. <em>Now</em> it has a reference to its owner class, which you can get by saying:</p> <pre><code>&gt;&gt;&gt; A.compute.im_class &lt;class '__main__.A'&gt; </code></pre> <p>So you can read f.im_class inside ‘new_f’, which is executed after the assignment, but not in the decorator itself.</p> <p>(And even then it's a bit ugly relying on a CPython implementation detail if you don't need to. I'm not quite sure what you're trying to do, but things involving “get the owner class” are often doable using metaclasses.)</p>
6
2009-04-15T20:40:03Z
[ "python", "decorator" ]
Accessing the class that owns a decorated method from the decorator
753,537
<p>I'm writing a decorator for methods that must inspect the parent methods (the methods of the same name in the parents of the class in which I'm decorating).</p> <p>Example (from the fourth example of <a href="http://www.python.org/dev/peps/pep-0318/#examples" rel="nofollow" title="here">PEP 318</a>):</p> <pre><code>def returns(rtype): def check_returns(f): def new_f(*args, **kwds): result = f(*args, **kwds) assert isinstance(result, rtype), \ "return value %r does not match %s" % (result,rtype) return result new_f.func_name = f.func_name # here I want to reach the class owning the decorated method f, # it should give me the class A return new_f return check_returns class A(object): @returns(int) def compute(self, value): return value * 3 </code></pre> <p>So I'm looking for the code to type in place of <strong># here I want...</strong></p> <p>Thanks.</p>
4
2009-04-15T20:23:35Z
754,066
<p>As <a href="http://stackoverflow.com/questions/753537/accessing-the-class-that-owns-a-decorated-method-from-the-decorator/753617#753617">bobince said it</a>, you can't access the surrounding class, because at the time the decorator is invoked, the class does not exist yet. If you need access to the full dictionary of the class and the bases, you should consider a <a href="http://docs.python.org/dev/reference/datamodel.html?highlight=metaclass#__metaclass__" rel="nofollow"><em>metaclass</em></a>:</p> <blockquote> <p><code>__metaclass__</code></p> <p>This variable can be any callable accepting arguments for name, bases, and dict. Upon class creation, the callable is used instead of the built-in type().</p> </blockquote> <p>Basically, we convert the <code>returns</code> decorator into something that just tells the metaclass to do some magic on class construction:</p> <pre><code>class CheckedReturnType(object): def __init__(self, meth, rtype): self.meth = meth self.rtype = rtype def returns(rtype): def _inner(f): return CheckedReturnType(f, rtype) return _inner class BaseInspector(type): def __new__(mcs, name, bases, dct): for obj_name, obj in dct.iteritems(): if isinstance(obj, CheckedReturnType): # do your wrapping &amp; checking here, base classes are in bases # reassign to dct return type.__new__(mcs, name, bases, dct) class A(object): __metaclass__ = BaseInspector @returns(int) def compute(self, value): return value * 3 </code></pre> <p>Mind that I have not tested this code, please leave comments if I should update this.</p> <p>There are some <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">articles on metaclasses</a> by the highly recommendable David Mertz, which you might find interesting in this context.</p>
6
2009-04-15T22:51:32Z
[ "python", "decorator" ]
Inheritance and Overriding __init__ in python
753,640
<p>I was reading 'Dive Into Python' and in the chapter on classes it gives this example:</p> <pre><code>class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename </code></pre> <p>The author then says that if you want to override the <code>__init__</code> method, you must explicitly call the parent <code>__init__</code> with the correct parameters. </p> <ol> <li>What if that <code>FileInfo</code> class had more than one ancestor class?<br> <ul> <li>Do I have to explicitly call all of the ancestor classes' <code>__init__</code> methods? </li> </ul></li> <li>Also, do I have to do this to any other method I want to override?</li> </ol>
84
2009-04-15T20:45:46Z
753,654
<p>If the FileInfo class has more than one ancestor class then you should definitely call all of their __init__() functions. You should also do the same for the __del__() function, which is a destructor.</p>
3
2009-04-15T20:49:08Z
[ "python", "override", "superclass" ]
Inheritance and Overriding __init__ in python
753,640
<p>I was reading 'Dive Into Python' and in the chapter on classes it gives this example:</p> <pre><code>class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename </code></pre> <p>The author then says that if you want to override the <code>__init__</code> method, you must explicitly call the parent <code>__init__</code> with the correct parameters. </p> <ol> <li>What if that <code>FileInfo</code> class had more than one ancestor class?<br> <ul> <li>Do I have to explicitly call all of the ancestor classes' <code>__init__</code> methods? </li> </ul></li> <li>Also, do I have to do this to any other method I want to override?</li> </ol>
84
2009-04-15T20:45:46Z
753,657
<p>The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclass built-in classes.</p> <p>It looks like this nowadays.</p> <pre><code>class FileInfo(dict): """store file metadata""" def __init__(self, filename=None): super( FileInfo, self ).__init__() self["name"] = filename </code></pre> <p>Note the following.</p> <ol> <li><p>We can directly subclass built-in classes, like <code>dict</code>, <code>list</code>, <code>tuple</code>, etc.</p></li> <li><p>The <code>super</code> function handles tracking down this class's superclasses and calling functions in them appropriately.</p></li> </ol>
108
2009-04-15T20:49:52Z
[ "python", "override", "superclass" ]
Inheritance and Overriding __init__ in python
753,640
<p>I was reading 'Dive Into Python' and in the chapter on classes it gives this example:</p> <pre><code>class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename </code></pre> <p>The author then says that if you want to override the <code>__init__</code> method, you must explicitly call the parent <code>__init__</code> with the correct parameters. </p> <ol> <li>What if that <code>FileInfo</code> class had more than one ancestor class?<br> <ul> <li>Do I have to explicitly call all of the ancestor classes' <code>__init__</code> methods? </li> </ul></li> <li>Also, do I have to do this to any other method I want to override?</li> </ol>
84
2009-04-15T20:45:46Z
753,661
<p>Yes, you must call <code>__init__</code> for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.</p>
2
2009-04-15T20:50:35Z
[ "python", "override", "superclass" ]
Inheritance and Overriding __init__ in python
753,640
<p>I was reading 'Dive Into Python' and in the chapter on classes it gives this example:</p> <pre><code>class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename </code></pre> <p>The author then says that if you want to override the <code>__init__</code> method, you must explicitly call the parent <code>__init__</code> with the correct parameters. </p> <ol> <li>What if that <code>FileInfo</code> class had more than one ancestor class?<br> <ul> <li>Do I have to explicitly call all of the ancestor classes' <code>__init__</code> methods? </li> </ul></li> <li>Also, do I have to do this to any other method I want to override?</li> </ol>
84
2009-04-15T20:45:46Z
753,705
<p>You don't really <em>have</em> to call the <code>__init__</code> methods of the base class(es), but you usually <em>want</em> to do it because the base classes will do some important initializations there that are needed for rest of the classes methods to work.</p> <p>For other methods it depends on your intentions. If you just want to add something to the base classes behavior you will want to call the base classes method additionally to your own code. If you want to fundamentally change the behavior, you might not call the base class' method and implement all the functionality directly in the derived class.</p>
8
2009-04-15T21:00:40Z
[ "python", "override", "superclass" ]
Inheritance and Overriding __init__ in python
753,640
<p>I was reading 'Dive Into Python' and in the chapter on classes it gives this example:</p> <pre><code>class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename </code></pre> <p>The author then says that if you want to override the <code>__init__</code> method, you must explicitly call the parent <code>__init__</code> with the correct parameters. </p> <ol> <li>What if that <code>FileInfo</code> class had more than one ancestor class?<br> <ul> <li>Do I have to explicitly call all of the ancestor classes' <code>__init__</code> methods? </li> </ul></li> <li>Also, do I have to do this to any other method I want to override?</li> </ol>
84
2009-04-15T20:45:46Z
11,055,691
<p>In each class that you need to inherit from, you can run a loop of each class that needs init'd upon initiation of the child class...an example that can copied might be better understood...</p> <pre><code>class Female_Grandparent: def __init__(self): self.grandma_name = 'Grandma' class Male_Grandparent: def __init__(self): self.grandpa_name = 'Grandpa' class Parent(Female_Grandparent, Male_Grandparent): def __init__(self): Female_Grandparent.__init__(self) Male_Grandparent.__init__(self) self.parent_name = 'Parent Class' class Child(Parent): def __init__(self): Parent.__init__(self) #---------------------------------------------------------------------------------------# for cls in Parent.__bases__: # This block grabs the classes of the child cls.__init__(self) # class (which is named 'Parent' in this case), # and iterates through them, initiating each one. # The result is that each parent, of each child, # is automatically handled upon initiation of the # dependent class. WOOT WOOT! :D #---------------------------------------------------------------------------------------# g = Female_Grandparent() print g.grandma_name p = Parent() print p.grandma_name child = Child() print child.grandma_name </code></pre>
14
2012-06-15T17:43:42Z
[ "python", "override", "superclass" ]
How do you order lists in the same way QuerySets are ordered in Django?
753,687
<p>I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort method on the list the order is different from the one I want. Is there a way to sort a list of instances of a model such that the order is equal to that specified in the model definition?</p>
1
2009-04-15T20:57:34Z
753,788
<p>The answer to your question is varying degrees of yes, with some manual requirements. If by <code>list</code> you mean a <code>queryset</code> that has been formed by some complicated query, then, sure:</p> <pre><code>queryset.order_by(ClassName.Meta.ordering) </code></pre> <p>or</p> <pre><code>queryset.order_by(instance._meta.ordering) </code></pre> <p>or</p> <pre><code>queryset.order_by("fieldname") #If you like being manual </code></pre> <p>If you're not working with a queryset, then of course you can still sort, the same way anyone sorts complex objects in python:</p> <ul> <li>Comparators</li> <li>Specifying keys</li> <li>Decorate/Sort/Undecorate</li> </ul> <p><a href="http://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">See the python wiki for a detailed explanation of all three.</a></p>
3
2009-04-15T21:23:23Z
[ "python", "django", "django-models" ]
How do you order lists in the same way QuerySets are ordered in Django?
753,687
<p>I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort method on the list the order is different from the one I want. Is there a way to sort a list of instances of a model such that the order is equal to that specified in the model definition?</p>
1
2009-04-15T20:57:34Z
756,132
<p>Not automatically, but with a bit of work, yes. You need to define a comparator function (or <strong>cmp</strong> method on the model class) that can compare two model instances according to the relevant attribute. For instance:</p> <pre><code>class Dated(models.Model): ... created = models.DateTimeField(default=datetime.now) class Meta: ordering = ('created',) def __cmp__(self, other): try: return cmp(self.created, other.created) except AttributeError: return cmp(self.created, other) </code></pre>
3
2009-04-16T13:31:44Z
[ "python", "django", "django-models" ]
How do you order lists in the same way QuerySets are ordered in Django?
753,687
<p>I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort method on the list the order is different from the one I want. Is there a way to sort a list of instances of a model such that the order is equal to that specified in the model definition?</p>
1
2009-04-15T20:57:34Z
758,263
<p>Building on Carl's answer, you could easily add the ability to use all the ordering fields and even detect the ones that are in reverse order.</p> <pre><code>class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birthday = date = models.DateField() class Meta: ordering = ['last_name', 'first_name'] def __cmp__(self, other): for order in self._meta.ordering: if order.startswith('-'): order = order[1:] mode = -1 else: mode = 1 if hasattr(self, order) and hasattr(other, order): result = mode * cmp(getattr(self, order), getattr(other, order)) if result: return result return 0 </code></pre>
2
2009-04-16T22:17:51Z
[ "python", "django", "django-models" ]
Need to build (or otherwise obtain) python-devel 2.3 and add to LD_LIBRARY_PATH
753,749
<p>I am supporting an application with a hard dependency on python-devel 2.3.7. The application runs the python interpreter embedded, attempting to load libpython2.3.so - but since the local machine has libpython2.4.so under /usr/lib64, the application is failing.</p> <p>I see that there are RPMs for python-devel (but not version 2.3.x). Another wrinkle is that I don't want to overwrite the existing python under /usr/lib (I don't have su anyway). What I want to do is place the somewhere in my home directory (i.e. /home/noahz/lib) and use PATH and LD_LIBRARY_PATH to point to the older version for this application. </p> <p>What I'm trying to find out (but can't seem to craft the right google search for) is:</p> <p>1) Where do I download python-devel-2.3 or libpython2.3.so.1.0 (if either available)</p> <p>2a) If I can't download python-devel-2.3, how do I build libpython2.3.so from source (already downloaded Python-2.3.tgz and </p> <p>2b) Is building libpython2.3.so.1.0 from source and pointing to it with LD_LIBRARY_PATH good enough, or am I going to run into other problems (other dependencies)</p> <p>3) In general, am I approaching this problem the right way? </p> <p><strong>ADDITIONAL INFO:</strong></p> <ul> <li><p>I attempted to symlink (ln -s) to the later version. This caused the app to fail silently.</p></li> <li><p>Distro is Red Hat Enterprise Linux 5 (RHEL5) - for x86_64</p></li> </ul>
2
2009-04-15T21:13:47Z
753,903
<p>Can you use one of these rpm's? What specific distro are you on?</p> <ul> <li><a href="http://www.python.org/download/releases/2.3.3/rpms/" rel="nofollow">http://www.python.org/download/releases/2.3.3/rpms/</a></li> <li><a href="http://rpm.pbone.net/index.php3/stat/4/idpl/3171326/com/python-devel-2.3-4.i586.rpm.html" rel="nofollow">http://rpm.pbone.net/index.php3/stat/4/idpl/3171326/com/python-devel-2.3-4.i586.rpm.html</a></li> </ul>
0
2009-04-15T21:58:03Z
[ "python", "linux", "build" ]
Need to build (or otherwise obtain) python-devel 2.3 and add to LD_LIBRARY_PATH
753,749
<p>I am supporting an application with a hard dependency on python-devel 2.3.7. The application runs the python interpreter embedded, attempting to load libpython2.3.so - but since the local machine has libpython2.4.so under /usr/lib64, the application is failing.</p> <p>I see that there are RPMs for python-devel (but not version 2.3.x). Another wrinkle is that I don't want to overwrite the existing python under /usr/lib (I don't have su anyway). What I want to do is place the somewhere in my home directory (i.e. /home/noahz/lib) and use PATH and LD_LIBRARY_PATH to point to the older version for this application. </p> <p>What I'm trying to find out (but can't seem to craft the right google search for) is:</p> <p>1) Where do I download python-devel-2.3 or libpython2.3.so.1.0 (if either available)</p> <p>2a) If I can't download python-devel-2.3, how do I build libpython2.3.so from source (already downloaded Python-2.3.tgz and </p> <p>2b) Is building libpython2.3.so.1.0 from source and pointing to it with LD_LIBRARY_PATH good enough, or am I going to run into other problems (other dependencies)</p> <p>3) In general, am I approaching this problem the right way? </p> <p><strong>ADDITIONAL INFO:</strong></p> <ul> <li><p>I attempted to symlink (ln -s) to the later version. This caused the app to fail silently.</p></li> <li><p>Distro is Red Hat Enterprise Linux 5 (RHEL5) - for x86_64</p></li> </ul>
2
2009-04-15T21:13:47Z
754,180
<p>You can use the python RPM's linked to from the python home page ChristopheD mentioned. You can extract the RPM's using cpio, as they are just specialized cpio archives. Your method of extracting them to your home directory and setting LD_LIBRARY_PATH and PATH should work; I use this all the time for hand-built newer versions of projects I also have installed.</p> <p>Don't focus on the -devel package though; you need the main package. You can unpack the -devel one as well, but the only thing you'll actually use from it is the libpython2.3.so symlink that points to the actual library, and you can just as well create this by hand.</p> <p>Whether this is the right approach depends on what you are trying to do. If all you're trying to do is to get this one application to run for you personally, then this hack sounds fine.</p> <p>If you wanted to actually distribute something to other people for running this application, and you have no way of fixing the actual application, you should consider building an rpm of the older python version that doesn't conflict with the system-installed one. </p>
2
2009-04-15T23:37:08Z
[ "python", "linux", "build" ]
Is there a more pythonic way to build this dictionary?
753,986
<p>What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: <code>values</code> is a list that is not related to any dictionary.</p> <pre><code>for value in values: new_dict[key_from_value(value)] = value </code></pre>
6
2009-04-15T22:26:44Z
754,002
<p>At least it's shorter:</p> <pre><code>dict((key_from_value(value), value) for value in values) </code></pre>
18
2009-04-15T22:30:23Z
[ "python" ]
Is there a more pythonic way to build this dictionary?
753,986
<p>What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: <code>values</code> is a list that is not related to any dictionary.</p> <pre><code>for value in values: new_dict[key_from_value(value)] = value </code></pre>
6
2009-04-15T22:26:44Z
754,024
<pre><code>&gt;&gt;&gt; l = [ 1, 2, 3, 4 ] &gt;&gt;&gt; dict( ( v, v**2 ) for v in l ) {1: 1, 2: 4, 3: 9, 4: 16} </code></pre> <p>In Python 3.0 you can use a "dict comprehension" which is basically a shorthand for the above:</p> <pre><code>{ v : v**2 for v in l } </code></pre>
15
2009-04-15T22:36:49Z
[ "python" ]