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
Accessing Microsoft Automation Objects from Python
659,018
<p>I have a set of macros that I have turned into an add-in in excel. The macros allow me to interact with another program that has what are called Microsoft Automation Objects that provide some control over what the other program does. For example, I have a filter tool in the add-in that filters the list provided by the other program to match a list in the Excel workbook. This is slow though. I might have fifty thousand lines in the other program and want to filter out all of the lines that don't match a list of three thousand lines in Excel. This type of matching takes about 30-40 minutes. I have begun wondering if there is way to do this with Python instead since I suspect the matching process could be done in seconds.</p> <p>Edited:</p> <p>Thanks- Based on the suggestion to look at Hammond's book I found out a number of resources. However, though I am still exploring it looks like many of these are old. For example, Hammond's book was published in 2000, which means the writing was finished almost a decade ago. Correction I just found the package called PyWin32 with a 2/2009 build. </p> <p>This should get me started. Thanks</p>
4
2009-03-18T16:28:03Z
659,286
<p>You will probably need the win32com package.</p> <p>This is a sample exemple I found at : <a href="http://www.markcarter.me.uk/computing/python/excel.html">http://www.markcarter.me.uk/computing/python/excel.html</a> which shows how to use com with Excel. This might be a good start.</p> <pre><code># this example starts Excel, creates a new workbook, # puts some text in the first and second cell # closes the workbook without saving the changes # and closes Excel. This happens really fast, so # you may want to comment out some lines and add them # back in one at a time ... or do the commands interactively from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlApp.Workbooks.Add() xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!' xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!' xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1 xlApp.Quit() xlApp.Visible = 0 # see note 2 del xlApp # raw_input("press Enter ...") </code></pre>
13
2009-03-18T17:22:27Z
[ "python", "object", "automation" ]
Python sequence naming convention
659,415
<p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, and made some research on google, and it seems that the accepted convention is to add the letter "s" at the end of the variable name.</p> <p>Let's assume we have a sequence of "weight values", therefore the variable name for the sequence should be <em>weights</em>. So far that's fine, but there will be cases where some word ends with "s" and happen to be the more logical way to name a variable which is not a sequence. Or let's say you have sequences of weights themselves stored into a sequence. The "s" naming convention would name the variable <em>weightss</em>, which is ugly. I am sure there is be a better naming convention for sequences.</p> <p>What naming convention for sequences would you advise?</p>
4
2009-03-18T17:51:50Z
659,428
<p>Whatever you little heart desires....</p> <p>Just kidding, but I wouldn't get to hung up on it. If it's ugly, do something to make it more readable like <code>seq_weight</code> and <code>seq_weights</code></p>
0
2009-03-18T17:55:36Z
[ "python", "naming-conventions", "sequence" ]
Python sequence naming convention
659,415
<p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, and made some research on google, and it seems that the accepted convention is to add the letter "s" at the end of the variable name.</p> <p>Let's assume we have a sequence of "weight values", therefore the variable name for the sequence should be <em>weights</em>. So far that's fine, but there will be cases where some word ends with "s" and happen to be the more logical way to name a variable which is not a sequence. Or let's say you have sequences of weights themselves stored into a sequence. The "s" naming convention would name the variable <em>weightss</em>, which is ugly. I am sure there is be a better naming convention for sequences.</p> <p>What naming convention for sequences would you advise?</p>
4
2009-03-18T17:51:50Z
659,430
<p>Why not just <code>thing_list</code> or <code>thing_seq</code>?</p>
-1
2009-03-18T17:55:50Z
[ "python", "naming-conventions", "sequence" ]
Python sequence naming convention
659,415
<p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, and made some research on google, and it seems that the accepted convention is to add the letter "s" at the end of the variable name.</p> <p>Let's assume we have a sequence of "weight values", therefore the variable name for the sequence should be <em>weights</em>. So far that's fine, but there will be cases where some word ends with "s" and happen to be the more logical way to name a variable which is not a sequence. Or let's say you have sequences of weights themselves stored into a sequence. The "s" naming convention would name the variable <em>weightss</em>, which is ugly. I am sure there is be a better naming convention for sequences.</p> <p>What naming convention for sequences would you advise?</p>
4
2009-03-18T17:51:50Z
659,439
<p>In general, avoid this kind of behaviour. Notice from <a href="http://www.python.org/dev/peps/pep-0008/">PEP8</a></p> <blockquote> <p>A Foolish Consistency is the Hobgoblin of Little Minds</p> </blockquote> <p>which is exactly what calling a variable <code>weightss</code> would be doing. So in general have your variables describing what they are, not according to some naming convention:</p> <pre><code>weights = [44, 66, 88] weight_groups = [[44, 66, 88], ...] </code></pre> <p>etc.</p> <p>From the same section of the <a href="http://www.python.org/dev/peps/pep-0008/">PEP8</a>:</p> <blockquote> <p>But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!</p> </blockquote>
20
2009-03-18T18:00:41Z
[ "python", "naming-conventions", "sequence" ]
Python sequence naming convention
659,415
<p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>, and made some research on google, and it seems that the accepted convention is to add the letter "s" at the end of the variable name.</p> <p>Let's assume we have a sequence of "weight values", therefore the variable name for the sequence should be <em>weights</em>. So far that's fine, but there will be cases where some word ends with "s" and happen to be the more logical way to name a variable which is not a sequence. Or let's say you have sequences of weights themselves stored into a sequence. The "s" naming convention would name the variable <em>weightss</em>, which is ugly. I am sure there is be a better naming convention for sequences.</p> <p>What naming convention for sequences would you advise?</p>
4
2009-03-18T17:51:50Z
659,448
<blockquote> <p>The "s" naming convention would name the variable weightss, which is ugly. I am sure there is be a better naming convention for sequences.</p> </blockquote> <p>I think the convention you're describing is meant to be interpreted as "whenever you have list of something, make it clear that it's a list by pluralizing it". For example, if you have a list of instances of grass, you would call this <code>grasses</code>, not <code>grasss</code>. I don't think it's meant to be taken as literally as you're taking it.</p> <p>PEP always advises you to take your own approach if that is more readable and useful. As <a href="http://stackoverflow.com/questions/659415/python-sequence-naming-convention/659439#659439"><strong>Ali mentioned</strong></a>, one of the guiding principles of PEP is that you shouldn't fall prey to foolish consistencies.</p>
10
2009-03-18T18:03:23Z
[ "python", "naming-conventions", "sequence" ]
What's the correct way to add extra find-links to easy_install when called as a function?
659,575
<p>I need to call easy_install as a function to install some Python eggs from a bunch of servers. Precisely what I install and where I get it from is determined at run-time: For example which servers I use depends on the geographic location of the computer.</p> <p>Since I cannot guarantee that any single server will always be available, it has been decided that my script needs to check a number of servers. Some locations have prohibitive web-filtering so I need to check a UNC path. Other locations require me to check a mix, as in this example:</p> <pre><code>myargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99'] setuptools.command.easy_install.main( myargs ) </code></pre> <p>It seems to work just fine when I do not provide a find-links option (-f) (in this case it just picks up the defaults from distutils.cfg), when I try to specify an additional find-links the option all I get is:</p> <pre><code>Traceback (most recent call last): File "D:\workspace\pythonscripts_trunk\javapy_egg\Scripts\test_javapy.py", line 20, in ? result = pyproxy.requireEgg( eggspec , True, hosts ) File "d:\workspace\pythonscripts_trunk\javapy_egg\src\calyon\javapy\pyproxy.py", line 141, in requireEgg pkg_resources.require(eggname) File "d:\python24\lib\site-packages\setuptools-0.6c9-py2.4.egg\pkg_resources. py", line 626, in require needed = self.resolve(parse_requirements(requirements)) File "d:\python24\lib\site-packages\setuptools-0.6c9-py2.4.egg\pkg_resources.py", line 524, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: myproject==trunk-99 </code></pre> <p>Can somebody confirm the correct way to do this? For example do I use Windows or UNIX slashes in the arguments? What character must be used to seperate multiple URLs? </p> <p>I'm using setuptools 0.6c9 on Windows32 </p>
1
2009-03-18T18:37:52Z
679,035
<p>Quote:</p> <pre><code>myargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99'] setuptools.command.easy_install.main( myargs ) </code></pre> <p>This first problem I see with this is that you're missing a single quote on the end of your list of servers to look in.</p> <p>Also, it's generally a good idea to surround each URL with double quotes to make sure they each get interpreted as a single item.</p> <p>I'm not sure what you're doing with this argument <code>'myproject==trunk-99'</code>, but the way you have it written above, easy_install is interpreting it as a package name (<a href="http://peak.telecommunity.com/DevCenter/EasyInstall#packaging-others-projects-as-eggs" rel="nofollow">see the documentation</a>).</p> <p>You probably want to drop the <code>myproject==</code> as it is only looking for the project name, not a Boolean or keyword argument.</p> <p>Also, I think you meant to use the <code>-v</code> argument instead of the non-existant <code>-vv</code>.</p> <p>You were correct to use a space to separate your list of URLs/servers. Forward slashes will work on both Unix and Windows.</p> <p>Something like this should work for you:</p> <pre><code>myargs = ['-v', '-m', '-a', '-f', '"//filesrver/eggs/" "http://webserver1/python_eggs/" "http://webserver2/python_eggs/"', 'trunk-99'] setuptools.command.easy_install.main( myargs ) </code></pre>
3
2009-03-24T20:04:42Z
[ "python", "setuptools" ]
Python: How to add RSA padding?
659,737
<p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br /> I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p> <p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signature hash) is not properly padded.<br /> What does it mean?<br /> Neither PyCrypto or M2Crypto mention anything about this and google didn't find anything relevant. Do these libraries automatically add the paddign? How can one tell?</p> <p>If the answer to the above is no, what is considered proper padding?</p>
4
2009-03-18T19:24:04Z
659,745
<p>Not entirely sure, but if you add a random component to your RSA message it prevents dictionary attacks</p>
0
2009-03-18T19:26:03Z
[ "python", "encryption", "rsa" ]
Python: How to add RSA padding?
659,737
<p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br /> I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p> <p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signature hash) is not properly padded.<br /> What does it mean?<br /> Neither PyCrypto or M2Crypto mention anything about this and google didn't find anything relevant. Do these libraries automatically add the paddign? How can one tell?</p> <p>If the answer to the above is no, what is considered proper padding?</p>
4
2009-03-18T19:24:04Z
661,147
<p>I recently fought through figuring out encryption...this article helped alot in explaining what was ment by padding:</p> <p><a href="http://www.di-mgt.com.au/cryptopad.html" rel="nofollow">http://www.di-mgt.com.au/cryptopad.html</a></p> <p>(method one seemed the easiest for me to implement)</p> <p>I can share some code snippets if needed.</p> <p>P.S. This file came in handy too in helping create secure keys (google for it) PBKDF2.py - PKCS#5 v2.0 Password-Based Key Derivation</p>
1
2009-03-19T05:28:53Z
[ "python", "encryption", "rsa" ]
Python: How to add RSA padding?
659,737
<p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br /> I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p> <p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signature hash) is not properly padded.<br /> What does it mean?<br /> Neither PyCrypto or M2Crypto mention anything about this and google didn't find anything relevant. Do these libraries automatically add the paddign? How can one tell?</p> <p>If the answer to the above is no, what is considered proper padding?</p>
4
2009-03-18T19:24:04Z
661,276
<p>One of the reason for <strong>random</strong> padding might be that "from the book" RSA with low exponent (let's say 3) can be cracked really simply if the exact same message is sent to several people (three).</p> <p>You'd therefore better make sure that you don't send the exact same message by applying some kind of random (yet inversible) transformation to your message before.</p> <p>Maybe that's what thing padding is about !?</p> <p>EDIT: I looked on wikipedia. what I was talking about is called Hastad's attack.</p>
3
2009-03-19T07:02:35Z
[ "python", "encryption", "rsa" ]
Python: How to add RSA padding?
659,737
<p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br /> I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p> <p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signature hash) is not properly padded.<br /> What does it mean?<br /> Neither PyCrypto or M2Crypto mention anything about this and google didn't find anything relevant. Do these libraries automatically add the paddign? How can one tell?</p> <p>If the answer to the above is no, what is considered proper padding?</p>
4
2009-03-18T19:24:04Z
663,290
<p>PyCrypto doesn't add the mentioned padding.<br /> M2Crypto instead does.</p> <p>M2Crypto is built on top of openSSL, supports mostlyl everything you need, is still maintained and up to date while PyCrypto issues several deprecation warnings.</p>
6
2009-03-19T17:52:53Z
[ "python", "encryption", "rsa" ]
Python: How to add RSA padding?
659,737
<p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br /> I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p> <p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signature hash) is not properly padded.<br /> What does it mean?<br /> Neither PyCrypto or M2Crypto mention anything about this and google didn't find anything relevant. Do these libraries automatically add the paddign? How can one tell?</p> <p>If the answer to the above is no, what is considered proper padding?</p>
4
2009-03-18T19:24:04Z
10,399,555
<p>Firstly, you should be using AES, since it is the de-facto standard.</p> <p>AES encrypts bytes in block-sizes of 16 bytes. Obviously this works fine for any large piece of data. But the last bit of it, obviously maybe lesser than 16 bytes.</p> <p>For the last block, you'll need to pad it,and typical padding is done via PCKS7, which is pretty straight-forward.</p> <p>Lets say you have a string: "icecream" as the last block.</p> <p><code>"icecream"</code> is 8 bytes, so you need another 8 bytes to make a block</p> <p>So what you do is simply append the character 8(not '8') 8 times</p> <pre><code>"icecream\x08\x08\x08\x08\x08\x08\x08\x08" </code></pre> <p>Would be your resultant string. Now you go ahead an encrypt the data.</p> <p>Remember that while decrypting, you'll need to catch this last block, and strip the padding before using it.</p>
0
2012-05-01T14:59:01Z
[ "python", "encryption", "rsa" ]
Reversing Django URLs With Extra Options
659,832
<p>Suppose I have a URLconf like below, and <code>'foo'</code> and <code>'bar'</code> are valid values for <code>page_slug</code>.</p> <pre><code>urlpatterns = patterns('', (r'^page/(?P&lt;page_slug&gt;.*)/', 'myapp.views.someview'), ) </code></pre> <p>Then, I could reconstruct the URLs using the below, right?</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/page/foo/' &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/page/bar/' </code></pre> <p>But what if I change my URLconf to this?</p> <pre><code>urlpatterns = patterns('', (r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}), (r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}), ) </code></pre> <p>I expected this result:</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/foo-direct/' &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/my-bar-page/' </code></pre> <p>However, this throws a <code>NoReverseMatch</code> exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want?</p> <p>Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).</p>
10
2009-03-18T19:45:58Z
659,922
<p>Here's what we do.</p> <p>urls.py has patterns like this</p> <pre><code>url(r'^(?P&lt; datarealm &gt;.*?)/json/someClass/(?P&lt;object_id&gt;.*?)/$', 'json_someClass_resource', ), </code></pre> <p>views.py as reverse calls like this</p> <pre><code> object = SomeModel.objects.get(...) url= reverse('json_someClass_resource', kwargs={'object_id':object.id,'datarealm':object.datarealm.name}) </code></pre>
6
2009-03-18T20:17:11Z
[ "python", "django" ]
Reversing Django URLs With Extra Options
659,832
<p>Suppose I have a URLconf like below, and <code>'foo'</code> and <code>'bar'</code> are valid values for <code>page_slug</code>.</p> <pre><code>urlpatterns = patterns('', (r'^page/(?P&lt;page_slug&gt;.*)/', 'myapp.views.someview'), ) </code></pre> <p>Then, I could reconstruct the URLs using the below, right?</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/page/foo/' &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/page/bar/' </code></pre> <p>But what if I change my URLconf to this?</p> <pre><code>urlpatterns = patterns('', (r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}), (r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}), ) </code></pre> <p>I expected this result:</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/foo-direct/' &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/my-bar-page/' </code></pre> <p>However, this throws a <code>NoReverseMatch</code> exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want?</p> <p>Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).</p>
10
2009-03-18T19:45:58Z
660,339
<p>Named urls ought to be an option. Your case is highlighted in the Django reference:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2</a></p> <p>I'm not sure the designers left another work-around; they expected named urls to cover it.</p> <p>May I digress about encapsulation? Thanks. There are two main reasons:</p> <ol> <li>Abstraction--no one <em>wants</em> to see the details</li> <li>Security--no one <em>should</em> see the details</li> </ol> <p>As for 1, you can get a decent amount of mileage out of it in python, and Django is an excellent example. As for 2, it's an interpreted language. Either you're running it where it's written, or you're shipping off compiled .pyc files. If that's really what you're doing, then compile the url conf.</p> <p>Finally, it seems less encapsulated to let other apps know about the functions than the url structure. But if you really disagree, I think you'll have to implement a more flexible reverse method yourself.</p>
4
2009-03-18T22:24:25Z
[ "python", "django" ]
Reversing Django URLs With Extra Options
659,832
<p>Suppose I have a URLconf like below, and <code>'foo'</code> and <code>'bar'</code> are valid values for <code>page_slug</code>.</p> <pre><code>urlpatterns = patterns('', (r'^page/(?P&lt;page_slug&gt;.*)/', 'myapp.views.someview'), ) </code></pre> <p>Then, I could reconstruct the URLs using the below, right?</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/page/foo/' &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/page/bar/' </code></pre> <p>But what if I change my URLconf to this?</p> <pre><code>urlpatterns = patterns('', (r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}), (r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}), ) </code></pre> <p>I expected this result:</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'foo'}) '/foo-direct/' &gt;&gt;&gt; reverse('myapp.views.someview', kwargs={'page_slug': 'bar'}) '/my-bar-page/' </code></pre> <p>However, this throws a <code>NoReverseMatch</code> exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want?</p> <p>Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).</p>
10
2009-03-18T19:45:58Z
2,853,959
<p>You should try naming your urlconfs. Example:</p> <pre><code>urlpatterns = patterns('', url(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}, name='foo-direct'), url(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}, name='bar-page'), ) </code></pre> <p>Then just edit your reverses and you should get it working.</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse('foo-direct', kwargs={'page_slug': 'foo'}) '/foo-direct/' &gt;&gt;&gt; reverse('bar-page', kwargs={'page_slug': 'bar'}) '/my-bar-page/' </code></pre> <p>More info at: <a href="http://docs.djangoproject.com/en/1.2/topics/http/urls/#id2">Django Docs</a></p>
15
2010-05-18T00:52:50Z
[ "python", "django" ]
Checking file attributes in python
659,847
<p>I'd like to check the archive bit for each file in a directory using python. So far i've got the following but i can't get it to work properly. The idea of the script is to be able to see all the files that have the archive bit on.</p> <p>Thanks</p> <pre><code># -*- coding: latin-1 -*- import os , win32file, win32con from time import * start = clock() ext = [ '.txt' , '.doc' ] def fileattributeisset(filename, fileattr): return bool(win32file.GetFileAttributes(filename) &amp; fileattr) for root, dirs, files in os.walk('d:\\Pruebas'): print ("root", root) print ("dirs", dirs) print ("files", files) for i in files: if i[ - 4:] in ext: print('...', root, '\\', i, end=' ') fattrs = win32file.GetFileAttributes(i) if fattrs &amp; win32con.FILE_ATTRIBUTE_ARCHIVE: print('A isSet',fattrs) #print( fileattributeisset(i, win32con.FILE_ATTRIBUTE_ARCHIVE)) print ('####') </code></pre> <p>EDIT: all files appear to have the archive bit on, doing 'attrib' shows that all files have no attribute bits on.</p>
2
2009-03-18T19:51:17Z
660,223
<p>The file list returned from os.walk are not fully qualified paths, so when you call</p> <pre><code>win32file.GetFileAttributes(i) </code></pre> <p>it can't find the file and returns an error code; which happens to be -1. So the operation</p> <pre><code>fattrs &amp; win32con.FILE_ATTRIBUTE_ARCHIVE </code></pre> <p>is always true.</p> <p>You need to join the root to the filename so that GetFileAttributes will succeed:</p> <pre><code>fattrs = win32file.GetFileAttributes(os.path.join(root, i)) </code></pre> <p>Also, when you are checking the extension, it is probably better to use <code>os.path.splitext(path)</code> to retrieve the extension rather than relying on them be 3 characters long as you do.</p>
6
2009-03-18T21:37:52Z
[ "python" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
659,888
<p>"Do child processes spawned via multiprocessing share objects created earlier in the program?"</p> <p>No. </p> <p>Processes have independent memory space.</p> <p><strong>Solution 1</strong></p> <p>To make best use of a large structure with lots of workers, do this.</p> <ol> <li><p>Write each worker as a "filter" -- reads intermediate results from stdin, does work, writes intermediate results on stdout.</p></li> <li><p>Connect all the workers as a pipeline:</p> <pre><code>process1 &lt;source | process2 | process3 | ... | processn &gt;result </code></pre></li> </ol> <p>Each process reads, does work and writes.</p> <p>This is remarkably efficient since all processes are running concurrently. The writes and reads pass directly through shared buffers between the processes.</p> <p><hr /></p> <p><strong>Solution 2</strong></p> <p>In some cases, you have a more complex structure -- often a "fan-out" structure. In this case you have a parent with multiple children.</p> <ol> <li><p>Parent opens source data. Parent forks a number of children.</p></li> <li><p>Parent reads source, farms parts of the source out to each concurrently running child.</p></li> <li><p>When parent reaches the end, close the pipe. Child gets end of file and finishes normally.</p></li> </ol> <p>The child parts are pleasant to write because each child simply reads <code>sys.sydin</code>. </p> <p>The parent has a little bit of fancy footwork in spawning all the children and retaining the pipes properly, but it's not too bad.</p> <p>Fan-in is the opposite structure. A number of independently running processes need to interleave their inputs into a common process. The collector is not as easy to write, since it has to read from many sources. </p> <p>Reading from many named pipes is often done using the <code>select</code> module to see which pipes have pending input.</p> <p><hr /></p> <p><strong>Solution 3</strong></p> <p>Shared lookup is the definition of a database. </p> <p>Solution 3A -- load a database. Let the workers process the data in the database.</p> <p>Solution 3B -- create a very simple server using <a href="http://werkzeug.pocoo.org/">werkzeug</a> (or similar) to provide WSGI applications that respond to HTTP GET so the workers can query the server.</p> <p><hr /></p> <p><strong>Solution 4</strong></p> <p>Shared filesystem object. Unix OS offers shared memory objects. These are just files that are mapped to memory so that swapping I/O is done instead of more convention buffered reads.</p> <p>You can do this from a Python context in several ways</p> <ol> <li><p>Write a startup program that (1) breaks your original gigantic object into smaller objects, and (2) starts workers, each with a smaller object. The smaller objects could be pickled Python objects to save a tiny bit of file reading time.</p></li> <li><p>Write a startup program that (1) reads your original gigantic object and writes a page-structured, byte-coded file using <code>seek</code> operations to assure that individual sections are easy to find with simple seeks. This is what a database engine does -- break the data into pages, make each page easy to locate via a <code>seek</code>.</p> <p>Spawn workers with access this this large page-structured file. Each worker can seek to the relevant parts and do their work there.</p></li> </ol>
31
2009-03-18T20:06:08Z
[ "python", "multiprocessing" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
659,913
<p>Different processes have different address space. Like running different instances of the interpreter. That's what IPC (interprocess communication) is for.</p> <p>You can use either queues or pipes for this purpose. You can also use rpc over tcp if you want to distribute the processes over a network later.</p> <p><a href="http://docs.python.org/dev/library/multiprocessing.html#exchanging-objects-between-processes" rel="nofollow">http://docs.python.org/dev/library/multiprocessing.html#exchanging-objects-between-processes</a></p>
2
2009-03-18T20:14:54Z
[ "python", "multiprocessing" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
660,024
<p>If you're running under Unix, they may share the same object, due to <a href="http://unixfaq.blogspot.com/2008/08/whats-difference-between-fork-and-vfork.html" rel="nofollow">how fork works</a> (i.e., the child processes have separate memory but it's copy-on-write, so it may be shared as long as nobody modifies it). I tried the following:</p> <pre><code>import multiprocessing x = 23 def printx(y): print x, id(x) print y if __name__ == '__main__': pool = multiprocessing.Pool(processes=4) pool.map(printx, (1,2,3,4)) </code></pre> <p>and got the following output:</p> <pre> $ ./mtest.py 23 22995656 1 23 22995656 2 23 22995656 3 23 22995656 4 </pre> <p>Of course this doesn't <em>prove</em> that a copy hasn't been made, but you should be able to verify that in your situation by looking at the output of <code>ps</code> to see how much real memory each subprocess is using.</p>
4
2009-03-18T20:44:52Z
[ "python", "multiprocessing" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
660,026
<p><a href="http://stackoverflow.com/questions/659865/python-multiprocessing-sharing-a-large-read-only-object-between-processes/659888#659888">S.Lott</a> is correct. Python's multiprocessing shortcuts effectively give you a separate, duplicated chunk of memory.</p> <p>On most *nix systems, using a lower-level call to <code>os.fork()</code> will, in fact, give you copy-on-write memory, which might be what you're thinking. AFAIK, in theory, in the most simplistic of programs possible, you could read from that data without having it duplicated.</p> <p>However, things aren't quite that simple in the Python interpreter. Object data and meta-data are stored in the same memory segment, so even if the object never changes, something like a reference counter for that object being incremented will cause a memory write, and therefore a copy. Almost any Python program that is doing more than "print 'hello'" will cause reference count increments, so you will likely never realize the benefit of copy-on-write.</p> <p>Even if someone did manage to hack a shared-memory solution in Python, trying to coordinate garbage collection across processes would probably be pretty painful.</p>
19
2009-03-18T20:45:37Z
[ "python", "multiprocessing" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
660,215
<p>Not directly related to multiprocessing per se, but from your example, it would seem you could just use the <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> module or something like that. Does the "big_lookup_object" really have to be completely in memory?</p>
1
2009-03-18T21:35:08Z
[ "python", "multiprocessing" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
660,468
<h3>Do child processes spawned via multiprocessing share objects created <em>earlier</em> in the program?</h3> <p>It depends. For global read-only variables it can be often considered so (apart from the memory consumed) else it should not. </p> <p><a href="http://docs.python.org/dev/library/multiprocessing.html#multiprocessing-programming">multiprocessing</a>'s documentation says:</p> <p><code>Better to inherit than pickle/unpickle</code></p> <blockquote> <p>On Windows many types from multiprocessing need to be picklable so that child processes can use them. However, one should generally avoid sending shared objects to other processes using pipes or queues. Instead you should arrange the program so that a process which need access to a shared resource created elsewhere can inherit it from an ancestor process.</p> </blockquote> <p><code>Explicitly pass resources to child processes</code></p> <blockquote> <p>On Unix a child process can make use of a shared resource created in a parent process using a global resource. However, it is better to pass the object as an argument to the constructor for the child process.</p> <p>Apart from making the code (potentially) compatible with Windows this also ensures that as long as the child process is still alive the object will not be garbage collected in the parent process. This might be important if some resource is freed when the object is garbage collected in the parent process.</p> </blockquote> <p><code>Global variables</code></p> <blockquote> <p>Bear in mind that if code run in a child process tries to access a global variable, then the value it sees (if any) may not be the same as the value in the parent process at the time that Process.start() was called.</p> </blockquote> <h3>Example</h3> <p>On Windows (single CPU):</p> <pre><code>#!/usr/bin/env python import os, sys, time from multiprocessing import Pool x = 23000 # replace `23` due to small integers share representation z = [] # integers are immutable, let's try mutable object def printx(y): global x if y == 3: x = -x z.append(y) print os.getpid(), x, id(x), z, id(z) print y if len(sys.argv) == 2 and sys.argv[1] == "sleep": time.sleep(.1) # should make more apparant the effect if __name__ == '__main__': pool = Pool(processes=4) pool.map(printx, (1,2,3,4)) </code></pre> <p>With <code>sleep</code>:</p> <pre><code>$ python26 test_share.py sleep 2504 23000 11639492 [1] 10774408 1 2564 23000 11639492 [2] 10774408 2 2504 -23000 11639384 [1, 3] 10774408 3 4084 23000 11639492 [4] 10774408 4 </code></pre> <p>Without <code>sleep</code>:</p> <pre><code>$ python26 test_share.py 1148 23000 11639492 [1] 10774408 1 1148 23000 11639492 [1, 2] 10774408 2 1148 -23000 11639324 [1, 2, 3] 10774408 3 1148 -23000 11639324 [1, 2, 3, 4] 10774408 4 </code></pre>
24
2009-03-18T23:17:12Z
[ "python", "multiprocessing" ]
Python multiprocessing: sharing a large read-only object between processes?
659,865
<p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p> <p>I have the following setup:</p> <pre><code>do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) </code></pre> <p>I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.</p> <p>My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? </p> <p>Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.</p> <p>Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.</p>
56
2009-03-18T19:58:46Z
34,143,699
<p>For Linux/Unix/MacOS platform, forkmap is a quick-and-dirty solution. </p>
0
2015-12-07T21:37:24Z
[ "python", "multiprocessing" ]
.NET Framework equivalent of Python's imghdr.what function
660,057
<p>Does .NET Framework have a function similar to Python's imghdr.what function to determine what type of image a file (or stream) is? I can't find anything.</p>
0
2009-03-18T20:54:38Z
660,142
<p>Just recently I needed to determine mime type used in file. I don't know the exact logic behind this windows API calls, but I suspect it goes inside the file to get idea of it's mime type. Hope this will help</p> <pre><code>using System; using System.IO; using System.Runtime.InteropServices; namespace SomeNamespace { /// &lt;summary&gt; /// This will work only on windows /// &lt;/summary&gt; public class MimeTypeFinder { [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)] private extern static UInt32 FindMimeFromData( UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)] String pwzUrl, [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer, UInt32 cbSize, [MarshalAs(UnmanagedType.LPStr)]String pwzMimeProposed, UInt32 dwMimeFlags, out UInt32 ppwzMimeOut, UInt32 dwReserverd ); public string GetMimeFromFile(string filename) { if (!File.Exists(filename)) throw new FileNotFoundException(filename + " not found"); var buffer = new byte[256]; using (var fs = new FileStream(filename, FileMode.Open)) { if (fs.Length &gt;= 256) fs.Read(buffer, 0, 256); else fs.Read(buffer, 0, (int)fs.Length); } try { UInt32 mimetype; FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0); var mimeTypePtr = new IntPtr(mimetype); var mime = Marshal.PtrToStringUni(mimeTypePtr); Marshal.FreeCoTaskMem(mimeTypePtr); return mime; } catch (Exception) { return "unknown/unknown"; } } } } </code></pre>
0
2009-03-18T21:16:07Z
[ "c#", "python" ]
.NET Framework equivalent of Python's imghdr.what function
660,057
<p>Does .NET Framework have a function similar to Python's imghdr.what function to determine what type of image a file (or stream) is? I can't find anything.</p>
0
2009-03-18T20:54:38Z
660,169
<p><em>If</em> you can trust the file's extension, you can do something like the rails plugin <a href="http://github.com/mattetti/mimetype-fu" rel="nofollow">mimetype-fu</a>.</p> <p>This plugin has a yaml list of extensions and their known mime types. It is fairly exhaustive. We found a yaml parser for .net and simply used mimetype-fu's yaml. This made it both fast to build and fast performing.</p> <p>If you are dealing with streams only and don't have a filename, the above may work better for you.</p>
0
2009-03-18T21:23:29Z
[ "c#", "python" ]
How to manage a CPU intensive process on a server
660,059
<p>I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.</p> <p>The script takes up to 20 seconds to run and I am concerned about the performance on my server. Is there a good approach to either lower the priority of the process, periodically cede control to the OS, or otherwise protect the performance of my modest server?</p>
7
2009-03-18T20:54:54Z
660,068
<p>Assuming it's a UNIX server, you could use the <a href="http://www.builderau.com.au/program/linux/print.htm?TYPE=story&amp;AT=339286637-339028299t-320002022c" rel="nofollow">nice command</a> to lower its priority. That should do the trick.</p>
7
2009-03-18T20:57:42Z
[ "python", "performance", "signal-processing" ]
How to manage a CPU intensive process on a server
660,059
<p>I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.</p> <p>The script takes up to 20 seconds to run and I am concerned about the performance on my server. Is there a good approach to either lower the priority of the process, periodically cede control to the OS, or otherwise protect the performance of my modest server?</p>
7
2009-03-18T20:54:54Z
660,141
<p>You can use <a href="http://cpulimit.sourceforge.net/" rel="nofollow">cpulimit</a> on a linux based server. It will allow you to limit the CPU usage (specify the limit as a percentage) even of scripts that have already started running, and its usage is pretty straightforward.</p> <p>It's available on the Debian repository, so you can install it easily using aptitude:</p> <pre><code>apt-get install cpulimit </code></pre> <p>Typical ways to use <code>cpulimit</code> includes:</p> <pre><code># To limit CPU usage to 75% of program called foo: cpulimit -e foo -l 75 # To limit CPU usage to 50% of program with pid = 1582 cpulimit -p 1582 -l 50 </code></pre>
5
2009-03-18T21:15:54Z
[ "python", "performance", "signal-processing" ]
How do I list all tga files in a directory (non recursive) in Python?
660,160
<p>How do I list all tga files in a directory (non recursive) in Python?</p>
4
2009-03-18T21:21:30Z
660,178
<pre><code> >>> import os >>> for file in [tga for tga in os.listdir(directory) if tga.endswith(".tga")]: >>> print file </code></pre>
1
2009-03-18T21:25:29Z
[ "python" ]
How do I list all tga files in a directory (non recursive) in Python?
660,160
<p>How do I list all tga files in a directory (non recursive) in Python?</p>
4
2009-03-18T21:21:30Z
660,179
<pre><code>import glob, os for filename in glob.glob(os.path.join(yourPath, "*.tga")) print(filename) </code></pre>
13
2009-03-18T21:25:51Z
[ "python" ]
How do I list all tga files in a directory (non recursive) in Python?
660,160
<p>How do I list all tga files in a directory (non recursive) in Python?</p>
4
2009-03-18T21:21:30Z
660,190
<p>If you are doing it based on file extension, you can do something like this:</p> <pre><code>import os directory = "C:/" extension = ".tga" list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)] </code></pre> <p>Obviously you can omit the lower() if you can garantee the case of the files. Also there is the excellent path.py (<a href="http://pypi.python.org/pypi/path.py">http://pypi.python.org/pypi/path.py</a>) module.</p> <p>If you do not know the file extension you can use something like PIL (<a href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a>) to detect the file type by decoding the file.</p>
19
2009-03-18T21:27:56Z
[ "python" ]
How do I list all tga files in a directory (non recursive) in Python?
660,160
<p>How do I list all tga files in a directory (non recursive) in Python?</p>
4
2009-03-18T21:21:30Z
10,376,226
<p>The following example uses <code>filter</code>, which offers an elegant solution as shown below:</p> <pre><code>import os files = filter(lambda x: x.endswith('.tga'), os.listdir(DIR)) </code></pre>
2
2012-04-29T21:38:56Z
[ "python" ]
How do I list all tga files in a directory (non recursive) in Python?
660,160
<p>How do I list all tga files in a directory (non recursive) in Python?</p>
4
2009-03-18T21:21:30Z
10,718,762
<p>My Targa/Vista have often .vst and .tga, sometimes other extension:</p> <pre><code>import os from glob import glob import PIL filenames = [] for filename in glob(os.path.join(dirname, "*.*")): try: img = PIL.Image(filename) if img.format == "TGA": filenames.append(filename) except IOError: // from PIL if not recognised pass </code></pre>
0
2012-05-23T11:12:15Z
[ "python" ]
Python: decorator specific argument (unrelated to wrapped function)?
660,727
<p>I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:</p> <pre><code>@cacheable('/path/to/cache/file') def my_function(a, b, c): return 'something' </code></pre> <p>The argument to the decorator is completely separate from the argument to the function it's wrapping. I've looked at quite a few examples but I'm not quite getting how to do this - is it possible to have an argument for the decorator that's unrelated to and not passed to the wrapped function?</p>
6
2009-03-19T01:11:03Z
660,751
<p>The idea is that your decorator is a function returning a decorator.</p> <p><strong>FIRST</strong> Write your decorator as if you knew your argument was a global variable. Let's say something like:</p> <p>-</p> <pre><code>def decorator(f): def decorated(*args,**kwargs): cache = Cache(cachepath) if cache.iscached(*args,**kwargs): ... else: res = f(*args,**kwargs) cache.store((*args,**kwargs), res) return res return decorated </code></pre> <p><strong>THEN</strong> Write a function that takes cachepath as an arg and return your decorator.</p> <p>-</p> <pre><code>def cache(filepath) def decorator(f): def decorated(*args,**kwargs): cache = Cache(cachepath) if cache.iscached(*args,**kwargs): ... else: res = f(*args,**kwargs) cache.store((*args,**kwargs), res) return res return decorated return decorator </code></pre>
9
2009-03-19T01:22:45Z
[ "python", "decorator" ]
Python: decorator specific argument (unrelated to wrapped function)?
660,727
<p>I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:</p> <pre><code>@cacheable('/path/to/cache/file') def my_function(a, b, c): return 'something' </code></pre> <p>The argument to the decorator is completely separate from the argument to the function it's wrapping. I've looked at quite a few examples but I'm not quite getting how to do this - is it possible to have an argument for the decorator that's unrelated to and not passed to the wrapped function?</p>
6
2009-03-19T01:11:03Z
660,758
<p>Yes it is. As you know, a decorator is a function. When written in the form:</p> <pre><code>def mydecorator(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @mydecorator def foo(a, b, c): pass </code></pre> <p>the argument passed to <code>mydecorator</code> is the function <code>foo</code> itself.</p> <p>When the decorator accepts an argument, the call <code>@mydecorator('/path/to')</code> is actually going to call the mydecorator function with '/path/to' first. Then the result of the call to <code>mydecorator(path)</code> will be called to receive the function <code>foo</code>. You're effectively defining a dynamic wrapper function.</p> <p>In a nutshell, you need another layer of decorator functions.</p> <p>Here is this slightly silly example:</p> <pre><code>def addint(val): def decorator(func): def wrapped(*args, **kwargs): result = func(*args, **kwargs) return result + val return wrapped # returns the decorated function "add_together" return decorator # returns the definition of the decorator "addint" # specifically built to return an extra 5 to the sum @addint(5) def add_together(a, b): return a + b print add_together(1, 2) # prints 8, not 3 </code></pre>
5
2009-03-19T01:25:48Z
[ "python", "decorator" ]
Python: decorator specific argument (unrelated to wrapped function)?
660,727
<p>I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:</p> <pre><code>@cacheable('/path/to/cache/file') def my_function(a, b, c): return 'something' </code></pre> <p>The argument to the decorator is completely separate from the argument to the function it's wrapping. I've looked at quite a few examples but I'm not quite getting how to do this - is it possible to have an argument for the decorator that's unrelated to and not passed to the wrapped function?</p>
6
2009-03-19T01:11:03Z
660,834
<p>Paul's answer is good, I would move the cache object so it doesn't need to be built every time, and design your cache so that it raises KeyError when there is a cache miss:</p> <pre>def cache(filepath): def decorator(f): f._cache = Cache(cachepath) def decorated(*args,**kwargs): try: key = (args, kwargs) res = f._cache.get(key) except KeyError: res = f(*args, **kwargs) f._cache.put(key, res) return res return decorated return decorator </pre>
3
2009-03-19T02:11:19Z
[ "python", "decorator" ]
Python Django loop logic: Error says 'int' is not iterable - check my syntax?
660,773
<pre><code>return sum(jobrecord.get_cost() or 0 for jobrecord in self.project.jobrecord_set.filter( date__lte=date, date__gte=self.start_date) or 0) </code></pre>
0
2009-03-19T01:38:37Z
660,779
<p>After a small rewrite</p> <pre><code>query = self.project.jobrecord_set.filter( date__lte=date, date__gte=self.start_date) values= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 ) return sum( values ) </code></pre> <p>Look closely at the <code>values= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 )</code></p> <p>What happens when the query is empty?</p> <p>You're evaluating <code>jobrecord.get_cost() or 0 for jobrecord in 0</code></p>
3
2009-03-19T01:42:52Z
[ "python", "django" ]
Python Django loop logic: Error says 'int' is not iterable - check my syntax?
660,773
<pre><code>return sum(jobrecord.get_cost() or 0 for jobrecord in self.project.jobrecord_set.filter( date__lte=date, date__gte=self.start_date) or 0) </code></pre>
0
2009-03-19T01:38:37Z
660,842
<p>0 is indeed not iterable. I think you want to drop that last <code>or 0</code>. when the filter query matches no elements, it will return an empty query, and your sum will just be 0, since <code>sum([])</code> is zero.</p> <p>If there's some reason why the query might raise an exception (invalid dates or some such), an or clause wont catch that either. <code>[][1] or 0</code> still raises an exception.</p>
1
2009-03-19T02:13:33Z
[ "python", "django" ]
Django-way of specifying channel image in rss feed
660,836
<p>What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.</p> <p><b>Edit</b> dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds</p>
9
2009-03-19T02:11:26Z
660,906
<p>I suggesting to use <a href="http://code.google.com/p/django-atompub/" rel="nofollow">django-atompub</a> for Atom feed generation. It has very nice Class abstraction with lots of options, so no any XML hacking, high-level Python code only.</p> <p>Example:</p> <pre><code># Define feed class class StreamFeed(Feed): ... [snipped] def item_links(self, item): return [{'rel': 'enclosure', 'href': item.file.url, 'length': item.file.size, 'type': item.mime.name}, {'rel': 'alternate', 'href': full_url(item.get_absolute_url())}] </code></pre> <p>I used it in my open source photoblog django app. You can see examples via <a href="http://bitbucket.org/dobrych/mediatr/src/" rel="nofollow">bitbucket repo</a>.</p> <p>Complete <a href="http://bitbucket.org/dobrych/mediatr/src/tip/feeds.py" rel="nofollow">feed generation code</a>.</p>
4
2009-03-19T02:50:45Z
[ "python", "django", "rss" ]
Django-way of specifying channel image in rss feed
660,836
<p>What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.</p> <p><b>Edit</b> dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds</p>
9
2009-03-19T02:11:26Z
695,464
<p>Found the <em>right</em> way of doing it. As the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/?from=olddocs#custom-feed-generators">documentation</a> describes, I needed to create a custom feed generator by subclassing from <em>Rss201rev2Feed</em> and overriding method </p> <pre> add_root_elements() </pre> <p>like this:</p> <pre><code>class RssFooFeedGenerator(Rss201rev2Feed): def add_root_elements(self, handler): super(RssFooFeedGenerator, self).add_root_elements(handler) handler.addQuickElement(u"image", '', { 'url': u"http://www.example.com/images/logo.jpg", 'title': u"Some title", 'link': u"http://www.example.com/", }) class RssFooFeed(Feed): feed_type = RssFooFeedGenerator title = u"Foo items" link = u"http://www.example.com/" description = u"Some description" </code></pre>
8
2009-03-29T21:55:08Z
[ "python", "django", "rss" ]
Django-way of specifying channel image in rss feed
660,836
<p>What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.</p> <p><b>Edit</b> dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds</p>
9
2009-03-19T02:11:26Z
8,894,216
<p>For valid RSS 2.0 you shoud use this:</p> <pre><code>class ImageRssFeedGenerator(Rss201rev2Feed): def add_root_elements(self, handler): super(ImageRssFeedGenerator, self).add_root_elements(handler) handler.startElement(u'image', {}) handler.addQuickElement(u"url", self.feed['image_url']) handler.addQuickElement(u"title", self.feed['title']) handler.addQuickElement(u"link", self.feed['link']) handler.endElement(u'image') class LastPublishedPromiseFeed(Feed): link = 'http://www.example.com' feed_type = ImageRssFeedGenerator def feed_extra_kwargs(self, obj): return {'image_url': self.link + '/image.jpg'} </code></pre>
5
2012-01-17T11:58:11Z
[ "python", "django", "rss" ]
django : using admin datepicker
660,898
<p>I'm trying to use the admin datepicker in my own django forms.</p> <p>Roughly following the discussion here : <a href="http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html">http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html</a></p> <p>I've</p> <p>a) In my forms.py included the line</p> <pre><code>from django.contrib.admin import widgets </code></pre> <p>b) and used the widget like this :</p> <pre><code>date = forms.DateTimeField(widget=widgets.AdminDateWidget()) </code></pre> <p>c) And in my actual template I've added :</p> <pre><code>{{form.media}} </code></pre> <p>To include the js / styles etc.</p> <p>However, when I try to view my form I get no nice widget; just an ordinary text box. And the Firefox javascript error console shows me :</p> <p>gettext is not defined in calendar.js (line 26)</p> <p>and </p> <p>addEvent is not defined in DateTimeShortcuts.js (line 254)</p> <p>Any suggestions? Is this a bug in Django's own javascript library?</p> <p>Update : Basically, need to include the core and (or fake) the i18lization</p> <p>Update 2 : Carl points out this is pretty much a duplicate of <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/38916#38916">http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/38916#38916</a> (although starting from a different position)</p>
9
2009-03-19T02:48:29Z
660,986
<p>No, it's not a bug. </p> <p>It's trying to call the gettext() internationalization function in js. You can do js internationalization much like you do it in python code or templates, it's only a less known feature.</p> <p>If you don't use js internationalization in your project you can just put.</p> <pre><code>&lt;script&gt;function gettext(txt){ return txt }&lt;/script&gt; </code></pre> <p>in your top template so the js interpreter doesn't choke.</p> <p>This is a hacky way to solve it I know.</p> <p>Edit:</p> <p>Or you can include the exact jsi18n js django admin references to get it working even with other languages. I don't know which one it is.</p> <p>This was posted on django-users today:</p> <p><a href="http://groups.google.com/group/django-users/browse_thread/thread/2f529966472c479d#" rel="nofollow">http://groups.google.com/group/django-users/browse_thread/thread/2f529966472c479d#</a></p> <p>Maybe it was you, anyway, just in case.</p>
4
2009-03-19T03:42:13Z
[ "python", "django", "forms", "django-forms", "date" ]
django : using admin datepicker
660,898
<p>I'm trying to use the admin datepicker in my own django forms.</p> <p>Roughly following the discussion here : <a href="http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html">http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html</a></p> <p>I've</p> <p>a) In my forms.py included the line</p> <pre><code>from django.contrib.admin import widgets </code></pre> <p>b) and used the widget like this :</p> <pre><code>date = forms.DateTimeField(widget=widgets.AdminDateWidget()) </code></pre> <p>c) And in my actual template I've added :</p> <pre><code>{{form.media}} </code></pre> <p>To include the js / styles etc.</p> <p>However, when I try to view my form I get no nice widget; just an ordinary text box. And the Firefox javascript error console shows me :</p> <p>gettext is not defined in calendar.js (line 26)</p> <p>and </p> <p>addEvent is not defined in DateTimeShortcuts.js (line 254)</p> <p>Any suggestions? Is this a bug in Django's own javascript library?</p> <p>Update : Basically, need to include the core and (or fake) the i18lization</p> <p>Update 2 : Carl points out this is pretty much a duplicate of <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/38916#38916">http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/38916#38916</a> (although starting from a different position)</p>
9
2009-03-19T02:48:29Z
660,996
<p>I think I solved the first half by explicitly adding these lines to my template :</p> <pre><code>&lt;script type="text/javascript" src="../../../jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/admin_media/js/core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/admin_media/js/admin/RelatedObjectLookups.js"&gt;&lt;/script&gt; </code></pre> <p>But it still reports not knowing gettext</p>
2
2009-03-19T03:46:03Z
[ "python", "django", "forms", "django-forms", "date" ]
django : using admin datepicker
660,898
<p>I'm trying to use the admin datepicker in my own django forms.</p> <p>Roughly following the discussion here : <a href="http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html">http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html</a></p> <p>I've</p> <p>a) In my forms.py included the line</p> <pre><code>from django.contrib.admin import widgets </code></pre> <p>b) and used the widget like this :</p> <pre><code>date = forms.DateTimeField(widget=widgets.AdminDateWidget()) </code></pre> <p>c) And in my actual template I've added :</p> <pre><code>{{form.media}} </code></pre> <p>To include the js / styles etc.</p> <p>However, when I try to view my form I get no nice widget; just an ordinary text box. And the Firefox javascript error console shows me :</p> <p>gettext is not defined in calendar.js (line 26)</p> <p>and </p> <p>addEvent is not defined in DateTimeShortcuts.js (line 254)</p> <p>Any suggestions? Is this a bug in Django's own javascript library?</p> <p>Update : Basically, need to include the core and (or fake) the i18lization</p> <p>Update 2 : Carl points out this is pretty much a duplicate of <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/38916#38916">http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/38916#38916</a> (although starting from a different position)</p>
9
2009-03-19T02:48:29Z
685,606
<p>You may find the following works for you:</p> <pre><code>&lt;link href="/media/css/base.css" rel="stylesheet" type="text/css" media="screen" /&gt; &lt;script type="text/javascript" src="/admin/jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/media/js/core.js"&gt;&lt;/script&gt; {{ form.media }} </code></pre>
1
2009-03-26T12:42:14Z
[ "python", "django", "forms", "django-forms", "date" ]
Overriding python threading.Thread.run()
660,961
<p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p> <blockquote> <p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.</p> </blockquote> <p>I have constructed the following code:</p> <pre><code>class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() </code></pre> <p>But when I execute it, I receive the following error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) </code></pre> <p>It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. </p> <p>Any suggestions on how to best accomplish this?</p>
17
2009-03-19T03:26:56Z
660,968
<p>You define the run method to accept 3 arguments, but you call it with one argument (python calls it with the reference to the object).</p> <p>You need to pass the arguments to run instead of <code>__init__</code>.</p> <p>Or make the <code>__init__</code> method accept the arguments instead.</p>
0
2009-03-19T03:32:42Z
[ "python", "multithreading" ]
Overriding python threading.Thread.run()
660,961
<p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p> <blockquote> <p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.</p> </blockquote> <p>I have constructed the following code:</p> <pre><code>class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() </code></pre> <p>But when I execute it, I receive the following error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) </code></pre> <p>It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. </p> <p>Any suggestions on how to best accomplish this?</p>
17
2009-03-19T03:26:56Z
660,974
<p>You really don't need to subclass Thread. The only reason the API supports this is to make it more comfortable for people coming from Java where that's the only way to do it sanely.</p> <p>The pattern that we recommend you use is to pass a method to the Thread constructor, and just call .start().</p> <pre><code> def myfunc(arg1, arg2): print 'In thread' print 'args are', arg1, arg2 thread = Thread(target=myfunc, args=(destination_name, destination_config)) thread.start() </code></pre>
39
2009-03-19T03:35:18Z
[ "python", "multithreading" ]
Overriding python threading.Thread.run()
660,961
<p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p> <blockquote> <p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.</p> </blockquote> <p>I have constructed the following code:</p> <pre><code>class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() </code></pre> <p>But when I execute it, I receive the following error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) </code></pre> <p>It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. </p> <p>Any suggestions on how to best accomplish this?</p>
17
2009-03-19T03:26:56Z
4,890,401
<p>The documentation of threading.Thread may seem to imply that any unused positional and keyword args are passed to run. They are not.</p> <p>Any extra positional args and keyword kwargs are indeed trapped by the default threading.Thread.<strong>init</strong> method -- but they are ONLY passed to a method specified using target= keyword; they are NOT passed to the run() method.</p> <p>In fact, the documentation at <a href="http://docs.python.org/library/threading.html" rel="nofollow">http://docs.python.org/library/threading.html</a> makes it clear that it <em>is</em> the default run() method that invokes the supplied target= method with the trapped args and kwargs:</p> <blockquote> <p>"You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively."</p> </blockquote>
2
2011-02-03T18:53:50Z
[ "python", "multithreading" ]
Overriding python threading.Thread.run()
660,961
<p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p> <blockquote> <p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.</p> </blockquote> <p>I have constructed the following code:</p> <pre><code>class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() </code></pre> <p>But when I execute it, I receive the following error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) </code></pre> <p>It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. </p> <p>Any suggestions on how to best accomplish this?</p>
17
2009-03-19T03:26:56Z
4,974,726
<p>Here's is an example of passing arguments using threading and not extending <strong>init</strong>:</p> <pre><code>import threading class Example(threading.Thread): def run(self): print '%s from %s' % (self._Thread__kwargs['example'], self.name) example = Example(kwargs={'example': 'Hello World'}) example.start() example.join() </code></pre> <p>and here's using mutliprocessing:</p> <pre><code>import multiprocessing class Example(multiprocessing.Process): def run(self): print '%s from %s' % (self._kwargs['example'], self.name) example = Example(kwargs={'example': 'Hello World'}) example.start() example.join() </code></pre>
4
2011-02-11T22:29:40Z
[ "python", "multithreading" ]
Overriding python threading.Thread.run()
660,961
<p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p> <blockquote> <p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.</p> </blockquote> <p>I have constructed the following code:</p> <pre><code>class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() </code></pre> <p>But when I execute it, I receive the following error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) </code></pre> <p>It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. </p> <p>Any suggestions on how to best accomplish this?</p>
17
2009-03-19T03:26:56Z
19,942,496
<p>If you want to keep your object-oriented approach and also have run arguments, you can do the following:</p> <pre><code>import threading class Destination: def run(self, name, config): print 'In thread' destination = Destination() thread = threading.Thread(target=destination.run, args=(destination_name, destination_config)) thread.start() </code></pre> <p>As mentioned above, it could also be done with <code>partial</code></p> <pre><code>from functools import partial import threading class Destination: def run(self, name, config): print 'In thread' destination = Destination() thread = threading.Thread(target=partial( destination.run, destination_name, destination_config)) thread.start() </code></pre> <p>The advantage of doing this versus a purely-functional approach is that it lets you keep your other existing object-oriented code the same. The only change is to have it not subclass Thread, which shouldn't be a big deal, since per <code>threading.Thread</code> documentation: </p> <blockquote> <p>only override the <strong>init</strong>() and run() methods of this class</p> </blockquote> <p>If you were overriding Thread so that you could access the thread object from within your subclass, then I'd recommend just using threading.currentThread() from within your object. This way you segment the thread's namespace from your own, and per the "Zen of Python" by Tim Peters:</p> <blockquote> <p>Namespaces are one honking great idea -- let's do more of those!</p> </blockquote>
-1
2013-11-12T23:56:29Z
[ "python", "multithreading" ]
Overriding python threading.Thread.run()
660,961
<p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p> <blockquote> <p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.</p> </blockquote> <p>I have constructed the following code:</p> <pre><code>class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() </code></pre> <p>But when I execute it, I receive the following error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) </code></pre> <p>It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. </p> <p>Any suggestions on how to best accomplish this?</p>
17
2009-03-19T03:26:56Z
29,850,862
<p>In order to address some of the confusion about whether an overridden <code>run()</code> method takes additional arguments, here is an implementation of an overridden <code>run()</code> method that does what the method inherited from <code>threading.Thread</code> does.</p> <p>Note, this just to see how one would override <code>run()</code>; it is not meant to be a meaningful example. If all you want to do is invoking a target function with sequential and/or keyword arguments, it is not necessary to have a subclass; this has been pointed out e.g. in <a href="http://stackoverflow.com/questions/660961/overriding-python-threading-thread-run/660974#660974">Jerub's answer</a> to this question.</p> <p>The following code supports both Python v2 and v3.</p> <p>Although particularly the access to the mangled attribute names in the Python 2 code is ugly, I am not aware of another way to access these attributes (let me know if you know one...):</p> <pre><code>import sys import threading class DestinationThread(threading.Thread): def run(self): if sys.version_info[0] == 2: self._Thread__target(*self._Thread__args, **self._Thread__kwargs) else: # assuming v3 self._target(*self._args, **self._kwargs) def func(a, k): print("func(): a=%s, k=%s" % (a, k)) thread = DestinationThread(target=func, args=(1,), kwargs={"k": 2}) thread.start() thread.join() </code></pre> <p>It prints (tested with Python 2.6, 2.7, and 3.4 on Windows 7):</p> <pre><code>func(): a=1, k=2 </code></pre>
0
2015-04-24T14:59:59Z
[ "python", "multithreading" ]
Access to errno from Python?
661,017
<p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p> <p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p> <p>Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.</p> <p>Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.</p>
18
2009-03-19T04:00:33Z
661,030
<p>It looks like you can use this patch that will provide you with <code>ctypes.get_errno/set_errno</code></p> <p><a href="http://bugs.python.org/issue1798">http://bugs.python.org/issue1798</a></p> <p>This is the patch that was actually applied to the repository:</p> <p><a href="http://svn.python.org/view?view=rev&amp;revision=63977">http://svn.python.org/view?view=rev&amp;revision=63977</a></p> <p>Otherwise, adding a new C module that does nothing but return errno /is/ disgusting, but so is the library that you're using. I would do that in preference to patching python myself.</p>
6
2009-03-19T04:10:16Z
[ "python", "linux", "python-2.5", "errno" ]
Access to errno from Python?
661,017
<p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p> <p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p> <p>Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.</p> <p>Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.</p>
18
2009-03-19T04:00:33Z
661,150
<p>I'm not sure if this is what you and Jerub are referring to, but you could write a very short C extension that just exports errno, i.e. with <a href="http://www.python.org/doc/2.5.1/ext/simpleExample.html" rel="nofollow">the python language interface</a>. </p> <p>Otherwise, I agree with you that having to add this small bit of compiled code is a pain.</p>
1
2009-03-19T05:30:18Z
[ "python", "linux", "python-2.5", "errno" ]
Access to errno from Python?
661,017
<p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p> <p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p> <p>Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.</p> <p>Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.</p>
18
2009-03-19T04:00:33Z
661,295
<p>Gave up and tracked through the C headers.</p> <pre><code>import ctypes c = ctypes.CDLL("libc.so.6") c.__errno_location.restype = ctypes.POINTER(ctypes.c_int) c.write(5000, "foo", 4) print c.__errno_location().contents # -&gt; c_long(9) </code></pre> <p>It doesn't work in the python command prompt because it resets errno to read from stdin.</p> <p>Once you know the <a href="http://www.google.com/search?q=%5F%5Ferrno%5Flocation%2Bctypes">magic word of __errno_location</a> this looks like a common pattern. But with just <a href="http://www.google.com/search?q=errno%2Bctypes">errno</a> I was pretty lost.</p>
6
2009-03-19T07:18:23Z
[ "python", "linux", "python-2.5", "errno" ]
Access to errno from Python?
661,017
<p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p> <p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p> <p>Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.</p> <p>Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.</p>
18
2009-03-19T04:00:33Z
661,300
<p>Belowed code is not reliable (or comprehensive, there are a plefora of ways <code>errno</code> could be defined) but it should get you started (or reconsider your position on a tiny extension module (after all on Debian <code>python setup.py install</code> or <code>easy_install</code> should have no problem to build it)). From <a href="http://codespeak.net/pypy/dist/pypy/rpython/lltypesystem/ll2ctypes.py">http://codespeak.net/pypy/dist/pypy/rpython/lltypesystem/ll2ctypes.py</a></p> <pre><code>if not hasattr(ctypes, 'get_errno'): # Python 2.5 or older if sys.platform == 'win32': standard_c_lib._errno.restype = ctypes.POINTER(ctypes.c_int) def _where_is_errno(): return standard_c_lib._errno() elif sys.platform in ('linux2', 'freebsd6'): standard_c_lib.__errno_location.restype = ctypes.POINTER(ctypes.c_int) def _where_is_errno(): return standard_c_lib.__errno_location() elif sys.platform in ('darwin', 'freebsd7'): standard_c_lib.__error.restype = ctypes.POINTER(ctypes.c_int) def _where_is_errno(): return standard_c_lib.__error() ctypes.get_errno = lambda: _where_is_errno().contents.value </code></pre> <p>Where <code>standard_c_lib</code>:</p> <pre><code>def get_libc_name(): if sys.platform == 'win32': # Parses sys.version and deduces the version of the compiler import distutils.msvccompiler version = distutils.msvccompiler.get_build_version() if version is None: # This logic works with official builds of Python. if sys.version_info &lt; (2, 4): clibname = 'msvcrt' else: clibname = 'msvcr71' else: if version &lt;= 6: clibname = 'msvcrt' else: clibname = 'msvcr%d' % (version * 10) # If python was built with in debug mode import imp if imp.get_suffixes()[0][0] == '_d.pyd': clibname += 'd' return clibname+'.dll' else: return ctypes.util.find_library('c') # Make sure the name is determined during import, not at runtime libc_name = get_libc_name() standard_c_lib = ctypes.cdll.LoadLibrary(get_libc_name()) </code></pre>
11
2009-03-19T07:19:50Z
[ "python", "linux", "python-2.5", "errno" ]
Access to errno from Python?
661,017
<p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p> <p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p> <p>Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.</p> <p>Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.</p>
18
2009-03-19T04:00:33Z
661,303
<p>Here is a snippet of code that allows to access <code>errno</code>:</p> <pre><code>from ctypes import * libc = CDLL("libc.so.6") get_errno_loc = libc.__errno_location get_errno_loc.restype = POINTER(c_int) def errcheck(ret, func, args): if ret == -1: e = get_errno_loc()[0] raise OSError(e) return ret copen = libc.open copen.errcheck = errcheck print copen("nosuchfile", 0) </code></pre> <p>The important thing is that you check <code>errno</code> as soon as possible after your function call, otherwise it may already be overwritten.</p>
15
2009-03-19T07:20:16Z
[ "python", "linux", "python-2.5", "errno" ]
Access to errno from Python?
661,017
<p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p> <p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p> <p>Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me.</p> <p>Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.</p>
18
2009-03-19T04:00:33Z
6,170,629
<p>ctypes actually gives a standard way to access python's c implementation, which is using errno. I haven't tested this on anything other than my (linux) system, but this should be very portable:</p> <p>ctypes.c_int.in_dll(ctypes.pythonapi,"errno")</p> <p>which returns a c_int containing the current value.</p>
0
2011-05-29T21:47:21Z
[ "python", "linux", "python-2.5", "errno" ]
Can I make pdb start debugging right away?
661,034
<p>I want to debug a python project</p> <p>The problem is, I don't know where to set a break point,</p> <p>what I want to do, is be able to call a method </p> <pre><code>SomeClass( some_ctor_arguments ).some_method()` </code></pre> <p>and have the debugger be fired right away</p> <p>How do I do that?</p> <p>I tried <code>pdb.run( string_command )</code> but it doesn't seem to work right</p> <pre><code>&gt;&gt;&gt; import pdb &gt;&gt;&gt; import &lt;some-package&gt; &gt;&gt;&gt; pdb.run( .... ) &gt; &lt;string&gt;(1)&lt;module&gt;() (Pdb) s NameError: "name '&lt;some-package&gt;' is not defined" </code></pre>
5
2009-03-19T04:12:05Z
661,044
<p>Found it ..</p> <pre><code>pdb.runcall( object.method ) </code></pre>
5
2009-03-19T04:15:06Z
[ "python", "debugging", "pdb" ]
Can I make pdb start debugging right away?
661,034
<p>I want to debug a python project</p> <p>The problem is, I don't know where to set a break point,</p> <p>what I want to do, is be able to call a method </p> <pre><code>SomeClass( some_ctor_arguments ).some_method()` </code></pre> <p>and have the debugger be fired right away</p> <p>How do I do that?</p> <p>I tried <code>pdb.run( string_command )</code> but it doesn't seem to work right</p> <pre><code>&gt;&gt;&gt; import pdb &gt;&gt;&gt; import &lt;some-package&gt; &gt;&gt;&gt; pdb.run( .... ) &gt; &lt;string&gt;(1)&lt;module&gt;() (Pdb) s NameError: "name '&lt;some-package&gt;' is not defined" </code></pre>
5
2009-03-19T04:12:05Z
661,322
<pre><code>pdb.set_trace() </code></pre> <p>will start the debugger at this point.</p> <p>Place it at the beginning of the method you want to debug.</p>
4
2009-03-19T07:27:40Z
[ "python", "debugging", "pdb" ]
Security of Python's eval() on untrusted strings?
661,084
<p>If I am evaluating a Python string using eval(), and have a class like:</p> <pre><code>class Foo(object): a = 3 def bar(self, x): return x + a </code></pre> <p>What are the security risks if I do not trust the string? In particular:</p> <ol> <li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?</li> <li>Is <code>eval(string, {}, {})</code> unsafe? That is, can I reach os or sys entirely from builtins like len and list?</li> <li>Is there a way to make builtins not present at all in the eval context?</li> </ol> <p>There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.</p> <p>Obviously, <code>eval(string)</code> without custom dictionaries is unsafe in most cases.</p>
20
2009-03-19T04:39:50Z
661,128
<p><code>eval()</code> will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.</p> <p>There was recently a thread about how to do this kind of thing safely on the python-dev list, and the conclusions were:</p> <ul> <li>It's really hard to do this properly.</li> <li>It requires patches to the python interpreter to block many classes of attacks.</li> <li>Don't do it unless you really want to.</li> </ul> <p>Start here to read about the challenge: <a href="http://tav.espians.com/a-challenge-to-break-python-security.html">http://tav.espians.com/a-challenge-to-break-python-security.html</a> </p> <p>What situation do you want to use eval() in? Are you wanting a user to be able to execute arbitrary expressions? Or are you wanting to transfer data in some way? Perhaps it's possible to lock down the input in some way.</p>
41
2009-03-19T05:13:44Z
[ "python", "security", "eval" ]
Security of Python's eval() on untrusted strings?
661,084
<p>If I am evaluating a Python string using eval(), and have a class like:</p> <pre><code>class Foo(object): a = 3 def bar(self, x): return x + a </code></pre> <p>What are the security risks if I do not trust the string? In particular:</p> <ol> <li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?</li> <li>Is <code>eval(string, {}, {})</code> unsafe? That is, can I reach os or sys entirely from builtins like len and list?</li> <li>Is there a way to make builtins not present at all in the eval context?</li> </ol> <p>There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.</p> <p>Obviously, <code>eval(string)</code> without custom dictionaries is unsafe in most cases.</p>
20
2009-03-19T04:39:50Z
661,196
<p>You are probably better off turning the question around: </p> <ol> <li>What sort of expressions are you wanting to eval?</li> <li>Can you insure that only strings matching some narrowly defined syntax are eval()d?</li> <li>Then consider if <em>that</em> is safe.</li> </ol> <p>For example, if you are wanting to let the user enter an algebraic expression for evaluation, consider limiting them to one letter variable names, numbers, and a specific set of operators and functions. Don't eval() strings containing anything else.</p>
3
2009-03-19T05:57:13Z
[ "python", "security", "eval" ]
Security of Python's eval() on untrusted strings?
661,084
<p>If I am evaluating a Python string using eval(), and have a class like:</p> <pre><code>class Foo(object): a = 3 def bar(self, x): return x + a </code></pre> <p>What are the security risks if I do not trust the string? In particular:</p> <ol> <li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?</li> <li>Is <code>eval(string, {}, {})</code> unsafe? That is, can I reach os or sys entirely from builtins like len and list?</li> <li>Is there a way to make builtins not present at all in the eval context?</li> </ol> <p>There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.</p> <p>Obviously, <code>eval(string)</code> without custom dictionaries is unsafe in most cases.</p>
20
2009-03-19T04:39:50Z
663,953
<p>Note that even if you pass empty dictionaries to eval(), it's still possible to segfault (C)Python with some syntax tricks. For example, try this on your interpreter: <code>eval("()"*8**5)</code></p>
6
2009-03-19T20:36:24Z
[ "python", "security", "eval" ]
Security of Python's eval() on untrusted strings?
661,084
<p>If I am evaluating a Python string using eval(), and have a class like:</p> <pre><code>class Foo(object): a = 3 def bar(self, x): return x + a </code></pre> <p>What are the security risks if I do not trust the string? In particular:</p> <ol> <li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?</li> <li>Is <code>eval(string, {}, {})</code> unsafe? That is, can I reach os or sys entirely from builtins like len and list?</li> <li>Is there a way to make builtins not present at all in the eval context?</li> </ol> <p>There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.</p> <p>Obviously, <code>eval(string)</code> without custom dictionaries is unsafe in most cases.</p>
20
2009-03-19T04:39:50Z
664,224
<p>You can get to <code>os</code> using builtin functions: <code>__import__('os')</code>.</p> <p>For python 2.6+, the <a href="http://docs.python.org/library/ast.html#ast-helpers">ast module</a> may help; in particular <code>ast.literal_eval</code>, although it depends on exactly what you want to eval.</p>
9
2009-03-19T21:55:19Z
[ "python", "security", "eval" ]
Security of Python's eval() on untrusted strings?
661,084
<p>If I am evaluating a Python string using eval(), and have a class like:</p> <pre><code>class Foo(object): a = 3 def bar(self, x): return x + a </code></pre> <p>What are the security risks if I do not trust the string? In particular:</p> <ol> <li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?</li> <li>Is <code>eval(string, {}, {})</code> unsafe? That is, can I reach os or sys entirely from builtins like len and list?</li> <li>Is there a way to make builtins not present at all in the eval context?</li> </ol> <p>There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.</p> <p>Obviously, <code>eval(string)</code> without custom dictionaries is unsafe in most cases.</p>
20
2009-03-19T04:39:50Z
1,994,506
<p>There is a very good <a href="http://www.diveintopython3.net/advanced-iterators.html#eval" rel="nofollow">article on the un-safety of <code>eval()</code></a> in Mark Pilgrim's <a href="http://www.diveintopython3.net/" rel="nofollow">Dive into Python</a> tutorial.</p> <p>Quoted from this article: </p> <blockquote> <p>In the end, it is possible to safely evaluate untrusted Python expressions, for some definition of “safe” that turns out not to be terribly useful in real life. It’s fine if you’re just playing around, and it’s fine if you only ever pass it trusted input. But anything else is just asking for trouble.</p> </blockquote>
1
2010-01-03T10:14:40Z
[ "python", "security", "eval" ]
Security of Python's eval() on untrusted strings?
661,084
<p>If I am evaluating a Python string using eval(), and have a class like:</p> <pre><code>class Foo(object): a = 3 def bar(self, x): return x + a </code></pre> <p>What are the security risks if I do not trust the string? In particular:</p> <ol> <li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?</li> <li>Is <code>eval(string, {}, {})</code> unsafe? That is, can I reach os or sys entirely from builtins like len and list?</li> <li>Is there a way to make builtins not present at all in the eval context?</li> </ol> <p>There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.</p> <p>Obviously, <code>eval(string)</code> without custom dictionaries is unsafe in most cases.</p>
20
2009-03-19T04:39:50Z
10,964,364
<p>You cannot secure eval with a blacklist approach like this. See <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html">Eval really is dangerous</a> for examples of input that will segfault the CPython interpreter, give access to any class you like, and so on.</p>
11
2012-06-09T20:28:25Z
[ "python", "security", "eval" ]
Is there a parser/way available to parser Wikipedia dump files using Python?
661,584
<p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p> <p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer any parser in python. If not suggest one and I will try to write a port of it in python and contribute it to the web, so other persons make use of it or at least try it. </p> <p>So all I want is a python parser to parse Wikipedia dump files. I started writing a manual parser which parses each node and gets the stuff done.</p>
6
2009-03-19T09:44:26Z
661,625
<p>There is example code for the same at <a href="http://jjinux.blogspot.com/2009/01/python-parsing-wikipedia-dumps-using.html" rel="nofollow">http://jjinux.blogspot.com/2009/01/python-parsing-wikipedia-dumps-using.html</a></p>
3
2009-03-19T10:00:28Z
[ "python", "xml", "parsing", "wiki", "wikipedia" ]
Is there a parser/way available to parser Wikipedia dump files using Python?
661,584
<p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p> <p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer any parser in python. If not suggest one and I will try to write a port of it in python and contribute it to the web, so other persons make use of it or at least try it. </p> <p>So all I want is a python parser to parse Wikipedia dump files. I started writing a manual parser which parses each node and gets the stuff done.</p>
6
2009-03-19T09:44:26Z
661,626
<p>I don't know about licensing, but <a href="http://linux.softpedia.com/get/Education/Wikipedia-Dump-Reader-30091.shtml" rel="nofollow">this</a> is implemented in python, and includes the source.</p>
1
2009-03-19T10:00:45Z
[ "python", "xml", "parsing", "wiki", "wikipedia" ]
Is there a parser/way available to parser Wikipedia dump files using Python?
661,584
<p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p> <p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer any parser in python. If not suggest one and I will try to write a port of it in python and contribute it to the web, so other persons make use of it or at least try it. </p> <p>So all I want is a python parser to parse Wikipedia dump files. I started writing a manual parser which parses each node and gets the stuff done.</p>
6
2009-03-19T09:44:26Z
922,960
<p>Another good module is <em>mwlib</em> from <a href="http://code.pediapress.com/wiki/wiki/mwlib" rel="nofollow">here</a> - it is a pain to install with all dependencies (at least on Windows), but it works well.</p>
1
2009-05-28T20:23:25Z
[ "python", "xml", "parsing", "wiki", "wikipedia" ]
Is there a parser/way available to parser Wikipedia dump files using Python?
661,584
<p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p> <p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer any parser in python. If not suggest one and I will try to write a port of it in python and contribute it to the web, so other persons make use of it or at least try it. </p> <p>So all I want is a python parser to parse Wikipedia dump files. I started writing a manual parser which parses each node and gets the stuff done.</p>
6
2009-03-19T09:44:26Z
28,220,070
<p><a href="https://dizzylogic.com/wikiparser" rel="nofollow">Wiki Parser</a> is a very fast parser for Wikipedia dump files (~2 hours to parse all 55GB of English Wikipedia). It produces XML that preserves both content and article structure.</p> <p>You can then use python to do anything you want with the XML output.</p>
0
2015-01-29T16:46:08Z
[ "python", "xml", "parsing", "wiki", "wikipedia" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
661,624
<pre><code>&gt;&gt;&gt; gen = (i for i in []) &gt;&gt;&gt; next(gen) Traceback (most recent call last): File "&lt;pyshell#43&gt;", line 1, in &lt;module&gt; next(gen) StopIteration </code></pre> <p>At the end of generator <code>StopIteration</code> is raised, since in your case end is reached immediately, exception is raised. <strong>But normally you shouldn't check for existence of next value.</strong></p> <p>another thing you can do is:</p> <pre><code>&gt;&gt;&gt; gen = (i for i in []) &gt;&gt;&gt; if not list(gen): print('empty generator') </code></pre>
1
2009-03-19T10:00:23Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
661,653
<p>Sorry for the obvious approach, but the best way would be to do:</p> <pre><code>for item in my_generator: print item </code></pre> <p>Now you have detected that the generator is empty while you are using it. Of course, item will never be displayed if the generator is empty.</p> <p>This may not exactly fit in with your code, but this is what the idiom of the generator is for: iterating, so perhaps you might change your approach slightly, or not use generators at all.</p>
2
2009-03-19T10:14:14Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
661,673
<p>I hate to offer a second solution, especially one that I would not use myself, but, if you absolutely <em>had</em> to do this and to not consume the generator, as in other answers:</p> <pre><code>def do_something_with_item(item): print item empty_marker = object() try: first_item = my_generator.next() except StopIteration: print 'The generator was empty' first_item = empty_marker if first_item is not empty_marker: do_something_with_item(first_item) for item in my_generator: do_something_with_item(item) </code></pre> <p>Now I really don't like this solution, because I believe that this is not how generators are to be used.</p>
7
2009-03-19T10:23:37Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
661,765
<p>Here is a recipe for an iterator wrapper, it probably allows to do what you want:</p> <p><a href="http://code.activestate.com/recipes/502304/" rel="nofollow">http://code.activestate.com/recipes/502304/</a></p> <p>Note: I have not tested if it works or not. Nor am I sure that the functionality is useful.</p>
3
2009-03-19T10:59:03Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
661,967
<p>The best approach, IMHO, would be to avoid a special test. Most times, use of a generator <em>is</em> the test:</p> <pre><code>thing_generated = False # Nothing is lost here. if nothing is generated, # the for block is not executed. Often, that's the only check # you need to do. This can be done in the course of doing # the work you wanted to do anyway on the generated output. for thing in my_generator(): thing_generated = True do_work(thing) </code></pre> <p>If that's not good enough, you can still perform an explicit test. At this point, <code>thing</code> will contain the last value generated. If nothing was generated, it will be undefined - unless you've already defined the variable. You could check the value of <code>thing</code>, but that's a bit unreliable. Instead, just set a flag within the block and check it afterward:</p> <pre><code>if not thing_generated: print "Avast, ye scurvy dog!" </code></pre>
6
2009-03-19T12:08:48Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
662,925
<p>The simple answer to your question: no, there is no simple way. There are a whole lot of work-arounds.</p> <p>There really shouldn't be a simple way, because of what generators are: a way to output a sequence of values <em>without holding the sequence in memory</em>. So there's no backward traversal.</p> <p>You could write a has_next function or maybe even slap it on to a generator as a method with a fancy decorator if you wanted to.</p>
25
2009-03-19T16:25:12Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
664,239
<p>Suggestion:</p> <pre><code>def peek(iterable): try: first = next(iterable) except StopIteration: return None return first, itertools.chain([first], iterable) </code></pre> <p>Usage:</p> <pre><code>res = peek(mysequence) if res is None: # sequence is empty. Do stuff. else: first, mysequence = res # Do something with first, maybe? # Then iterate over the sequence: for element in mysequence: # etc. </code></pre>
33
2009-03-19T22:01:31Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
7,971,996
<p>If you need to know <em>before</em> you use the generator, then no, there is no simple way. If you can wait until <em>after</em> you have used the generator, there is a simple way:</p> <pre><code>was_empty = True for some_item in some_generator: was_empty = False do_something_with(some_item) if was_empty: handle_already_empty_generator_case() </code></pre>
0
2011-11-01T19:47:29Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
21,525,143
<p>A simple way is to use the optional parameter for <a href="http://docs.python.org/2/library/functions.html#next" rel="nofollow">next()</a> which is used if the generator is exhausted (or empty). For example: </p> <pre><code>iterable = some_generator() _exhausted = object() if next(iterable, _exhausted) == _exhausted: print('generator is empty') </code></pre> <p><em>Edit: Corrected the problem pointed out in mehtunguh's comment.</em></p>
7
2014-02-03T10:41:42Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
22,594,020
<p>I realize that this post is 5 years old at this point, but I found it while looking for an idiomatic way of doing this, and did not see my solution posted. So for posterity:</p> <pre><code>import itertools def get_generator(): """ Returns (bool, generator) where bool is true iff the generator is not empty. """ gen = (i for i in [0, 1, 2, 3, 4]) a, b = itertools.tee(gen) try: a.next() except StopIteration: return (False, b) return (True, b) </code></pre> <p>Of course, as I'm sure many commentators will point out, this is hacky and only works at all in certain limited situations (where the generators are side-effect free, for example). YMMV.</p>
2
2014-03-23T17:02:20Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
24,199,042
<p>All you need to do to see if the generator is empty is to try to get the next result. Of course if you're not <em>ready</em> to use that result then you have to store it to return it again later.</p> <p>Here's a wrapper class that can be added to an existing iterator to add an <code>__nonzero__</code> test, so you can see if the generator is empty with a simple <code>if</code>. It can probably also be turned into a decorator.</p> <pre><code>class GenWrapper: def __init__(self, iter): self.source = iter self.stored = False def __iter__(self): return self def __nonzero__(self): if self.stored: return True try: self.value = self.source.next() self.stored = True except StopIteration: return False return True def next(self): if self.stored: self.stored = False return self.value return self.source.next() </code></pre> <p>Here's how you'd use it:</p> <pre><code>with open(filename, 'r') as f: f = GenWrapper(f) if f: print 'Not empty' else: print 'Empty' </code></pre>
2
2014-06-13T06:30:58Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
32,039,643
<p>Here is my simple approach that i use to keep on returning an iterator while checking if something was yielded I just check if the loop runs:</p> <pre><code> n = 0 for key, value in iterator: n+=1 yield key, value if n == 0: print ("nothing found in iterator) break </code></pre>
0
2015-08-16T20:32:33Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
37,375,898
<p><code>next(generator, None) is not None</code></p> <p>Or replace <code>None</code> but whatever value you know it's <em>not</em> in your generator.</p>
5
2016-05-22T14:58:54Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
37,821,192
<p>I solved it by using the sum function. See below for an example I used with glob.iglob (which returns a generator).</p> <pre><code>def isEmpty(): files = glob.iglob(search) if sum(1 for _ in files): return True return False </code></pre> <p>*This will probably not work for HUGE generators but should perform nicely for smaller lists</p>
-1
2016-06-14T20:09:31Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
38,087,154
<p>Simply wrap the generator with <a href="https://docs.python.org/2.7/library/itertools.html#itertools.chain" rel="nofollow">itertools.chain</a>, put something that will represent the end of the iterable as the second iterable, then simply check for that.</p> <p>Ex:</p> <pre><code>import itertools g = some_iterable eog = object() wrap_g = itertools.chain(g, [eog]) </code></pre> <p>Now all that's left is to check for that value we appended to the end of the iterable, when you read it then that will signify the end</p> <pre><code>for value in wrap_g: if value == eog: # DING DING! We just found the last element of the iterable pass # Do something </code></pre>
0
2016-06-28T22:14:12Z
[ "python", "generator" ]
How do I know if a generator is empty from the start?
661,603
<p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
57
2009-03-19T09:51:24Z
38,650,175
<p>Here's a simple decorator which wraps the generator, so it returns None if empty. This can be useful if your code needs to know whether the generator will produce anything <em>before</em> looping through it.</p> <pre><code>def generator_or_none(func): """Wrap a generator function, returning None if it's empty. """ def inner(*args, **kwargs): # peek at the first item; return None if it doesn't exist try: next(func(*args, **kwargs)) except StopIteration: return None # return original generator otherwise first item will be missing return func(*args, **kwargs) return inner </code></pre> <p>Usage:</p> <pre><code>import random @generator_or_none def random_length_generator(): for i in range(random.randint(0, 10)): yield i gen = random_length_generator() if gen is None: print('Generator is empty') </code></pre> <p>One example where this is useful is in templating code - i.e. jinja2</p> <pre><code>{% if content_generator %} &lt;section&gt; &lt;h4&gt;Section title&lt;/h4&gt; {% for item in content_generator %} {{ item }} {% endfor % &lt;/section&gt; {% endif %} </code></pre>
0
2016-07-29T03:43:42Z
[ "python", "generator" ]
Can I use a single file as a buffer? I.e. write to and read from at same time
661,826
<p>I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.</p> <p>The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the same file using the monitor application. The writer application is C++, and the reader is currently Python on Win32 XP.</p> <p>Are there libraries to do this? Has anyone seen examples of this?</p> <p>I don't want to have to use a database as I don't want to link to a database library in the applcation. I.e. don't have space and may not be supported on the embedded platform.</p> <p>Another way to do this is over a network connection, but I figure files are the simplest solution.</p>
2
2009-03-19T11:20:44Z
661,836
<p>Most systems has several solutions for what you want to do, such as pipes and unix sockets. These are intended for this, unlike regular files. There are however programs that does this on regular files, and I think the clearest example of this is the unix-utility tail, which can "follow" a file.</p> <p>Take a look at<br /> <a href="http://msdn.microsoft.com/en-us/library/aa365590(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa365590(VS.85).aspx</a></p> <p>Python has a good wrapper library for win32, so anything you see there can probably be access from python.</p>
4
2009-03-19T11:26:55Z
[ "python", "file-io" ]
Can I use a single file as a buffer? I.e. write to and read from at same time
661,826
<p>I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.</p> <p>The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the same file using the monitor application. The writer application is C++, and the reader is currently Python on Win32 XP.</p> <p>Are there libraries to do this? Has anyone seen examples of this?</p> <p>I don't want to have to use a database as I don't want to link to a database library in the applcation. I.e. don't have space and may not be supported on the embedded platform.</p> <p>Another way to do this is over a network connection, but I figure files are the simplest solution.</p>
2
2009-03-19T11:20:44Z
661,992
<p>What you're talking about is called "Interprocess Communication". There are lots of ways of doing this.</p> <p>Using Unix pipes.</p> <p><a href="https://docs.python.org/library/pipes.html" rel="nofollow">https://docs.python.org/library/pipes.html</a></p> <p>Using sockets.</p> <p><a href="https://docs.python.org/library/socket.html" rel="nofollow">https://docs.python.org/library/socket.html</a></p> <p>Using queues.</p> <p><a href="https://docs.python.org/library/queue.html" rel="nofollow">https://docs.python.org/library/queue.html</a></p> <p>Any of these is better than file I/O.</p>
1
2009-03-19T12:17:51Z
[ "python", "file-io" ]
Can I use a single file as a buffer? I.e. write to and read from at same time
661,826
<p>I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.</p> <p>The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the same file using the monitor application. The writer application is C++, and the reader is currently Python on Win32 XP.</p> <p>Are there libraries to do this? Has anyone seen examples of this?</p> <p>I don't want to have to use a database as I don't want to link to a database library in the applcation. I.e. don't have space and may not be supported on the embedded platform.</p> <p>Another way to do this is over a network connection, but I figure files are the simplest solution.</p>
2
2009-03-19T11:20:44Z
669,335
<p>You can use memory-mapped files, standard Python module called mmap.</p>
2
2009-03-21T13:48:06Z
[ "python", "file-io" ]
write a table with empty cells based on dictionary of values
662,463
<p>I have this view in my app:</p> <pre><code>def context_detail(request, context_id): c = get_object_or_404(Context, pk=context_id) scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True) total = sum(sc.count for sc in scs) table = [] forms = [] for a in c.assemblage_set.all(): for sc in a.sherdcount_set.all(): forms.append(sc.typename) forms_set = set(forms) for a in c.assemblage_set.all(): diko = {} diko['assemblage'] = a for f in forms_set: for sc in a.sherdcount_set.all(): if f == sc.typename: diko[f] = sc.count else: diko[f] = 0 table.append(diko) return render_to_response('tesi/context_detail.html', {'context': c, 'total': total, 'sherdcounts': scs, 'table': table, 'forms': forms_set}, context_instance=RequestContext(request)) </code></pre> <p>The aim of the two for loops would be that of creating a list of dictionaries that holds values of SherdCount.count with reference to the SherdCount.typename foreign key (and I was able to do that, even if the current code is a bit messed up).</p> <p>The "table" list should contain something like this:</p> <pre><code>[{&lt;Type: Hayes 61B&gt;: 0, &lt;Type: Hayes 99A-B&gt;: 0, &lt;Type: Hayes 105&gt;: 0, &lt;Type: Hayes 104A&gt;: 0, &lt;Type: Hayes 104B&gt;: 0, &lt;Type: Hayes 103&gt;: 0, &lt;Type: Hayes 91&gt;: 0, &lt;Type: Hayes 91A&gt;: 0, &lt;Type: Hayes 91B&gt;: 0, &lt;Type: Hayes 91C&gt;: 0, &lt;Type: Hayes 91D&gt;: 0, &lt;Type: Hayes 85B&gt;: 0, &lt;Type: Hayes 82A&gt;: 0, &lt;Type: Hayes 76&gt;: 0, &lt;Type: Hayes 73&gt;: 0, &lt;Type: Hayes 72&gt;: 0, &lt;Type: Hayes 70&gt;: 0, &lt;Type: Hayes 68&gt;: 0, &lt;Type: Hayes 67&gt;: 0, &lt;Type: Hayes 66&gt;: 0, &lt;Type: Hayes 62A&gt;: 0, &lt;Type: Hayes 80B&gt;: 0, &lt;Type: Hayes 59&gt;: 0, &lt;Type: Hayes 61A&gt;: 0, &lt;Type: Hayes 91A-B&gt;: 0, &lt;Type: Hayes 58&gt;: 0, &lt;Type: Hayes 50&gt;: 0, &lt;Type: Hayes 53&gt;: 0, &lt;Type: Hayes 71&gt;: 0, &lt;Type: Hayes 60&gt;: 0, &lt;Type: Hayes 80A&gt;: 0, &lt;Type: Hayes Style A2-3&gt;: 0, &lt;Type: Hayes Style B&gt;: 0, &lt;Type: Hayes Style E1&gt;: 1, 'assemblage': &lt;Assemblage: Brescia, Santa Giulia : non periodizzato&gt;}, {&lt;Type: Hayes 61B&gt;: 0, &lt;Type: Hayes 99A-B&gt;: 0, &lt;Type: Hayes 105&gt;: 0, &lt;Type: Hayes 104A&gt;: 0, &lt;Type: Hayes 104B&gt;: 0, &lt;Type: Hayes 103&gt;: 0, &lt;Type: Hayes 91&gt;: 0, &lt;Type: Hayes 91A&gt;: 0, &lt;Type: Hayes 91B&gt;: 0, &lt;Type: Hayes 91C&gt;: 0, &lt;Type: Hayes 91D&gt;: 0, &lt;Type: Hayes 85B&gt;: 0, &lt;Type: Hayes 82A&gt;: 0, &lt;Type: Hayes 76&gt;: 0, &lt;Type: Hayes 73&gt;: 0, &lt;Type: Hayes 72&gt;: 0, &lt;Type: Hayes 70&gt;: 0, &lt;Type: Hayes 68&gt;: 0, &lt;Type: Hayes 67&gt;: 0, &lt;Type: Hayes 66&gt;: 0, &lt;Type: Hayes 62A&gt;: 0, &lt;Type: Hayes 80B&gt;: 0, &lt;Type: Hayes 59&gt;: 0, &lt;Type: Hayes 61A&gt;: 0, &lt;Type: Hayes 91A-B&gt;: 0, &lt;Type: Hayes 58&gt;: 0, &lt;Type: Hayes 50&gt;: 0, &lt;Type: Hayes 53&gt;: 0, &lt;Type: Hayes 71&gt;: 0, &lt;Type: Hayes 60&gt;: 0, &lt;Type: Hayes 80A&gt;: 0, &lt;Type: Hayes Style A2-3&gt;: 0, &lt;Type: Hayes Style B&gt;: 3, &lt;Type: Hayes Style E1&gt;: 0, 'assemblage': &lt;Assemblage: Brescia, Santa Giulia : Periodo IIIA&gt;}, </code></pre> <p>But the many 0 values are obviously wrong. even though there might be some zeros (the empty cells I was referring to)</p> <p>The question is, once I have built such a list, how do I create a table in the template with all the cells (e.g. 1 row per Type and 1 column per Context, with SherdCount at cells) ?</p> <p>Steko</p>
1
2009-03-19T14:40:44Z
663,424
<p>Here's the data structure.</p> <pre><code>[{&lt;Type1&gt;: 16, &lt;Type2&gt;: 10, &lt;Type3&gt;: 12, &lt;Type4&gt;: 7, &lt;Type5&gt;: 0, 'assemblage': &lt;Assemblage1&gt;}, {&lt;Type1&gt;: 85, &lt;Type2&gt;: 18, &lt;Type3&gt;: 21, &lt;Type4&gt;: 12, &lt;Type5&gt;: 2, 'assemblage': &lt;Assemblage2&gt;}, ...] </code></pre> <p>The problem is that the resulting table must be generated in row order, and this list of dictionaries is in column order. So the list of dicts must be pivoted into row-major order.</p> <pre><code>from collections import defaultdict titles = [] cells = defaultdict(list) for x,col in enumerate(table): titles.append( col['assemblage'] ) for rk in col: if rk == 'assemblage': continue # skip the title cells[rk][x]= col[rk] </code></pre> <p>Also, it helps to formalize the results as a list of lists; dictionaries have no inherent order.</p> <pre><code>final= [] for name in sorted( cells.keys() ): final.append( cells[name] ) </code></pre> <p>Here's the template to render <code>titles</code> and <code>final</code> as a table.</p> <pre><code>&lt;table&gt; &lt;tr&gt; {% for t in titles %}&lt;th&gt;{{t}}&lt;/th&gt;{% endfor %} &lt;/tr&gt; {% for row in final %} &lt;tr&gt; {% for cell in row %}&lt;td&gt;{{cell}}&lt;/td&gt;{% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre>
2
2009-03-19T18:25:34Z
[ "python", "django", "django-templates" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
662,713
<blockquote> <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> </blockquote> <p>With minidom no, the datatype used to store attributes is an unordered dictionary. <a href="http://www.doxdesk.com/software/py/pxdom.html">pxdom</a> can do it, though it is considerably slower.</p>
6
2009-03-19T15:42:55Z
[ "python", "xml", "minidom" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
989,585
<p>I've ended up using the <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> library instead of minidom.</p>
0
2009-06-13T00:11:41Z
[ "python", "xml", "minidom" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
5,908,853
<p>It is clear that xml attribute are not ordered. I just have found this strange behavior !</p> <p>It seems that this related to a sort added in xml.dom.minidom.Element.writexml function !!</p> <pre><code>class Element(Node): ... snip ... def writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"&lt;" + self.tagName) attrs = self._get_attributes() a_names = attrs.keys() a_names.sort() --------^^^^^^^^^^^^^^ for a_name in a_names: writer.write(" %s=\"" % a_name) _write_data(writer, attrs[a_name].value) writer.write("\"") </code></pre> <p>Removing the line restore a behavior which keep the order of the original document. It is a good idea when you have to check with diff tools that there is not a mistake in your code.</p>
2
2011-05-06T08:36:58Z
[ "python", "xml", "minidom" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
8,345,268
<p>To keep the attribute order I made this slight modification in minidom:</p> <pre><code>from collections import OrderedDict </code></pre> <p>In the Element class : </p> <pre><code>__init__(...) self._attrs = OrderedDict() #self._attrs = {} writexml(...) #a_names.sort() </code></pre> <p>Now this will only work with Python 2.7+ And I'm not sure if it actually works => Use at your own risks...</p> <p>And please note that you should not rely on attribute order:</p> <p><em>Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.</em></p>
5
2011-12-01T17:00:35Z
[ "python", "xml", "minidom" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
8,429,008
<p>Before Python 2.7, I used following <em>hotpatching</em>:</p> <pre><code>class _MinidomHooker(object): def __enter__(self): minidom.NamedNodeMap.keys_orig = minidom.NamedNodeMap.keys minidom.NamedNodeMap.keys = self._NamedNodeMap_keys_hook return self def __exit__(self, *args): minidom.NamedNodeMap.keys = minidom.NamedNodeMap.keys_orig del minidom.NamedNodeMap.keys_orig @staticmethod def _NamedNodeMap_keys_hook(node_map): class OrderPreservingList(list): def sort(self): pass return OrderPreservingList(node_map.keys_orig()) </code></pre> <p>Used this way:</p> <pre><code>with _MinidomHooker(): document.writexml(...) </code></pre> <p>Disclaimer:</p> <ol> <li>thou shall not rely on the order of attributes.</li> <li>mutating the NamedNodeMap class is not thread safe.</li> <li><em>hotpatching</em> is evil.</li> </ol>
2
2011-12-08T09:47:45Z
[ "python", "xml", "minidom" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
22,303,750
<p>You guys can put up as many disclaimers you want. While reordering the attributes has no meaning for the program it does have a meaning for the programmer/user.</p> <p>For Fredrick it was important to have the RGB order since that is how the order of the colors is. For me it is the name attribute in particular.</p> <p>Compare</p> <pre><code>&lt;field name="url" type="string" indexed="true" stored="true" required="true" multiValued="false"/&gt; &lt;!-- ID --&gt; &lt;field name="forkortelse" type="string" indexed="true" stored="true" required="false" multiValued="false" /&gt; &lt;field name="kortform" type="text_general" indexed="true" stored="true" required="false" multiValued="false" /&gt; &lt;field name="dato" type="date" indexed="true" stored="true" required="false" multiValued="false" /&gt; &lt;field name="nummer" type="int" indexed="true" stored="true" required="false" multiValued="false" /&gt; &lt;field name="kilde" type="string" indexed="true" stored="true" required="false" multiValued="false" /&gt; &lt;field name="tittel" type="text_general" indexed="true" stored="true" multiValued="true"/&gt; </code></pre> <p>Against</p> <pre><code>&lt;field indexed="true" multiValued="false" name="forkortelse" required="false" stored="true" type="string"/&gt; &lt;field indexed="true" multiValued="false" name="kortform" required="false" stored="true" type="text_general"/&gt; &lt;field indexed="true" multiValued="false" name="dato" required="false" stored="true" type="date"/&gt; &lt;field indexed="true" multiValued="false" name="nummer" required="false" stored="true" type="int"/&gt; &lt;field indexed="true" multiValued="false" name="kilde" required="false" stored="true" type="string"/&gt; &lt;field an_optional_attr="OMG!" an_optional_attr2="OMG!!" indexed="true" name="tittel" stored="true" type="text_general"/&gt; </code></pre> <p>While it is not impossible to read it is not as easy. The name is the important attribute. Hiding the name field way back is no good. What if the name was 15 attributes to the left where 7 of the attributes in front was optional?</p> <p>The point is that the reordering is a bigger problem than what the acsending ordering gives in return. It messes with the way the programmer thinks or how the functionality is supposed to work. At least the ordering should be configurable/optional. </p> <p>Excuse my poor english. It is not my main language. </p>
1
2014-03-10T15:02:13Z
[ "python", "xml", "minidom" ]
Preserve order of attributes when modifying with minidom
662,624
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p> <p>Say I have: <code>&lt;color red="255" green="255" blue="233" /&gt;</code> when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order.</p> <p>I am processing the file by looping through the elements returned by <code>elements = doc.getElementsByTagName('color')</code> and then I do assignments like this <code>e.attributes["red"].value = "233"</code>.</p>
6
2009-03-19T15:23:11Z
29,696,911
<p><strong>1.Custom your own 'Element.writexml' method.</strong></p> <p>from 'minidom.py' copy Element's writexml code to your own file.</p> <p>rename it to writexml_nosort,</p> <p>delete 'a_names.sort()' (python 2.7) or change 'a_names = sorted(attrs.keys())' to 'a_names = attrs.keys()'(python 3.4)</p> <p>change the Element's method to your own:</p> <p>minidom.Element.writexml = writexml_nosort;</p> <p><strong>2.custom your favorite order:</strong> </p> <p>right_order = ['a', 'b', 'c', 'a1', 'b1']</p> <p><strong>3.adjust your element 's _attrs</strong></p> <p>node._attrs = OrderedDict( [(k,node._attrs[k]) for k in right_order ] )</p>
0
2015-04-17T10:37:44Z
[ "python", "xml", "minidom" ]
How to Alter Photographed Document to Look "Scanned"
662,638
<p>How can I <a href="http://www.techcrunch.com/2009/03/17/jotnot-turns-your-iphones-camera-into-a-document-scanner/" rel="nofollow">do this</a> in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it?</p> <p>Also, are there any other manipulations I should do to make it look more "scan-like"?</p> <p>I want to make a simple version of this program for myself in Python.</p>
6
2009-03-19T15:27:18Z
662,694
<p>Look at transform() with method set to QUAD</p> <p><a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">http://effbot.org/imagingbook/image.htm</a></p> <blockquote> <pre><code>im.transform(size, QUAD, data) =&gt; image im.transform(size, QUAD, data, filter) =&gt; image </code></pre> <p>Maps a quadrilateral (a region defined by four corners) from the image to a rectangle with the given size.</p> <p>Data is an 8-tuple (x0, y0, x1, y1, x2, y2, y3, y3) which contain the upper left, lower left, lower right, and upper right corner of the source quadrilateral.</p> </blockquote>
8
2009-03-19T15:37:38Z
[ "python", "image-processing", "python-imaging-library", "image-scanner" ]
Help with subprocess.call on a Windows machine
662,641
<p>I am trying to modify a <a href="http://trac.edgewall.org" rel="nofollow">trac</a> plugin that allows downloading of wiki pages to word documents. pagetodoc.py throws an exception on this line:</p> <pre><code># Call the subprocess using convenience method retval = subprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close_fds = True) </code></pre> <p>Saying that <code>close_fds</code> is not supported on Windows. The process seems to create some temporary files in C:\Windows\Temp. I tried removing the <code>close_fds</code> parameter, but then files the subprocess writes to stay open indefinitely. An exception is then thrown when the files are written to later. This is my first time working with Python, and I am not familiar with the libraries. It is even more difficult since most people probably code on Unix machines. Any ideas how I can rework this code?</p> <p>Thanks!</p>
2
2009-03-19T15:27:59Z
663,054
<p>close_fds <em><a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow">is</a></em> supported on windows starting with python 2.6 (if stdin/stdout/stderr are not redirected). you might consider upgrading.</p>
1
2009-03-19T16:59:33Z
[ "python", "trac", "python-2.4" ]
Can I write Python web application for Windows and Linux platforms at the same time?
662,762
<p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p> <p>CGI? Maybe something new? WSGI | FastCGI ? </p>
3
2009-03-19T15:52:10Z
662,784
<p>web.py includes a server... It will do the trick for small jobs.</p> <p>By the way, Apache works on windows.</p>
2
2009-03-19T15:55:29Z
[ "python", "cgi", "fastcgi", "wsgi" ]
Can I write Python web application for Windows and Linux platforms at the same time?
662,762
<p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p> <p>CGI? Maybe something new? WSGI | FastCGI ? </p>
3
2009-03-19T15:52:10Z
662,789
<p>Yes you can. But you can also use apache on windows. If you go the IIS way there's only CGI and it's pretty hard to set up. You can also use python based server like CherryPy which is pretty good and will work on all platforms with python.</p> <p>Some frameworks like django support both CGI and WSGI, so you don't have to worry about the details of WSGI or CGI much.</p> <p>If you ask me, WSGI is the future for python web apps.</p>
7
2009-03-19T15:55:57Z
[ "python", "cgi", "fastcgi", "wsgi" ]
Can I write Python web application for Windows and Linux platforms at the same time?
662,762
<p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p> <p>CGI? Maybe something new? WSGI | FastCGI ? </p>
3
2009-03-19T15:52:10Z
662,791
<p>Yes, if you use CGI, FastCGI or depending on your framework, even a self-contained web server (so IIS and Apache would be a reverse-proxy) then that would all work.</p> <p>The difference will be the configuration of the OS-specific servers, and also your Python environment on each OS. So you may find yourself doing a small bit of work at the beginning to make sure your paths are right, etc.</p>
2
2009-03-19T15:56:14Z
[ "python", "cgi", "fastcgi", "wsgi" ]
Can I write Python web application for Windows and Linux platforms at the same time?
662,762
<p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p> <p>CGI? Maybe something new? WSGI | FastCGI ? </p>
3
2009-03-19T15:52:10Z
662,826
<p>A rather big Python based web framework is <a href="http://www.zope.org/" rel="nofollow">ZOPE</a>.</p> <blockquote> <p>Zope is an open source application server for building content management systems, intranets, portals, and custom applications. The Zope community consists of hundreds of companies and thousands of developers all over the world, working on building the platform and Zope applications. Zope is written in Python, a highly-productive, object-oriented scripting language</p> </blockquote> <p>ZOPE is available on Linux and Windows, and you can use Python to write your <em>Zope Web Apps</em> (it includes a simpler templating system, too).</p>
2
2009-03-19T16:03:33Z
[ "python", "cgi", "fastcgi", "wsgi" ]
Can I write Python web application for Windows and Linux platforms at the same time?
662,762
<p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p> <p>CGI? Maybe something new? WSGI | FastCGI ? </p>
3
2009-03-19T15:52:10Z
663,304
<p>consider also the possibility of using web2Py, or XML-RPC implementation, or Twisted...</p>
0
2009-03-19T17:56:23Z
[ "python", "cgi", "fastcgi", "wsgi" ]