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
listlengths
1
5
How to exit from Python without traceback?
1,187,970
<p>I would like to know how to I exit from Python without having an traceback dump on the output. </p> <p>I still want want to be able to return an error code but I do not want to display the traceback log.</p> <p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
156
2009-07-27T12:44:15Z
1,190,864
<p>Perhaps you're trying to catch all exceptions and this is catching the <code>SystemExit</code> exception raised by <code>sys.exit()</code>?</p> <pre><code>import sys try: sys.exit(1) # Or something that calls sys.exit() except SystemExit as e: sys.exit(e) except: # Cleanup and reraise. This will print a backtrace. # (Insert your cleanup code here.) raise </code></pre> <p>In general, using <code>except:</code> without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like <code>SystemExit</code> -- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with:</p> <pre><code>import sys sys.exit(1) # Or something that calls sys.exit(). </code></pre> <p>If you need to exit without raising <code>SystemExit</code>:</p> <pre><code>import os os._exit(1) </code></pre> <p>I do this, in code that runs under unittest and calls <code>fork()</code>. Unittest gets when the forked process raises <code>SystemExit</code>. This is definitely a corner case!</p>
49
2009-07-27T21:55:27Z
[ "python", "exit", "traceback" ]
How to exit from Python without traceback?
1,187,970
<p>I would like to know how to I exit from Python without having an traceback dump on the output. </p> <p>I still want want to be able to return an error code but I do not want to display the traceback log.</p> <p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
156
2009-07-27T12:44:15Z
24,333,416
<pre><code># Pygame Example import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('IBM Emulator') BLACK = (0, 0, 0) GREEN = (0, 255, 0) fontObj = pygame.font.Font('freesansbold.ttf', 32) textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK) textRectObj = textSurfaceObj.get_rect() textRectObj = (10, 10) try: while True: # main loop DISPLAYSURF.fill(BLACK) DISPLAYSURF.blit(textSurfaceObj, textRectObj) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() except SystemExit: pass </code></pre>
-5
2014-06-20T18:21:48Z
[ "python", "exit", "traceback" ]
How to exit from Python without traceback?
1,187,970
<p>I would like to know how to I exit from Python without having an traceback dump on the output. </p> <p>I still want want to be able to return an error code but I do not want to display the traceback log.</p> <p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
156
2009-07-27T12:44:15Z
26,246,313
<p>I would do it this way:</p> <pre><code>import sys def do_my_stuff(): pass if __name__ == "__main__": try: do_my_stuff() except SystemExit, e: print(e) </code></pre>
1
2014-10-07T22:27:04Z
[ "python", "exit", "traceback" ]
How to exit from Python without traceback?
1,187,970
<p>I would like to know how to I exit from Python without having an traceback dump on the output. </p> <p>I still want want to be able to return an error code but I do not want to display the traceback log.</p> <p>I want to be able to exit using <code>exit(number)</code> without trace but in case of an Exception (not an exit) I want the trace.</p>
156
2009-07-27T12:44:15Z
39,143,539
<p>It's much better practise to avoid using sys.exit() and instead raise/handle exceptions to allow the program to finish cleanly. If you want to turn off traceback, simply use:</p> <pre><code>sys.trackbacklimit=0 </code></pre> <p>You can set this at the top of your script to squash all traceback output, but I prefer to use it more sparingly, for example "known errors" where I want the output to be clean, e.g. in the file foo.py:</p> <pre><code>import sys from subprocess import * try: check_call([ 'uptime', '--help' ]) except CalledProcessError: sys.tracebacklimit=0 print "Process failed" raise print "This message should never follow an error." </code></pre> <p>If CalledProcessError is caught, the output will look like this:</p> <pre><code>[me@test01 dev]$ ./foo.py usage: uptime [-V] -V display version Process failed subprocess.CalledProcessError: Command '['uptime', '--help']' returned non-zero exit status 1 </code></pre> <p>If any other error occurs, we still get the full traceback output.</p>
2
2016-08-25T11:03:05Z
[ "python", "exit", "traceback" ]
Reusing a Django app within a single project
1,188,052
<p>In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, and then have it function as two separate apps with separate databases, etc.</p> <p>To clarify, consider the following: hypothetically speaking, I would like to have a single, generic news_content app, containing all the relevant models, views, url structure and templatetags, which I could then include and extend where necessary as many times as I like into a single project.</p> <p>It breaks down as follows:</p> <pre><code>news_content/ templatetags/ __init__.py news_content.py __init__.py models.py (defines generic models - news_item, category, etc.) views.py (generic views for news, archiving, etc.) urls.py admin.py </code></pre> <p>Is there a way to include this app multiple times in a project under various names? I feel like it should be obvious and I'm just not thinking clearly about it. Does anybody have any experience with this?</p> <p>I'd appreciate any advice people can give. Thank you.</p>
3
2009-07-27T13:02:10Z
1,188,120
<p>In this case you could create the common piece of code as a Python module instead of a whole new application.</p> <p>Then for each instance you would like to use it, create an app and import the bits from that module.</p>
2
2009-07-27T13:18:51Z
[ "python", "django" ]
Reusing a Django app within a single project
1,188,052
<p>In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, and then have it function as two separate apps with separate databases, etc.</p> <p>To clarify, consider the following: hypothetically speaking, I would like to have a single, generic news_content app, containing all the relevant models, views, url structure and templatetags, which I could then include and extend where necessary as many times as I like into a single project.</p> <p>It breaks down as follows:</p> <pre><code>news_content/ templatetags/ __init__.py news_content.py __init__.py models.py (defines generic models - news_item, category, etc.) views.py (generic views for news, archiving, etc.) urls.py admin.py </code></pre> <p>Is there a way to include this app multiple times in a project under various names? I feel like it should be obvious and I'm just not thinking clearly about it. Does anybody have any experience with this?</p> <p>I'd appreciate any advice people can give. Thank you.</p>
3
2009-07-27T13:02:10Z
1,188,246
<p>What's the actual difference between blogs and news? Perhaps that difference ought to be part of the blog/news app and you include it just once.</p> <p>If you have a blog page with blog entries and a news page with news entries and the only difference is a field in the database (kind_of_item = "blog" vs. kind_of_item = "news") then perhaps have you have this.</p> <p>urls.py</p> <pre><code>(r'^/(?P&lt;kind&gt;blog)/$', 'view.stuff'), (r'^/(?P&lt;kind&gt;news)/$', 'view.stuff'), </code></pre> <p>views.py</p> <pre><code>def stuff( request, kind ): content= news_blog.objects.filter( kind=kind ) return render_to_response( kind+"_page", { 'content': content } ) </code></pre> <p>Perhaps you don't need the same app twice, but need to extend the app to handle both use cases.</p>
3
2009-07-27T13:47:35Z
[ "python", "django" ]
Reusing a Django app within a single project
1,188,052
<p>In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, and then have it function as two separate apps with separate databases, etc.</p> <p>To clarify, consider the following: hypothetically speaking, I would like to have a single, generic news_content app, containing all the relevant models, views, url structure and templatetags, which I could then include and extend where necessary as many times as I like into a single project.</p> <p>It breaks down as follows:</p> <pre><code>news_content/ templatetags/ __init__.py news_content.py __init__.py models.py (defines generic models - news_item, category, etc.) views.py (generic views for news, archiving, etc.) urls.py admin.py </code></pre> <p>Is there a way to include this app multiple times in a project under various names? I feel like it should be obvious and I'm just not thinking clearly about it. Does anybody have any experience with this?</p> <p>I'd appreciate any advice people can give. Thank you.</p>
3
2009-07-27T13:02:10Z
1,188,819
<p>I'm not 100% sure I understand your question, so I'm going to list my understanding, and let me know if it is different from yours.</p> <ol> <li>You want to have a "news" and a "blog" section of your website with identical functionality.</li> <li>You want to have "news" and "blog" entries stored separately in the database so they don't end up intermingling.</li> </ol> <p>If this is the case, I'd suggest making an API to your views. Something like this:</p> <p><code>views.py</code>:</p> <pre><code>def view_article(request, article_slug, template_name='view_article.html', form_class=CommentForm, model_class=NewsArticle, success_url=None, ): </code></pre> <p><code>urls.py</code>:</p> <pre><code>(r'^news/(?P&lt;article_slug&gt;[-\w]+)/$', 'view_article', {}, "view_news_article"), (r'^blog/(?P&lt;article_slug&gt;[-\w]+)/$', 'view_article', {'model_class': BlogArticle}, "view_blog_article"), </code></pre> <p>This makes your app highly reusable by offering the ability to override the <code>template</code>, <code>form</code>, <code>model</code>, and <code>success_url</code> straight from <code>urls.py</code>.</p>
1
2009-07-27T15:23:19Z
[ "python", "django" ]
Bizzare eclipse-pydev console behavior
1,188,103
<p>Stumbled upon some seemingly random character mangling in eclipse-pydev console: specific characters are read from stdout as '\xd0?' (first byte correct, second "?")</p> <p>Is there some solution to this?</p> <p>(PyDEV 1.4.6, Python 2.6, console encoding - inherited UTF-8, Eclipse 3.5, WinXP with UK locale)</p> <p>Code:</p> <pre><code>import sys if __name__ == "__main__": for l in sys.stdin: print 'Byte: ', repr(l) try: u = repr(unicode(l)) print 'Unicode:', u except Exception, e: print 'Fail: ', e </code></pre> <p>Input:</p> <pre><code>йцукенгшщзхъ фывапролджэ ячсмитьбю ЙЦУКЕНГШЩЗХЪ ФЫВАПРОЛДЖЭ ЯЧСМИТЬБЮ </code></pre> <p>and output:</p> <pre><code>Byte: '\xd0\xb9\xd1\x86\xd1\x83\xd0\xba\xd0\xb5\xd0\xbd\xd0\xb3\xd1\x88\xd1\x89\xd0\xb7\xd1\x85\xd1\x8a\r\n' Unicode: u'\u0439\u0446\u0443\u043a\u0435\u043d\u0433\u0448\u0449\u0437\u0445\u044a\r\n' Byte: '\xd1\x84\xd1\x8b\xd0\xb2\xd0\xb0\xd0\xbf\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb4\xd0\xb6\xd1?\r\n' Fail: 'utf8' codec can't decode bytes in position 20-21: invalid data Byte: '\xd1?\xd1\x87\xd1?\xd0\xbc\xd0\xb8\xd1\x82\xd1\x8c\xd0\xb1\xd1\x8e\r\n' Fail: 'utf8' codec can't decode bytes in position 0-1: invalid data Byte: '\xd0\x99\xd0\xa6\xd0\xa3\xd0\x9a\xd0\x95\xd0?\xd0\x93\xd0\xa8\xd0\xa9\xd0\x97\xd0\xa5\xd0\xaa\r\n' Fail: 'utf8' codec can't decode bytes in position 10-11: invalid data Byte: '\xd0\xa4\xd0\xab\xd0\x92\xd0?\xd0\x9f\xd0\xa0\xd0\x9e\xd0\x9b\xd0\x94\xd0\x96\xd0\xad\r\n' Fail: 'utf8' codec can't decode bytes in position 6-7: invalid data Byte: '\xd0\xaf\xd0\xa7\xd0\xa1\xd0\x9c\xd0\x98\xd0\xa2\xd0\xac\xd0\x91\xd0\xae\r\n' Unicode: u'\u042f\u0427\u0421\u041c\u0418\u0422\u042c\u0411\u042e\r\n' </code></pre>
1
2009-07-27T13:15:32Z
1,188,516
<p>I'm not too sure about input encoding, but I've found that with output encoding to tty streams, an explicit encoding step was needed for Python 2.x but not for Python 3.x.</p> <p>So for input you may need an explicit decode step using e.g. <code>l.decode(sys.stdin.encoding)</code>.</p> <p>Does it work OK in a vanilla Python console?</p>
0
2009-07-27T14:31:48Z
[ "python", "utf-8", "pydev" ]
Bizzare eclipse-pydev console behavior
1,188,103
<p>Stumbled upon some seemingly random character mangling in eclipse-pydev console: specific characters are read from stdout as '\xd0?' (first byte correct, second "?")</p> <p>Is there some solution to this?</p> <p>(PyDEV 1.4.6, Python 2.6, console encoding - inherited UTF-8, Eclipse 3.5, WinXP with UK locale)</p> <p>Code:</p> <pre><code>import sys if __name__ == "__main__": for l in sys.stdin: print 'Byte: ', repr(l) try: u = repr(unicode(l)) print 'Unicode:', u except Exception, e: print 'Fail: ', e </code></pre> <p>Input:</p> <pre><code>йцукенгшщзхъ фывапролджэ ячсмитьбю ЙЦУКЕНГШЩЗХЪ ФЫВАПРОЛДЖЭ ЯЧСМИТЬБЮ </code></pre> <p>and output:</p> <pre><code>Byte: '\xd0\xb9\xd1\x86\xd1\x83\xd0\xba\xd0\xb5\xd0\xbd\xd0\xb3\xd1\x88\xd1\x89\xd0\xb7\xd1\x85\xd1\x8a\r\n' Unicode: u'\u0439\u0446\u0443\u043a\u0435\u043d\u0433\u0448\u0449\u0437\u0445\u044a\r\n' Byte: '\xd1\x84\xd1\x8b\xd0\xb2\xd0\xb0\xd0\xbf\xd1\x80\xd0\xbe\xd0\xbb\xd0\xb4\xd0\xb6\xd1?\r\n' Fail: 'utf8' codec can't decode bytes in position 20-21: invalid data Byte: '\xd1?\xd1\x87\xd1?\xd0\xbc\xd0\xb8\xd1\x82\xd1\x8c\xd0\xb1\xd1\x8e\r\n' Fail: 'utf8' codec can't decode bytes in position 0-1: invalid data Byte: '\xd0\x99\xd0\xa6\xd0\xa3\xd0\x9a\xd0\x95\xd0?\xd0\x93\xd0\xa8\xd0\xa9\xd0\x97\xd0\xa5\xd0\xaa\r\n' Fail: 'utf8' codec can't decode bytes in position 10-11: invalid data Byte: '\xd0\xa4\xd0\xab\xd0\x92\xd0?\xd0\x9f\xd0\xa0\xd0\x9e\xd0\x9b\xd0\x94\xd0\x96\xd0\xad\r\n' Fail: 'utf8' codec can't decode bytes in position 6-7: invalid data Byte: '\xd0\xaf\xd0\xa7\xd0\xa1\xd0\x9c\xd0\x98\xd0\xa2\xd0\xac\xd0\x91\xd0\xae\r\n' Unicode: u'\u042f\u0427\u0421\u041c\u0418\u0422\u042c\u0411\u042e\r\n' </code></pre>
1
2009-07-27T13:15:32Z
1,189,434
<p>Well, I don't know how to fix it, but I have deduced the pattern in what goes wrong.</p> <p>The bytes that get replaced with "?" are precisely those bytes that are not defined in <a href="http://en.wikipedia.org/wiki/Windows-1252" rel="nofollow">windows-1252</a> - that is, bytes 0x81, 0x8d, 0x8f, 0x90, and 0x9d.</p> <p>What this looks like to me is that somehow you're getting this series of translations:</p> <ul> <li><p>unicode input -> series of bytes in utf-8</p></li> <li><p>utf-8 bytes -> read by something that expects the input to be Windows-1252, and so translates impossible bytes to "<code>?</code>"</p></li> <li><p>the characters in converted back to bytes via windows-1252, and fed into your variable <code>l</code>.</p></li> </ul> <p>Does this version of pydev give <code>sys.stdin.encoding</code> a decent value? And how does <code>sys.stdin.encoding</code> compare to the result of <code>sys.getdefaultencoding()</code>?</p>
2
2009-07-27T17:15:26Z
[ "python", "utf-8", "pydev" ]
How to specify which eth interface Django test server should listen on?
1,188,205
<p>As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server should use?</p> <p>-- Added --</p> <p>The network configuration is here. I'm connecting to the machine via 143.248.x.y address from my PC. (My PC is also in 143.248.a.b network.) But I cannot find this address. Normal apache works very well as well as other custom daemons running on other ports.</p> <p>The one who configured this machine is not me, so I don't know much details of the network...</p> <pre><code>eth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78 inet addr:192.168.6.100 Bcast:192.168.2.255 Mask:255.255.255.0 inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:441917680 errors:0 dropped:0 overruns:0 frame:0 TX packets:357190979 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:191664873035 (178.5 GB) TX bytes:324846526526 (302.5 GB) eth1 Link encap:Ethernet HWaddr 00:15:17:88:97:79 inet addr:172.10.1.100 Bcast:172.10.1.255 Mask:255.255.255.0 inet6 addr: fe80::215:17ff:fe88:9779/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1113794891 errors:0 dropped:97 overruns:0 frame:0 TX packets:699821135 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:843942929141 (785.9 GB) TX bytes:838436421169 (780.8 GB) Base address:0x2000 Memory:b8800000-b8820000 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:1085510396 errors:0 dropped:0 overruns:0 frame:0 TX packets:1085510396 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:422100792153 (393.1 GB) TX bytes:422100792153 (393.1 GB) peth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78 inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1 RX packets:441918386 errors:0 dropped:742 overruns:0 frame:0 TX packets:515286699 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:199626686230 (185.9 GB) TX bytes:337365591758 (314.1 GB) Base address:0x2020 Memory:b8820000-b8840000 veth0 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth1 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth2 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth3 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.0 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.1 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.2 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.3 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) </code></pre> <p>-- Added (2) --</p> <p>Finally I used w3m (a text-mode web browser which runs on terminal) to connect from localhost. :P</p>
11
2009-07-27T13:38:43Z
1,188,299
<p>No. It's not how it works. The interfase has an IP address, you have a network with the test server and your PC. You should connect to that IP (possibly with an alternative port that you specified), and that's all. If you only have these two devices in the network, it is most likely that both of them should have static IP addresses. (or, if there is not mutual network, you cannot connect to each other).</p>
0
2009-07-27T13:58:00Z
[ "python", "django", "networking", "ethernet" ]
How to specify which eth interface Django test server should listen on?
1,188,205
<p>As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server should use?</p> <p>-- Added --</p> <p>The network configuration is here. I'm connecting to the machine via 143.248.x.y address from my PC. (My PC is also in 143.248.a.b network.) But I cannot find this address. Normal apache works very well as well as other custom daemons running on other ports.</p> <p>The one who configured this machine is not me, so I don't know much details of the network...</p> <pre><code>eth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78 inet addr:192.168.6.100 Bcast:192.168.2.255 Mask:255.255.255.0 inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:441917680 errors:0 dropped:0 overruns:0 frame:0 TX packets:357190979 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:191664873035 (178.5 GB) TX bytes:324846526526 (302.5 GB) eth1 Link encap:Ethernet HWaddr 00:15:17:88:97:79 inet addr:172.10.1.100 Bcast:172.10.1.255 Mask:255.255.255.0 inet6 addr: fe80::215:17ff:fe88:9779/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1113794891 errors:0 dropped:97 overruns:0 frame:0 TX packets:699821135 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:843942929141 (785.9 GB) TX bytes:838436421169 (780.8 GB) Base address:0x2000 Memory:b8800000-b8820000 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:1085510396 errors:0 dropped:0 overruns:0 frame:0 TX packets:1085510396 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:422100792153 (393.1 GB) TX bytes:422100792153 (393.1 GB) peth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78 inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1 RX packets:441918386 errors:0 dropped:742 overruns:0 frame:0 TX packets:515286699 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:199626686230 (185.9 GB) TX bytes:337365591758 (314.1 GB) Base address:0x2020 Memory:b8820000-b8840000 veth0 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth1 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth2 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth3 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.0 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.1 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.2 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.3 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) </code></pre> <p>-- Added (2) --</p> <p>Finally I used w3m (a text-mode web browser which runs on terminal) to connect from localhost. :P</p>
11
2009-07-27T13:38:43Z
1,188,333
<p>Yes, if the IP of your interface is for example 192.168.1.2 and you want to run on port 8080, start the development server like this:</p> <pre><code>./manage.py runserver 192.168.1.2:8080 </code></pre>
2
2009-07-27T14:05:11Z
[ "python", "django", "networking", "ethernet" ]
How to specify which eth interface Django test server should listen on?
1,188,205
<p>As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server should use?</p> <p>-- Added --</p> <p>The network configuration is here. I'm connecting to the machine via 143.248.x.y address from my PC. (My PC is also in 143.248.a.b network.) But I cannot find this address. Normal apache works very well as well as other custom daemons running on other ports.</p> <p>The one who configured this machine is not me, so I don't know much details of the network...</p> <pre><code>eth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78 inet addr:192.168.6.100 Bcast:192.168.2.255 Mask:255.255.255.0 inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:441917680 errors:0 dropped:0 overruns:0 frame:0 TX packets:357190979 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:191664873035 (178.5 GB) TX bytes:324846526526 (302.5 GB) eth1 Link encap:Ethernet HWaddr 00:15:17:88:97:79 inet addr:172.10.1.100 Bcast:172.10.1.255 Mask:255.255.255.0 inet6 addr: fe80::215:17ff:fe88:9779/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1113794891 errors:0 dropped:97 overruns:0 frame:0 TX packets:699821135 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:843942929141 (785.9 GB) TX bytes:838436421169 (780.8 GB) Base address:0x2000 Memory:b8800000-b8820000 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:1085510396 errors:0 dropped:0 overruns:0 frame:0 TX packets:1085510396 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:422100792153 (393.1 GB) TX bytes:422100792153 (393.1 GB) peth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78 inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1 RX packets:441918386 errors:0 dropped:742 overruns:0 frame:0 TX packets:515286699 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:199626686230 (185.9 GB) TX bytes:337365591758 (314.1 GB) Base address:0x2020 Memory:b8820000-b8840000 veth0 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth1 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth2 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) veth3 Link encap:Ethernet HWaddr 00:00:00:00:00:00 BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.0 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.1 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.2 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) vif0.3 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) </code></pre> <p>-- Added (2) --</p> <p>Finally I used w3m (a text-mode web browser which runs on terminal) to connect from localhost. :P</p>
11
2009-07-27T13:38:43Z
1,188,359
<p>I think the OP is referring to having multiple interfaces configured on the test machine.</p> <p>You can specify the IP address that Django will bind to as follows:</p> <pre><code># python manage.py runserver 0.0.0.0:8000 </code></pre> <p>This would bind Django to all interfaces on port 8000. You can pass any active IP address in place of 0.0.0.0, so simply use the IP address of the interface you want to bind to.</p> <p>Hope this helps.</p>
27
2009-07-27T14:09:34Z
[ "python", "django", "networking", "ethernet" ]
Writing in file's actual position in Python
1,188,214
<p>I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:</p> <pre><code>"123456789" (before) "123\n456\n789" (after) </code></pre> <p>I've tried with this:</p> <pre><code>f = open(file, "r+") f.write("123456789") f.seek(3, 0) f.write("\n") f.seek(0) f.read() </code></pre> <p>-> '123\n56789'</p> <p>I want it not to substitute the character in position n, but only to insert another ("\n") char in that position.</p> <p>Any idea about how to do this? Thanks</p>
2
2009-07-27T13:40:53Z
1,188,221
<p>I don't think there is any way to do that in the way you are trying to: you would have to read in to the end of the file from the position you want to insert, then write your new character at the position you wish it to be, then write the original data back after it. This is the same way things would work in C or any language with a seek() type API.</p> <p>Alternatively, read the file into a string, then use list methods to insert your data.</p> <pre><code>source_file = open("myfile", "r") file_data = list(source_file.read()) source_file.close() file_data.insert(position, data) open("myfile", "wb").write(file_data) </code></pre>
7
2009-07-27T13:43:45Z
[ "python", "file" ]
Writing in file's actual position in Python
1,188,214
<p>I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:</p> <pre><code>"123456789" (before) "123\n456\n789" (after) </code></pre> <p>I've tried with this:</p> <pre><code>f = open(file, "r+") f.write("123456789") f.seek(3, 0) f.write("\n") f.seek(0) f.read() </code></pre> <p>-> '123\n56789'</p> <p>I want it not to substitute the character in position n, but only to insert another ("\n") char in that position.</p> <p>Any idea about how to do this? Thanks</p>
2
2009-07-27T13:40:53Z
1,188,262
<pre><code>with open(file, 'r+') as f: data = f.read() f.seek(0) for i in range(len(data)): # could also use 'for i, chara in enumerate(data):' and then 'f.write(chara)' instead of 'f.write(data[i])' if (i + 1) % 3 == 0: # could also do 'if i % 3 == 2:', but that may be slightly confusing f.write('\n') else: f.write(data[i]) </code></pre> <p>I don't think it's all that Pythonic (due to the <code>range(len(data))</code>), but it should work, unless your data file is really really large (in which case you'll have to process the data in the file part by part and store the results in another file to prevent overwriting data you haven't processed yet).</p> <p>(<a href="http://docs.python.org/3.1/reference/compound%5Fstmts.html#the-with-statement" rel="nofollow">More on the <code>with</code> statement.</a>)</p>
1
2009-07-27T13:50:48Z
[ "python", "file" ]
Writing in file's actual position in Python
1,188,214
<p>I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:</p> <pre><code>"123456789" (before) "123\n456\n789" (after) </code></pre> <p>I've tried with this:</p> <pre><code>f = open(file, "r+") f.write("123456789") f.seek(3, 0) f.write("\n") f.seek(0) f.read() </code></pre> <p>-> '123\n56789'</p> <p>I want it not to substitute the character in position n, but only to insert another ("\n") char in that position.</p> <p>Any idea about how to do this? Thanks</p>
2
2009-07-27T13:40:53Z
1,188,527
<p>You can think a file is just an array of characters, and if you want to insert a new element in the middle of an array, then you have to shift all the elements that are after it.</p> <p>You could do what you say if the file contained a "linked list" of chars or "extends", but then you would need a special editor to see it sequentially.</p>
0
2009-07-27T14:33:55Z
[ "python", "file" ]
Why Python omits attribute in the SOAP message?
1,188,367
<p>I have a web service that returns following type:</p> <pre><code>&lt;xsd:complexType name="TaggerResponse"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="msg" type="xsd:string"&gt;&lt;/xsd:element&gt; &lt;/xsd:sequence&gt; &lt;xsd:attribute name="status" type="tns:Status"&gt;&lt;/xsd:attribute&gt; &lt;/xsd:complexType&gt; </code></pre> <p>The type contains one element (<code>msg</code>) and one attribute (<code>status</code>). </p> <p>To communicate with the web service I use SOAPpy library. Below is a sample result return by the web service (SOAP message):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;SOAP-ENV:Body&gt; &lt;SOAP-ENV:TagResponse&gt; &lt;parameters status="2"&gt; &lt;msg&gt;text&lt;/msg&gt; &lt;/parameters&gt; &lt;/SOAP-ENV:TagResponse&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>Python parses this message as:</p> <pre><code>&lt;SOAPpy.Types.structType parameters at 157796908&gt;: {'msg': 'text'} </code></pre> <p>As you can see the attribute is lost. What should I do to get the value of "<code>status</code>"?</p>
0
2009-07-27T14:10:55Z
1,188,395
<p>The response example you posted (the actual XML coming back from the WS request) does not have the value in it you are looking for! I would suggest this is why SOAPpy cannot return it to you.</p> <p>If it is a case of making your code have consistent behaviour in cases where the value is returned and when it isn't then try using <code>dict</code>'s <code>get()</code> method to get the value:</p> <pre><code>attribute_value = result.get("attribute", None) </code></pre> <p>Then you can test the result for none. You can also do so like this:</p> <pre><code>if not "attribute" in result: ...handle case where there is no attribute value... </code></pre>
1
2009-07-27T14:15:21Z
[ "python", "web-services", "soap", "wsdl", "soappy" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,188,679
<p>Note that not all objects may be directly pickled - only basic types, or objects that have defined the pickle protocol.<br /> Using your own binary format would allow you to potentially store any kind of object.</p> <p>Just for note, Zope Object DB (ZODB) is following that very same approach, storing objects with the Pickle format. You may be interested in getting their implementations.</p>
2
2009-07-27T14:59:48Z
[ "python", "database", "data-structures", "persistence" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,188,704
<p>Pickling is a two-face coin.</p> <p>On one side, you have a way to store your object in a very easy way. Just four lines of code and you pickle. You have the object exactly as it is.</p> <p>On the other side, it can become a compatibility nightmare. You cannot unpickle objects if they are not defined in your code, exactly as they were defined when pickled. This strongly limits your ability to refactor the code, or rearrange stuff in your modules. Also, not everything can be pickled, and if you are not strict on what gets pickled and the client of your code has full freedom of including any object, sooner or later it will pass something unpicklable to your system, and the system will go boom.</p> <p>Be very careful about its use. there's no better definition of quick and dirty.</p>
9
2009-07-27T15:04:38Z
[ "python", "database", "data-structures", "persistence" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,188,711
<p>The potential advantages of a custom format over a pickle are:</p> <ul> <li>you can selectively get individual objects, rather than having to incarnate the full set of objects</li> <li>you can query subsets of objects by properties, and only load those objects that match your criteria</li> </ul> <p>Whether these advantages materialize depends on how you design the storage, of course.</p>
1
2009-07-27T15:06:16Z
[ "python", "database", "data-structures", "persistence" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,188,810
<p>One reason to define your own custom binary format could be optimization. pickle (and shelve, which uses pickle) is a generic serialization framework; it can store almost any Python data. It's easy to use pickle in a lot of situations, but it takes time to inspect all the objects and serialize their data and the data itself is stored in a generic, verbose format. If you are storing specific known data a custom-built serializer can be both faster and more concise. </p> <p>It takes 37 bytes to pickle an object with a single integer value:</p> <pre>>>> import pickle >>> class Foo: pass... >>> foo = Foo() >>> foo.x = 3 >>> print repr(pickle.dumps(foo)) "(i__main__\nFoo\np0\n(dp1\nS'x'\np2\nI3\nsb." </pre> <p>Embedded in that data is the name of the property and its type. A custom serializer for Foo (and Foo alone) could dispense with that and just store the number, saving both time and space.</p> <p>Another reason for a custom serialization framework is you can easily do custom validation and versioning of data. If you change your object types and need to load an old version of data it can be tricky via pickle. Your own code can be easily customized to handle older data formats. </p> <p>In practice, I'd build something using the generic cPickle module and only replace it if profiling indicated it was really important. Maintaining a separate serialization framework is a significant amount of work.</p> <p>One final resource you may find useful: <a href="http://kbyanc.blogspot.com/2007/07/python-serializer-benchmarks.html" rel="nofollow">some synthetic serializer benchmarks</a>. cPickle is pretty fast.</p>
3
2009-07-27T15:20:59Z
[ "python", "database", "data-structures", "persistence" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,189,525
<p>If you are going to do that (implement your own binary format), you should first know that python has a good library to handle HDF5, a binary format used in physics and astronomy to dump huge amounts of data.</p> <p>This is the home page of the library:</p> <ul> <li><a href="http://www.pytables.org/moin" rel="nofollow">http://www.pytables.org/moin</a></li> </ul> <p>Basically, you could think of HDF5 as an hierarchical database, in which a table column can contain an inner table by itself: the table Populations has a column called Individual, which is a table containing the informations of every individuals, etc...</p> <p>PyTables has also its own implementation of the cPickle module, you can access it with:</p> <pre><code>$ easy_install tables $ python &gt;&gt;&gt; import tables &gt;&gt;&gt; tables.cPickle </code></pre> <p>I have never used pytable's pickle, but I think it may be straightforward for you to learn how does it work, so you may have a look at it before implementing your own format.</p>
1
2009-07-27T17:29:00Z
[ "python", "database", "data-structures", "persistence" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,189,928
<p>Will you ever need to process data from untrusted sources? If so, you should know that the pickle format is actually a virtual machine that is capable of executing arbitrary code on behalf of the process doing the unpickling.</p>
0
2009-07-27T18:49:42Z
[ "python", "database", "data-structures", "persistence" ]
What are the benefits of not using cPickle to create a persistent storage for data?
1,188,585
<p>I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?</p>
5
2009-07-27T14:45:12Z
1,416,946
<p>See this solution at SourceForge:</p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p> <p>[The commentary included with the source endnotes discusses why pickle was selected over json.]</p>
1
2009-09-13T05:42:39Z
[ "python", "database", "data-structures", "persistence" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,657
<p>It is considered "Good Form" to group all imports together at the start of the file.</p> <blockquote> <p>Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.</p> </blockquote> <p>From here: <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">http://docs.python.org/tutorial/modules.html</a></p>
7
2009-07-27T14:57:15Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,662
<p>It's generally considered bad practice, but sometimes it's unavoidable (say when you have to avoid a circular import).</p> <p>An example of a time when it is necessary: I use <a href="http://code.google.com/p/waf/">Waf</a> to build all our code. The system is split into tools, and each tool is implemented in it's own module. Each tool module can implent a <code>detect()</code> method to detect if the pre-requisites are present. An example of one of these may do the following:</p> <pre><code>def detect(self): import foobar </code></pre> <p>If this works correctly, the tool is usable. Then later in the same module the <code>foobar</code> module may be needed, so you would have to import it again, at function level scope. Clearly if it was imported at module level things would blow up completely.</p>
5
2009-07-27T14:57:40Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,672
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> authoritatively states:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>PEP 8 should be the basis of any "in-house" style guide, since it summarizes what the core Python team has found to be the most effective style, overall (and with individual dissent of course, as on any other language, but consensus and the BDFL agree on PEP 8).</p>
41
2009-07-27T14:59:05Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,674
<p>If the imported module is infrequently used and the import is expensive, the in-the-middle-import is OK.</p> <p><strong>Otherwise, is it wise to follow Alex Martelli's suggestion.</strong></p>
9
2009-07-27T14:59:13Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,676
<p><a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>It is not bad practice to have scopped imports. So that the import applies only to the function you used it in.</p> <p>I think the code would be more readable though if the imports where grouped together at the top of the block or if you want it globally at the top of the file. </p>
2
2009-07-27T14:59:36Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,684
<p>Well, I think it is a good practice to group all imports together at start of file since everyone knows where to look if want to know which libs are loaded</p>
2
2009-07-27T15:00:08Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,693
<p>There was a detailed discussion of this topic on the Python mailing list in 2001:</p> <p><a href="https://mail.python.org/pipermail/python-list/2001-July/071567.html" rel="nofollow">https://mail.python.org/pipermail/python-list/2001-July/071567.html</a></p>
13
2009-07-27T15:02:08Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,188,862
<p>95% of the time, you should put all your imports at the top of the file. One case where you might want to do a function-local import is if you have to do it in order to avoid circular imports. Say foo.py imports bar.py, and a function in bar.py needs to import something from foo.py. If you put all your imports at the top, you could have unexpected problems importing files that rely on information that hasn't been compiled yet. In this case, having a function local import can allow your code to hold off on importing the other module until its code has been fully compiled, and you call the relevant function.</p> <p>However, it looks like your use-case is more about making it clear where foo() is coming from. In this case, I would far prefer one of two things: </p> <p>First, rather than</p> <pre><code>from prerequisite import foo </code></pre> <p>import prerequisite directly, and later on refer to it as prerequisite.foo. The added verbosity pays itself back in spades through increased code transparency.</p> <p>Alternatively, (or in conjunction with the above) if it's really such a long distance between your import and the place it's being used, it may be that your module is too big. The need for an import that nothing else uses might be an indication of a place where your code could stand to be refactored into a more manageably-sized chunk.</p>
3
2009-07-27T15:30:42Z
[ "python", "python-import" ]
Good or bad practice in Python: import in the middle of a file
1,188,640
<p>Suppose I have a relatively long module, but need an external module or method only once.</p> <p>Is it considered OK to import that method or module in the middle of the module?</p> <p>Or should <code>import</code>s only be in the first part of the module.</p> <p>Example:</p> <pre><code>import string, pythis, pythat ... ... ... ... def func(): blah blah blah from pysomething import foo foo() etc etc etc ... ... ... </code></pre> <p><strong>Please justify your answer and add links to <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Development">PEP</a>s or relevant sources</strong></p>
38
2009-07-27T14:53:25Z
1,189,199
<p>Everyone else has already mentioned the PEPs, but also take care to <strong>not</strong> have import statements in the middle of critical code. At least under Python 2.6, there are several more bytecode instructions required when a function has an import statement.</p> <pre><code>&gt;&gt;&gt; def f(): from time import time print time() &gt;&gt;&gt; dis.dis(f) 2 0 LOAD_CONST 1 (-1) 3 LOAD_CONST 2 (('time',)) 6 IMPORT_NAME 0 (time) 9 IMPORT_FROM 0 (time) 12 STORE_FAST 0 (time) 15 POP_TOP 3 16 LOAD_FAST 0 (time) 19 CALL_FUNCTION 0 22 PRINT_ITEM 23 PRINT_NEWLINE 24 LOAD_CONST 0 (None) 27 RETURN_VALUE &gt;&gt;&gt; def g(): print time() &gt;&gt;&gt; dis.dis(g) 2 0 LOAD_GLOBAL 0 (time) 3 CALL_FUNCTION 0 6 PRINT_ITEM 7 PRINT_NEWLINE 8 LOAD_CONST 0 (None) 11 RETURN_VALUE </code></pre>
12
2009-07-27T16:27:29Z
[ "python", "python-import" ]
Python POST ordered params
1,188,737
<p>I have a web service that accepts passed in params using http POST but in a specific order, eg (name,password,data). I have tried to use httplib but all the Python http POST libraries seem to take a dictionary, which is an unordered data structure. Any thoughts on how to http POST params in order for Python?</p> <p>Thanks!</p>
2
2009-07-27T15:11:19Z
1,188,759
<p>Why would you need a specific order in the POST parameters in the first place? As far as I know there are no requirements that POST parameter order is preserved by web servers.</p> <p>Every language I have used, has used a dictionary type object to hold these parameters as they are inherently key/value pairs.</p>
2
2009-07-27T15:14:21Z
[ "python", "http" ]
Make SetupTools/easy_install aware of installed Debian Packages?
1,188,812
<p>I'm installing an egg with <code>easy_install</code> which requires <code>ruledispatch</code>. It isn't available in PyPI, and when I use PEAK's version it <a href="http://en.wikipedia.org/wiki/FTBFS" rel="nofollow">FTBFS</a>. There is, however, a <code>python-dispatch</code> package which provides the same functionality as ruledispatch. How can I get <code>easy_install</code> to stop trying to install ruledispatch, and to allow it to recognize that ruledispatch is already installed as python-ruledispatch?</p> <p>Running Debian etch with Python 2.4</p>
1
2009-07-27T15:21:20Z
1,188,915
<p>The path least fiddly is likely:</p> <ol> <li>easy_install --no-deps</li> <li>Look at the egginfo of what you just installed</li> <li>Install all dependencies except ruledispatch by hand</li> <li>Optionally, prod the people responsible to list their stuff on pypi / not have dependencies that the package installer can't possibly satisfy / use dependency_links / use a custom package index / something.</li> </ol> <p>If the python-ruledispatch from the .deb is the same as the egg depends on or compatible, this should work.</p>
3
2009-07-27T15:40:16Z
[ "python", "debian", "setuptools", "easy-install", "etch" ]
Django: Easily add extra manager for child class, still use default manager from AbstractBase
1,188,899
<p>this question is about the last example on <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance" rel="nofollow">Custom managers and model inheritance</a>.</p> <p>I want to be able to do something similar to the following:</p> <pre><code>class ExtraManagerModel(models.Model): # OtherManager class supplied by argument shall be set as manager here class Meta: abstract = True class ChildC(AbstractBase, ExtraManagerModel(OtherManager)): # That doesn't work, something like that ... # Default manager is CustomManager, but OtherManager is # also available via the "extra_manager" attribute. </code></pre> <p>The whole purpose of this is that I don't want to write an <code>ExtraManagerModel</code> class for every overwritten manager in order to keep the default manager of the parent class (<code>AbstractBase</code>).</p> <p>Any ideas?</p>
1
2009-07-27T15:37:16Z
1,189,025
<p>I am absolutely not sure that I understand your question. Your code snippet seems to be contradicting the comment underneath it.</p> <p>Your code snippet looks like you want to be able to have different ExtraManagerModel classes. If that is the case, you can use an abstract class that is implemented by those ExtraManagerModels, and you inherit the abstract parent of those classes for the childC class.</p> <p>Hope this helps.</p>
0
2009-07-27T16:02:11Z
[ "python", "django", "django-models" ]
How can I get nose to find class attributes defined on a base test class?
1,188,922
<p>I'm getting some integration tests running against the database, and I'd like to have a structure that looks something like this:</p> <pre><code>class OracleMixin(object): oracle = True # ... set up the oracle connection class SqlServerMixin(object): sql_server = True # ... set up the sql server connection class SomeTests(object): integration = True # ... define test methods here class test_OracleSomeTests(SomeTests, OracleMixin): pass class test_SqlServerSomeTests(SomeTests, SqlServerMixin): pass </code></pre> <p>This way, I can run SQL Server tests and Oracle tests separately like this:</p> <pre><code>nosetests -a oracle nosetests -a sql_server </code></pre> <p>Or all integration tests like this:</p> <pre><code>nosetests -a integration </code></pre> <p>However, it appears that nose will only look for attributes on the subclass, not on the base class. Thus I have to define the test classes like this or the tests won't run:</p> <pre><code>class test_OracleSomeTests(SomeTests, OracleMixin): oracle = True integration = True class test_SqlServerSomeTests(SomeTests, SqlServerMixin): sql_server = True integration = True </code></pre> <p>This is a bit tedious to maintain. Any ideas how to get around this? If I was just dealing with one base class, I'd just use a metaclass and define the attributes on each class. But I get an uneasy feeling about having a metaclass for the test class, a metaclass for Oracle, and a metaclass for SQL Server.</p>
4
2009-07-27T15:41:55Z
1,189,540
<p>I do not think you can without making your own plugin. The the code in the attrib plugin only looks at the classes <code>__dict__</code>. Here is the <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/plugins/attrib.html" rel="nofollow">code</a> </p> <pre><code>def wantClass(self, cls): """Accept the class if the class or any method is wanted. """ cls_attr = cls.__dict__ if self.validateAttrib(cls_attr) is not False: return None ... </code></pre> <p>You could hack the plugin to do something like (not tested).</p> <pre><code>def wantClass(self, cls): """Accept the class if the class or any method is wanted. """ for class_ in cls.__mro__: cls_attr = class_.__dict__ if self.validateAttrib(cls_attr) is not False: return None cls_attr = cls.__dict__ ... </code></pre> <p>However, I am not sure that this is better or worse that the metaclass option.</p>
4
2009-07-27T17:30:59Z
[ "python", "integration-testing", "multiple-inheritance", "nose", "mixins" ]
How can I get nose to find class attributes defined on a base test class?
1,188,922
<p>I'm getting some integration tests running against the database, and I'd like to have a structure that looks something like this:</p> <pre><code>class OracleMixin(object): oracle = True # ... set up the oracle connection class SqlServerMixin(object): sql_server = True # ... set up the sql server connection class SomeTests(object): integration = True # ... define test methods here class test_OracleSomeTests(SomeTests, OracleMixin): pass class test_SqlServerSomeTests(SomeTests, SqlServerMixin): pass </code></pre> <p>This way, I can run SQL Server tests and Oracle tests separately like this:</p> <pre><code>nosetests -a oracle nosetests -a sql_server </code></pre> <p>Or all integration tests like this:</p> <pre><code>nosetests -a integration </code></pre> <p>However, it appears that nose will only look for attributes on the subclass, not on the base class. Thus I have to define the test classes like this or the tests won't run:</p> <pre><code>class test_OracleSomeTests(SomeTests, OracleMixin): oracle = True integration = True class test_SqlServerSomeTests(SomeTests, SqlServerMixin): sql_server = True integration = True </code></pre> <p>This is a bit tedious to maintain. Any ideas how to get around this? If I was just dealing with one base class, I'd just use a metaclass and define the attributes on each class. But I get an uneasy feeling about having a metaclass for the test class, a metaclass for Oracle, and a metaclass for SQL Server.</p>
4
2009-07-27T15:41:55Z
1,190,946
<p>If you want to find an attribute defined on a parent class, and you have an attribute of the same name in the subclass you will need to add the name of the parent class to access the scope you want</p> <p><em>I believe this is what you want:</em></p> <pre><code>class Parent: prop = 'a property' def self_prop(self): print self.prop # will always print 'a property' def parent_prop(self): print Parent.prop class Child(Parent): prop = 'child property' def access_eclipsed(self): print Parent.prop class Other(Child): pass &gt;&gt;&gt; Parent().self_prop() "a property" &gt;&gt;&gt; Parent().parent_prop() "a property" &gt;&gt;&gt; Child().self_prop() "child property" &gt;&gt;&gt; Child().parent_prop() "a property" &gt;&gt;&gt; Child().access_eclipsed() "a property" &gt;&gt;&gt; Other().self_prop() "child property" &gt;&gt;&gt; Other().parent_prop() "a property" &gt;&gt;&gt; Other().access_eclipsed() "a property" </code></pre> <p>and in your case it looks like you have two different classes which define different variables so you can just have a try: catch: at the top of your test functions or maybe in the initializer</p> <p><strong>and say</strong></p> <pre><code>try: isSQLServer = self.sql_server except AttributeError: isSQLServer = False </code></pre> <p>(though really they should be defining the same variables so that the test class doesn't have to know anything about the subclasses)</p>
0
2009-07-27T22:11:54Z
[ "python", "integration-testing", "multiple-inheritance", "nose", "mixins" ]
Why the trailing slash in the web service is so important?
1,188,927
<p>I was testing a web service in PHP and Python. The address of the web service was, let's say, <code>http://my.domain.com/my/webservice</code>. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error.</p> <p>Below is the code I used to communicate with the web service (Python):</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice', namespace) server.myFunction() </code></pre> <p>The respond I got from the server:</p> <pre><code>HTTPError: &lt;HTTPError 301 Moved Permanently&gt; </code></pre> <p>I figure out that if I add a trailing slash to the web service location it works!</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice/', namespace) server.myFunction() </code></pre> <p>Why the lack of the trailing slash causes the error?</p>
7
2009-07-27T15:43:16Z
1,188,941
<p>Because the actual server URL is: <a href="http://my.domain.com/my/webservice/" rel="nofollow">http://my.domain.com/my/webservice/</a></p> <p>The PHP library must be following redirects by default.</p>
3
2009-07-27T15:45:14Z
[ "php", "python", "wsdl", "soappy" ]
Why the trailing slash in the web service is so important?
1,188,927
<p>I was testing a web service in PHP and Python. The address of the web service was, let's say, <code>http://my.domain.com/my/webservice</code>. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error.</p> <p>Below is the code I used to communicate with the web service (Python):</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice', namespace) server.myFunction() </code></pre> <p>The respond I got from the server:</p> <pre><code>HTTPError: &lt;HTTPError 301 Moved Permanently&gt; </code></pre> <p>I figure out that if I add a trailing slash to the web service location it works!</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice/', namespace) server.myFunction() </code></pre> <p>Why the lack of the trailing slash causes the error?</p>
7
2009-07-27T15:43:16Z
1,188,943
<p>They're different URLs. <code>http://my.domain.com/my/webservice</code> implies a file <code>webservice</code> in the <code>my</code> folder. <code>http://my.domain.com/my/webservice/</code> implies the default document inside the my/webservice folder.</p> <p>Many webservers will automatically correct such URLs, but it is not required for them to do so.</p>
19
2009-07-27T15:46:21Z
[ "php", "python", "wsdl", "soappy" ]
Why the trailing slash in the web service is so important?
1,188,927
<p>I was testing a web service in PHP and Python. The address of the web service was, let's say, <code>http://my.domain.com/my/webservice</code>. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error.</p> <p>Below is the code I used to communicate with the web service (Python):</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice', namespace) server.myFunction() </code></pre> <p>The respond I got from the server:</p> <pre><code>HTTPError: &lt;HTTPError 301 Moved Permanently&gt; </code></pre> <p>I figure out that if I add a trailing slash to the web service location it works!</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice/', namespace) server.myFunction() </code></pre> <p>Why the lack of the trailing slash causes the error?</p>
7
2009-07-27T15:43:16Z
1,188,967
<p>[Disclaimer: This is a copy of my answer <a href="http://stackoverflow.com/questions/1160329/question-about-simplehttpserver-py/1160445#1160445">from here</a>. I know some people don't like this kind of copying, but this explains why the slash is important.]</p> <p>Imagine you serve a page</p> <pre><code>http://mydomain.com/bla </code></pre> <p>that contains</p> <pre><code>&lt;a href="more.html"&gt;Read more...&lt;/a&gt; </code></pre> <p>On click, the user's browser would retrieve <code>http://mydomain.com/more.html</code>. Had you instead served</p> <pre><code>http://mydomain.com/bla/ </code></pre> <p>(with the same content), the browser would retrieve <code>http://mydomain.com/bla/more.html</code>. To avoid this ambiguity, the redirection appends a slash if the URL points to a directory.</p>
2
2009-07-27T15:50:33Z
[ "php", "python", "wsdl", "soappy" ]
Why the trailing slash in the web service is so important?
1,188,927
<p>I was testing a web service in PHP and Python. The address of the web service was, let's say, <code>http://my.domain.com/my/webservice</code>. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error.</p> <p>Below is the code I used to communicate with the web service (Python):</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice', namespace) server.myFunction() </code></pre> <p>The respond I got from the server:</p> <pre><code>HTTPError: &lt;HTTPError 301 Moved Permanently&gt; </code></pre> <p>I figure out that if I add a trailing slash to the web service location it works!</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice/', namespace) server.myFunction() </code></pre> <p>Why the lack of the trailing slash causes the error?</p>
7
2009-07-27T15:43:16Z
1,188,995
<p>The error is a 301 redirect meaning the you are being redirected to the URL with the slash on the end by the web server. </p> <p>It seems that PHP will auto follow this redirect and thus not throw the error, whereas Python won't. You will need to do the following:</p> <ol> <li>Try to Connect to the initial URL</li> <li>Catch any 301 redirect and possibly 302 redirects as well</li> <li>If there was a redirect then try to connect to that URL instead.</li> </ol> <p>The new URL should be available in the response headers. </p> <p>HTH.</p>
3
2009-07-27T15:56:07Z
[ "php", "python", "wsdl", "soappy" ]
Why the trailing slash in the web service is so important?
1,188,927
<p>I was testing a web service in PHP and Python. The address of the web service was, let's say, <code>http://my.domain.com/my/webservice</code>. When I tested the web service in PHP using that URL everything worked fine. But, when I used the same location but in Python using SOAPpy I got an error.</p> <p>Below is the code I used to communicate with the web service (Python):</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice', namespace) server.myFunction() </code></pre> <p>The respond I got from the server:</p> <pre><code>HTTPError: &lt;HTTPError 301 Moved Permanently&gt; </code></pre> <p>I figure out that if I add a trailing slash to the web service location it works!</p> <pre><code>from SOAPpy import WSDL server = SOAPProxy('http://my.domain.com/my/webservice/', namespace) server.myFunction() </code></pre> <p>Why the lack of the trailing slash causes the error?</p>
7
2009-07-27T15:43:16Z
1,189,018
<p>What a SOAP-URL looks like is up to the server, if a slash is necessary depends on the server and the SOAP implementation.</p> <p>In your case, I assume that the target server is an apache server and the SOAP URL is actually a directory that contains your SOAP handling script. When you access <a href="http://my.domain.com/my/webservice" rel="nofollow">http://my.domain.com/my/webservice</a> on the server, apache decides that the directory is properly addressed as <a href="http://my.domain.com/my/webservice/" rel="nofollow">http://my.domain.com/my/webservice/</a> and sends a 301 redirect.</p> <p>SOAP uses a http POST, its up to the client to decide if the redirect should be followed or not, I assume that it just doesn't expect one.</p> <p>Other implementations of SOAP, e.g. Apache Axis in Java have URLs that look like Servlets, e.g. <a href="http://domain.com/soap/webservice" rel="nofollow">http://domain.com/soap/webservice</a> without slash, in this case the URL without slash is correct, there is no directory that exists anyway.</p> <p>Axis fails on redirects as well, I think.</p>
0
2009-07-27T16:01:16Z
[ "php", "python", "wsdl", "soappy" ]
Reason for unintuitive UnboundLocalError behaviour
1,188,944
<p>Note: There is a very similar question <a href="http://stackoverflow.com/questions/404534/python-globals-locals-and-unboundlocalerror">here</a>. Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case."</p> <p>I just stumbled over this:</p> <pre><code>a = 5 def x() print a a = 6 x() </code></pre> <p>throws an <code>UnboundLocalException</code>. Now, I do know why that happens (later in this scope, <code>a</code> is bound, so <code>a</code> is considered local throughout the scope).</p> <p>In this case:</p> <pre><code>a = 5 def x() print b b = 6 x() </code></pre> <p>this makes very much sense. But the first case has an intuitive logic to it, which is to mean this:</p> <pre><code>a = 5 def x() print globals()["a"] a = 6 # local assignment x() </code></pre> <p>I guess there's a reason why the "intutive" version is not allowed, but what is it? Although this might be a case of "Explicit is better than implicit," fiddling around with the <code>globals()</code> always feels a bit unclean to me.</p> <p>To put this into perspective, the actual case where this happened to me was someone else's script I had to change for one moment. In my (short-lived) change, I did some file renaming while the script was running, so I inserted</p> <pre><code>import os os.rename("foo", "bar") </code></pre> <p>into the script. This inserting happend inside a function. The module already imported <code>os</code> at the top level (I didn't check that), and some <code>os.somefunction</code> calls where made inside the function, but before my insert. These calls obviously triggered an <code>UnboundLocalException</code>.</p> <p>So, can someone explain the reasoning behind this implementation to me? Is it to prevent the user from making mistakes? Would the "intuitive" way just make things more complicated for the bytecode compiler? Or is there a possible ambiguity that I didn't think of?</p>
4
2009-07-27T15:46:35Z
1,189,075
<p>Having the same, identical name refer to completely different variables within the same flow of linear code is such a mind-boggling complexity that it staggers the mind. Consider:</p> <pre><code>def aaaargh(alist): for x in alist: print a a = 23 </code></pre> <p>what is THIS code supposed to do in your desired variant on Python? Have the <code>a</code> in the very same <code>print</code> statement refer to completely different and unrelated variables on the first leg of the loop vs the second one (assuming there IS a second one)? Have it work differently even for a one-item alist than the non-looping code would? Seriously, this way madness lies -- not even thinking of the scary implementation issues, just trying to document and teach this is something that would probably make me switch languages.</p> <p>And what would be the underpinning motivation for the language, its implementers, its teachers, its learners, its practitioners, to shoulder all of this conceptual burden -- <em>to support and encourage the semi-hidden, non-explicit use of GLOBAL VARIABLES</em>?! That hardly seems a worthwhile goal, does it now?!</p>
5
2009-07-27T16:08:56Z
[ "python" ]
Reason for unintuitive UnboundLocalError behaviour
1,188,944
<p>Note: There is a very similar question <a href="http://stackoverflow.com/questions/404534/python-globals-locals-and-unboundlocalerror">here</a>. Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case."</p> <p>I just stumbled over this:</p> <pre><code>a = 5 def x() print a a = 6 x() </code></pre> <p>throws an <code>UnboundLocalException</code>. Now, I do know why that happens (later in this scope, <code>a</code> is bound, so <code>a</code> is considered local throughout the scope).</p> <p>In this case:</p> <pre><code>a = 5 def x() print b b = 6 x() </code></pre> <p>this makes very much sense. But the first case has an intuitive logic to it, which is to mean this:</p> <pre><code>a = 5 def x() print globals()["a"] a = 6 # local assignment x() </code></pre> <p>I guess there's a reason why the "intutive" version is not allowed, but what is it? Although this might be a case of "Explicit is better than implicit," fiddling around with the <code>globals()</code> always feels a bit unclean to me.</p> <p>To put this into perspective, the actual case where this happened to me was someone else's script I had to change for one moment. In my (short-lived) change, I did some file renaming while the script was running, so I inserted</p> <pre><code>import os os.rename("foo", "bar") </code></pre> <p>into the script. This inserting happend inside a function. The module already imported <code>os</code> at the top level (I didn't check that), and some <code>os.somefunction</code> calls where made inside the function, but before my insert. These calls obviously triggered an <code>UnboundLocalException</code>.</p> <p>So, can someone explain the reasoning behind this implementation to me? Is it to prevent the user from making mistakes? Would the "intuitive" way just make things more complicated for the bytecode compiler? Or is there a possible ambiguity that I didn't think of?</p>
4
2009-07-27T15:46:35Z
1,189,081
<p>I believe there is a possible ambiguity.</p> <pre><code>a = 5 def x(): print a a = 6 # could be local or trying to update the global variable x() </code></pre> <p>It could be as you assumed:</p> <pre><code>a = 5 def x(): print globals()["a"] a = 6 # local assignment x() </code></pre> <p>Or it could be they want to update the global variable to 6:</p> <pre><code>a = 5 def x(): global a print a a = 6 x() </code></pre>
1
2009-07-27T16:09:36Z
[ "python" ]
Reason for unintuitive UnboundLocalError behaviour
1,188,944
<p>Note: There is a very similar question <a href="http://stackoverflow.com/questions/404534/python-globals-locals-and-unboundlocalerror">here</a>. Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case."</p> <p>I just stumbled over this:</p> <pre><code>a = 5 def x() print a a = 6 x() </code></pre> <p>throws an <code>UnboundLocalException</code>. Now, I do know why that happens (later in this scope, <code>a</code> is bound, so <code>a</code> is considered local throughout the scope).</p> <p>In this case:</p> <pre><code>a = 5 def x() print b b = 6 x() </code></pre> <p>this makes very much sense. But the first case has an intuitive logic to it, which is to mean this:</p> <pre><code>a = 5 def x() print globals()["a"] a = 6 # local assignment x() </code></pre> <p>I guess there's a reason why the "intutive" version is not allowed, but what is it? Although this might be a case of "Explicit is better than implicit," fiddling around with the <code>globals()</code> always feels a bit unclean to me.</p> <p>To put this into perspective, the actual case where this happened to me was someone else's script I had to change for one moment. In my (short-lived) change, I did some file renaming while the script was running, so I inserted</p> <pre><code>import os os.rename("foo", "bar") </code></pre> <p>into the script. This inserting happend inside a function. The module already imported <code>os</code> at the top level (I didn't check that), and some <code>os.somefunction</code> calls where made inside the function, but before my insert. These calls obviously triggered an <code>UnboundLocalException</code>.</p> <p>So, can someone explain the reasoning behind this implementation to me? Is it to prevent the user from making mistakes? Would the "intuitive" way just make things more complicated for the bytecode compiler? Or is there a possible ambiguity that I didn't think of?</p>
4
2009-07-27T15:46:35Z
1,189,177
<p>This is a basic side effect of scoping. The python developers decided that global variables shouldn't be available in the scope you are trying to use it in. Take this for example:</p> <pre><code>a = 5 def x(): a = 6 print a x() print a </code></pre> <p>This outputs <code>6 5</code>.</p> <p>It is <a href="http://stackoverflow.com/questions/484635/are-global-variables-bad/485020#485020">generally considered bad practice</a> to have global variables anyway, so the python developers restricted this. You have to explicitly make the global variable accessible in order to access it. This is actually to prevent ambiguity. Consider this:</p> <pre><code>a = 5 def x(): a = 6 print a y() def y(): global a a = a + 1 print a x() print a </code></pre> <p>If <code>x()</code> considered <code>a</code> to be local, and did the assignment, this would output <code>6 6 7</code>. Whoever wrote <code>x()</code> may not have considered that <code>y()</code> would use a global variable named <code>a</code>. Thus causing <code>y()</code> to act abnormally. Luckily the python scopping makes it so that the developer of <code>x()</code> doesn't have to worry about how the developer of <code>y()</code> implemented <code>y()</code>, only that it does what it is supposed to. As a result, this outputs <code>6 6 6</code> (figures), like it is supposed to.</p> <p>As a result, the <code>UnboundLocalException</code> is perfectly intuitive.</p>
0
2009-07-27T16:23:53Z
[ "python" ]
What are the Python thread + Unix signals semantics?
1,189,072
<p>What are the rules surrounding Python threads and how Unix signals are handled?</p> <p>Is <code>KeyboardInterrupt</code>, which is triggered by <code>SIGINT</code> but handled internally by the Python runtime, handled differently?</p>
8
2009-07-27T16:08:34Z
1,189,100
<p>From the <a href="http://docs.python.org/library/signal.html" rel="nofollow"><code>signal</code></a> documentation:</p> <blockquote> <p>Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform <code>signal()</code> operations in the main thread of execution. Any thread can perform an <code>alarm()</code>, <code>getsignal()</code>, <code>pause()</code>, <code>setitimer()</code> or <code>getitimer()</code>; only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication. Use locks instead.</p> </blockquote>
4
2009-07-27T16:11:52Z
[ "python", "unix", "multithreading", "posix", "signals" ]
What are the Python thread + Unix signals semantics?
1,189,072
<p>What are the rules surrounding Python threads and how Unix signals are handled?</p> <p>Is <code>KeyboardInterrupt</code>, which is triggered by <code>SIGINT</code> but handled internally by the Python runtime, handled differently?</p>
8
2009-07-27T16:08:34Z
1,189,162
<p>First, when setting up signal handlers using the <a href="http://docs.python.org/library/signal.html"><code>signal</code></a> module, you must create them in the main thread. You will receive an exception if you try to create them in a separate thread.</p> <p>Signal handlers registered via the <code>signal.signal()</code> function will always be called in the main thread. On architectures which support sending signals to threads, at the C level I believe the Python runtime ignores all signals on threads and has a signal handler on the main thread, which it uses to dispatch to your Python-code signal handler.</p> <p>The documentation for the <code>thread</code> module states that the <a href="http://docs.python.org/library/exceptions.html#exceptions.KeyboardInterrupt"><code>KeyboardInterrupt</code></a> exception (which is ordinarily triggered by <code>SIGINT</code>) can be <a href="http://docs.python.org/library/thread.html">delivered to an arbitrary thread</a> unless you have the <code>signal</code> module available to you, which all Unix systems should have. In that case, it's delivered to the main thread. If you're on a system without <code>signal</code>, you'll have to catch <code>KeyboardInterrupt</code> in your thread and call <a href="http://docs.python.org/library/thread.html#thread.interrupt%5Fmain"><code>thread.interrupt_main()</code></a> to re-raise it in the main thread.</p> <p>More information can be found in the Python docs for the <a href="http://docs.python.org/library/thread.html"><code>thread</code></a> and <a href="http://docs.python.org/library/signal.html"><code>signal</code></a> modules.</p>
9
2009-07-27T16:21:02Z
[ "python", "unix", "multithreading", "posix", "signals" ]
Unicode to UTF8 for CSV Files - Python via xlrd
1,189,111
<p>I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8.</p> <p>I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or other outputs that don't require a specific encoding.</p> <p>The worksheet is encoded as UTF-16-LE, according to <code>book.encoding</code></p> <p>The simplified version of what I'm doing is:</p> <pre><code>from xlrd import * import csv b = open_workbook('file.xls') s = b.sheet_by_name('Export') bc = open('file.csv','w') bcw = csv.writer(bc,csv.excel,b.encoding) for row in range(s.nrows): this_row = [] for col in range(s.ncols): this_row.append(s.cell_value(row,col)) bcw.writerow(this_row) </code></pre> <p>This produces the following error, about 740 lines in:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 5: ordinal not in range(128) </code></pre> <p>The value is seems to be getting hung up on is "516-777316" -- the text in the original Excel sheet is "516-7773167" (with a 7 on the end)</p> <p>I'll be the first to admit that I have only a vague sense of how character encoding works, so most of what I've tried so far are various fumbling permutations of <code>.encode</code> and <code>.decode</code> on the <code>s.cell_value(row,col)</code></p> <p>If someone could suggest a solution I would appreciate it -- even better if you could provide an explanation of what's not working and why, so that I can more easily debug these problems myself in the future.</p> <p>Thanks in advance!</p> <p><strong>EDIT:</strong></p> <p>Thanks for the comments so far.</p> <p>When I user <code>this_row.append(s.cell(row,col))</code> (e.g. s.cell instead of s.cell_value) the entire document writes without errors. </p> <p>The output isn't particularly desirable (<code>text:u'516-7773167'</code>), but it avoids the error even though the offending characters are still in the output. </p> <p>This makes me think that the challenge might be in xlrd after all. </p> <p>Thoughts?</p>
18
2009-07-27T16:13:48Z
1,189,195
<p>There appear to be two possibilities. One is that you have not perhaps opened the output file correctly:</p> <p>"If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference." ( <a href="http://docs.python.org/library/csv.html#module-csv" rel="nofollow">http://docs.python.org/library/csv.html#module-csv</a> )</p> <p>If that is not the problem, then another option for you is to use codecs.EncodedFile(file, input[, output[, errors]]) as a wrapper to output your .csv:</p> <p><a href="http://docs.python.org/library/codecs.html#module-codecs" rel="nofollow">http://docs.python.org/library/codecs.html#module-codecs</a></p> <p>This will allow you to have the file object filter from incoming UTF16 to UTF8. While both of them are technically "unicode", the way they encode is very different. </p> <p>Something like this:</p> <pre><code>rbc = open('file.csv','w') bc = codecs.EncodedFile(rbc, "UTF16", "UTF8") bcw = csv.writer(bc,csv.excel) </code></pre> <p>may resolve the problem for you, assuming I understood the problem right, and assuming that the error is thrown when writing to the file.</p>
0
2009-07-27T16:26:45Z
[ "python", "unicode", "encoding", "csv", "xlrd" ]
Unicode to UTF8 for CSV Files - Python via xlrd
1,189,111
<p>I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8.</p> <p>I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or other outputs that don't require a specific encoding.</p> <p>The worksheet is encoded as UTF-16-LE, according to <code>book.encoding</code></p> <p>The simplified version of what I'm doing is:</p> <pre><code>from xlrd import * import csv b = open_workbook('file.xls') s = b.sheet_by_name('Export') bc = open('file.csv','w') bcw = csv.writer(bc,csv.excel,b.encoding) for row in range(s.nrows): this_row = [] for col in range(s.ncols): this_row.append(s.cell_value(row,col)) bcw.writerow(this_row) </code></pre> <p>This produces the following error, about 740 lines in:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 5: ordinal not in range(128) </code></pre> <p>The value is seems to be getting hung up on is "516-777316" -- the text in the original Excel sheet is "516-7773167" (with a 7 on the end)</p> <p>I'll be the first to admit that I have only a vague sense of how character encoding works, so most of what I've tried so far are various fumbling permutations of <code>.encode</code> and <code>.decode</code> on the <code>s.cell_value(row,col)</code></p> <p>If someone could suggest a solution I would appreciate it -- even better if you could provide an explanation of what's not working and why, so that I can more easily debug these problems myself in the future.</p> <p>Thanks in advance!</p> <p><strong>EDIT:</strong></p> <p>Thanks for the comments so far.</p> <p>When I user <code>this_row.append(s.cell(row,col))</code> (e.g. s.cell instead of s.cell_value) the entire document writes without errors. </p> <p>The output isn't particularly desirable (<code>text:u'516-7773167'</code>), but it avoids the error even though the offending characters are still in the output. </p> <p>This makes me think that the challenge might be in xlrd after all. </p> <p>Thoughts?</p>
18
2009-07-27T16:13:48Z
1,189,198
<p>Looks like you've got 2 problems.</p> <p>There's something screwed up in that cell - '7' should be encoded as u'x37' I think, since it's within the ASCII-range.</p> <p>More importantly though, the fact that you're getting an error message specifying that the <code>ascii</code> codec can't be used suggests something's wrong with your encoding into unicode - it thinks you're trying to encode a value <code>0xed</code> that can't be represented in ASCII, but you said you're trying to represent it in unicode.</p> <p>I'm not smart enough to work out what particular line is causing the problem - if you edit your question to tell me what line's causing that error message I might be able to help a bit more (I guess it's either <code>this_row.append(s.cell_value(row,col))</code> or <code>bcw.writerow(this_row)</code>, but would appreciate you confirming).</p>
0
2009-07-27T16:27:06Z
[ "python", "unicode", "encoding", "csv", "xlrd" ]
Unicode to UTF8 for CSV Files - Python via xlrd
1,189,111
<p>I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8.</p> <p>I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or other outputs that don't require a specific encoding.</p> <p>The worksheet is encoded as UTF-16-LE, according to <code>book.encoding</code></p> <p>The simplified version of what I'm doing is:</p> <pre><code>from xlrd import * import csv b = open_workbook('file.xls') s = b.sheet_by_name('Export') bc = open('file.csv','w') bcw = csv.writer(bc,csv.excel,b.encoding) for row in range(s.nrows): this_row = [] for col in range(s.ncols): this_row.append(s.cell_value(row,col)) bcw.writerow(this_row) </code></pre> <p>This produces the following error, about 740 lines in:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 5: ordinal not in range(128) </code></pre> <p>The value is seems to be getting hung up on is "516-777316" -- the text in the original Excel sheet is "516-7773167" (with a 7 on the end)</p> <p>I'll be the first to admit that I have only a vague sense of how character encoding works, so most of what I've tried so far are various fumbling permutations of <code>.encode</code> and <code>.decode</code> on the <code>s.cell_value(row,col)</code></p> <p>If someone could suggest a solution I would appreciate it -- even better if you could provide an explanation of what's not working and why, so that I can more easily debug these problems myself in the future.</p> <p>Thanks in advance!</p> <p><strong>EDIT:</strong></p> <p>Thanks for the comments so far.</p> <p>When I user <code>this_row.append(s.cell(row,col))</code> (e.g. s.cell instead of s.cell_value) the entire document writes without errors. </p> <p>The output isn't particularly desirable (<code>text:u'516-7773167'</code>), but it avoids the error even though the offending characters are still in the output. </p> <p>This makes me think that the challenge might be in xlrd after all. </p> <p>Thoughts?</p>
18
2009-07-27T16:13:48Z
1,189,575
<p>I expect the <code>cell_value</code> return value is the unicode string that's giving you problems (please print its <code>type()</code> to confirm that), in which case you should be able to solve it by changing this one line:</p> <pre><code>this_row.append(s.cell_value(row,col)) </code></pre> <p>to:</p> <pre><code>this_row.append(s.cell_value(row,col).encode('utf8')) </code></pre> <p>If <code>cell_value</code> is returning multiple different types, then you need to encode if and only if it's returning a unicode string; so you'd split this line into a few lines:</p> <pre><code>val = s.cell_value(row, col) if isinstance(val, unicode): val = val.encode('utf8') this_row.append(val) </code></pre>
24
2009-07-27T17:37:03Z
[ "python", "unicode", "encoding", "csv", "xlrd" ]
Unicode to UTF8 for CSV Files - Python via xlrd
1,189,111
<p>I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8.</p> <p>I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or other outputs that don't require a specific encoding.</p> <p>The worksheet is encoded as UTF-16-LE, according to <code>book.encoding</code></p> <p>The simplified version of what I'm doing is:</p> <pre><code>from xlrd import * import csv b = open_workbook('file.xls') s = b.sheet_by_name('Export') bc = open('file.csv','w') bcw = csv.writer(bc,csv.excel,b.encoding) for row in range(s.nrows): this_row = [] for col in range(s.ncols): this_row.append(s.cell_value(row,col)) bcw.writerow(this_row) </code></pre> <p>This produces the following error, about 740 lines in:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 5: ordinal not in range(128) </code></pre> <p>The value is seems to be getting hung up on is "516-777316" -- the text in the original Excel sheet is "516-7773167" (with a 7 on the end)</p> <p>I'll be the first to admit that I have only a vague sense of how character encoding works, so most of what I've tried so far are various fumbling permutations of <code>.encode</code> and <code>.decode</code> on the <code>s.cell_value(row,col)</code></p> <p>If someone could suggest a solution I would appreciate it -- even better if you could provide an explanation of what's not working and why, so that I can more easily debug these problems myself in the future.</p> <p>Thanks in advance!</p> <p><strong>EDIT:</strong></p> <p>Thanks for the comments so far.</p> <p>When I user <code>this_row.append(s.cell(row,col))</code> (e.g. s.cell instead of s.cell_value) the entire document writes without errors. </p> <p>The output isn't particularly desirable (<code>text:u'516-7773167'</code>), but it avoids the error even though the offending characters are still in the output. </p> <p>This makes me think that the challenge might be in xlrd after all. </p> <p>Thoughts?</p>
18
2009-07-27T16:13:48Z
1,193,301
<p>You asked for explanations, but some of the phenomena are inexplicable without your help.</p> <p>(A) Strings in XLS files created by Excel 97 onwards are encoded in Latin1 if possible otherwise in UTF16LE. Each string carries a flag telling which was used. Earlier Excels encoded strings according to the user's "codepage". In any case, <strong>xlrd produces unicode objects</strong>. The file encoding is of interest only when the XLS file has been created by 3rd party software which either omits the codepage or lies about it. See the Unicode section up the front of the xlrd docs.</p> <p>(B) Unexplained phenomenon:</p> <p>This code:</p> <pre><code>bcw = csv.writer(bc,csv.excel,b.encoding) </code></pre> <p>causes the following error with Python 2.5, 2.6 and 3.1: <code>TypeError: expected at most 2 arguments, got 3</code> -- this is about what I'd expect given the docs on csv.writer; it's expecting a filelike object followed by either (1) nothing (2) a dialect or (3) one or more formatting parameters. You gave it a dialect, and csv.writer has no encoding argument, so splat. What version of Python are you using? Or did you not copy/paste the script that you actually ran?</p> <p>(C) Unexplained phenomena around traceback and what the actual offending data was:</p> <pre><code>"the_script.py", line 40, in &lt;module&gt; this_row.append(str(s.cell_value(row,col))) UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 5: ordinal not in range(128) </code></pre> <p>FIRSTLY, there's a str() in the offending code line that wasn't in the simplified script -- did you not copy/paste the script that you actually ran? In any case, you shouldn't use str in general -- you won't get the full precision on your floats; just let the csv module convert them.</p> <p>SECONDLY, you say """The value is seems to be getting hung up on is "516-777316" -- the text in the original Excel sheet is "516-7773167" (with a 7 on the end)""" --- it's difficult to imagine how the 7 gets lost off the end. I'd use something like this to find out exactly what the problematic data was:</p> <pre><code>try: str_value = str(s.cell_value(row, col)) except: print "row=%d col=%d cell_value=%r" % (row, col, s.cell_value(row, col)) raise </code></pre> <p>That %r saves you from typing <code>cell_value=%s ... repr(s.cell_value(row, col))</code> ... the repr() produces an unambiguous representation of your data. Learn it. Use it.</p> <p>How did you arrive at "516-777316"?</p> <p>THIRDLY, the error message is actually complaining about a unicode character u'\xed' at offset 5 (i.e. the sixth character). U+00ED is LATIN SMALL LETTER I WITH ACUTE, and there's nothing like that at all in "516-7773167"</p> <p>FOURTHLY, the error location seems to be a moving target -- you said in a comment on one of the solutions: "The error is on bcw.writerow." Huh?</p> <p>(D) Why you got that error message (with str()): <code>str(a_unicode_object)</code> attempts to convert the unicode object to a str object and in the absence of any encoding information uses ascii, but you have non-ascii data, so splat. Note that your object is to produce a csv file encoded in utf8, but your simplified script doesn't mention utf8 anywhere.</p> <p>(E) """... s.cell(row,col)) (e.g. s.cell instead of <code>s.cell_value)</code> the entire document writes without errors. The output isn't particularly desirable (text:u'516-7773167')"""</p> <p>That's happening because the csv writer is calling the <code>__str__</code> method of your Cell object, and this produces <code>&lt;type&gt;:&lt;repr(value)&gt;</code> which may be useful for debugging but as you say not so great in your csv file.</p> <p>(F) Alex Martelli's solution is great in that it got you going. However you should read the section on the Cell class in the xlrd docs: types of cell are text, number, boolean, date, error, blank and empty. If you have dates, you are going to want to format them as dates not numbers, so you can't use isinstance() (and you may not want the function call overhead anyway) ... this is what the <code>Cell.ctype</code> attribute and <code>Sheet.cell_type()</code> and <code>Sheet.row_types()</code> methods are for.</p> <p>(G) UTF8 is not Unicode. UTF16LE is not Unicode. UTF16 is not Unicode ... and the idea that individual strings would waste 2 bytes each on a UTF16 BOM is too preposterous for even MS to contemplate :-)</p> <p>(H) Further reading (apart from the xlrd docs):</p> <pre><code>http://www.joelonsoftware.com/articles/Unicode.html http://www.amk.ca/python/howto/unicode </code></pre>
8
2009-07-28T10:45:53Z
[ "python", "unicode", "encoding", "csv", "xlrd" ]
Is there a Python module to access Advantage Database Server?
1,189,146
<p>As the title suggest, I was wondering if there is a Python module that can access an Advantage Database Server (Sybase) files such as ADT and DBF.</p> <p>I have searched the web and couldn't find what I'm looking for this is why I wanted to ask it here.</p>
3
2009-07-27T16:18:59Z
1,189,539
<p><a href="http://www.fiby.at/dbfpy/" rel="nofollow">dbfpy</a> (and many other modules) let you read and write DBF files. I'm not aware of similar modules dealing with ADT files directly, but I think there are converters to make DBF files to/from ADT, if worse comes to worst.</p> <p>Another alternative for accessing ADT files would be to actually <em>run</em> sybase advantage with its <a href="http://www.sybase.com/products/databasemanagement/advantagedatabaseserver/odbc-driver" rel="nofollow">odbc</a> driver -- if that is feasible, there are several ways to connect to an ODBC service with Python.</p>
1
2009-07-27T17:30:54Z
[ "python", "database", "module", "dbf", "advantage-database-server" ]
Is there a Python module to access Advantage Database Server?
1,189,146
<p>As the title suggest, I was wondering if there is a Python module that can access an Advantage Database Server (Sybase) files such as ADT and DBF.</p> <p>I have searched the web and couldn't find what I'm looking for this is why I wanted to ask it here.</p>
3
2009-07-27T16:18:59Z
2,186,332
<p>I have used pyodbc with the Advantage ODBC driver, <a href="http://code.google.com/p/pyodbc/" rel="nofollow">http://code.google.com/p/pyodbc/</a> and pywin32 <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/</a> with the Advantage OLE DB provider successfully. My personal preference is the pyodbc driver.</p> <p>There is now a native wrapper at <a href="http://code.google.com/p/adsdb/" rel="nofollow">http://code.google.com/p/adsdb/</a>.</p>
2
2010-02-02T17:50:20Z
[ "python", "database", "module", "dbf", "advantage-database-server" ]
How do I resolve an SRV record in Python?
1,189,253
<p>Something which doesn't rely on native libraries would be better.</p>
4
2009-07-27T16:40:11Z
1,189,427
<p><a href="http://twistedmatrix.com/trac/">twisted</a> has an excellent pure-python implementation, see <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/names">twisted.names</a> sources (especially <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/names/dns.py">dns.py</a>). If you can't use all of their code, maybe you can extract and repurpose their <code>Record_SRV</code> class from that file.</p>
7
2009-07-27T17:14:00Z
[ "python", "networking", "dns", "srv" ]
How do I resolve an SRV record in Python?
1,189,253
<p>Something which doesn't rely on native libraries would be better.</p>
4
2009-07-27T16:40:11Z
1,191,670
<p>You could try the dnspython library:</p> <ul> <li><a href="http://www.dnspython.org/examples.html">http://www.dnspython.org/examples.html</a></li> <li><a href="http://www.dnspython.org/docs/1.7.1/html/dns.rdtypes.IN.SRV.SRV-class.html">http://www.dnspython.org/docs/1.7.1/html/dns.rdtypes.IN.SRV.SRV-class.html</a></li> </ul>
6
2009-07-28T02:33:54Z
[ "python", "networking", "dns", "srv" ]
How do I resolve an SRV record in Python?
1,189,253
<p>Something which doesn't rely on native libraries would be better.</p>
4
2009-07-27T16:40:11Z
15,123,686
<p>Using <a href="http://sourceforge.net/projects/pydns/" rel="nofollow">pydns</a>:</p> <pre><code>import DNS DNS.ParseResolvConf() srv_req = DNS.Request(qtype = 'srv') srv_result = srv_req.req('_ldap._tcp.example.org') for result in srv_result.answers: if result['typename'] == 'SRV': print result['data'] </code></pre>
1
2013-02-27T22:25:01Z
[ "python", "networking", "dns", "srv" ]
Does YouTube's API allow uploading and setting of thumbnails?
1,189,365
<p>I haven't found anything in their documentation or on the web that says yes or no. Using the Python library.</p>
0
2009-07-27T16:59:12Z
1,189,511
<p>Apparently thumbnails can't be <em>updated</em>, per <a href="http://code.google.com/apis/youtube/2.0/developers%5Fguide%5Fprotocol.html#Updating%5FVideo%5FEntry" rel="nofollow">the docs</a> -- <a href="http://code.google.com/apis/youtube/2.0/reference.html#youtube%5Fdata%5Fapi%5Ftag%5Fmedia:thumbnail" rel="nofollow">media:thumbnail</a> is not listed among the tags you can set on update. On <em>uploading</em> the video, yes, you can have <code>media:thumbnail</code> tags as part of your <code>media:group</code> tag which gives the video's metadata.</p>
2
2009-07-27T17:27:07Z
[ "python", "api", "youtube" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
1,189,445
<p>The ping program is installed setuid root. This allows any user to use the program, and still be able to open a raw socket.</p> <p>After it opens the raw socket, it typically drops root privs.</p> <p>You generally need a raw socket to do ICMP correctly, and raw sockets are usually restricted. So it's not really python's fault at all.</p> <p>Regarding the bit about ICMP above, apparently many implementations don't really support those combinations of flags well. So it is likely that most implmentations just use the way they "know" works on most / all architectures.</p>
10
2009-07-27T17:17:25Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
1,189,449
<p>Here's how /sbin/ping "somehow manages" (on most Unix-y systems):</p> <pre><code>$ ls -l /sbin/ping -r-sr-xr-x 1 root wheel 68448 Jan 26 10:00 /sbin/ping </code></pre> <p>See? It's owned by <code>root</code> and has that crucial <code>s</code> bit in the permission -- setuserid. So, no matter what user is running it, ping <strong>runs as root</strong>.</p> <p>If you're using a BSD Kernel with the new "non-privileged ICMP sockets" it would be interesting to see what's needed to use that functionality to ping from Python (but that won't help any user that's on a less advanced kernel, of course).</p>
9
2009-07-27T17:18:06Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
3,414,737
<p>I'm not sure if it is OK to post something in a question that seems it has already been answered a while ago.</p> <p>I have been searching for the same implementation and found a way to do ICMP via Python with non-root privileges.</p> <p><code>python-ping</code> uses the same 'need-root' way to do a ping, but came across a bug report where a user suggested changing <code>SOCK_RAW</code> to <code>SOCK_DGRAM</code> when calling <code>sock</code> :</p> <p><a href="http://hg.io/delroth/python-ping/issue/1/icmp-without-root-privilege" rel="nofollow">http://hg.io/delroth/python-ping/issue/1/icmp-without-root-privilege</a></p> <p>The dev explains this will be a "WONT-FIX" situation because it is a UDP ping rather. </p> <p>Since I really do not care if ICMP is going out via UDP, I went ahead and got the code and made the proposed changed.</p> <p>I am now able to do a ping without calling subprocess or needing root!</p> <p>Again, not sure if posting here after such a long time is OK, but thought this was a better thing!</p>
0
2010-08-05T12:40:24Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
5,362,316
<p>I was also looking for an implementation of ping without using subprocess or needing root to ping. My solution needed to be cross-platform, namely Windows and Linux.</p> <p>Changing the socket on Windows to SOCK_DGRAM results in a "protocol not supported 100043" exception. So it looks like Windows correctly checks to see if icmp is being sent out on TCP rather than UDP. However, windows does not care if it is running as "root" since that is a Linux concept. </p> <pre><code>if os.name == 'nt': #no root on windows my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) else: #changed to UDP socket...gets around ROOT priv issue my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, icmp) </code></pre>
0
2011-03-19T13:18:43Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
5,572,176
<p>Actually, on Windows 7 and Vista you do need to 'Run as Administrator' to do:</p> <pre><code>my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) </code></pre> <p>and as you note, doing it over a datagram socket causes an error.</p>
1
2011-04-06T19:51:46Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
6,281,194
<p>I am running python under windows 7 , Since i am editing and "compiling" the code under Eclipse pydev plugin, My solution was : Running the eclipse.exe as an administrator : this solved the problem,</p> <p>This solution is similar to running the cmd as an administrator.</p>
-6
2011-06-08T15:18:33Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
21,308,054
<p>The man page you're reading is about "BSD Kernel Interfaces Manual" and seems to come from "Mac OS X 10.9". I don't have a Mac OS X machine to try, but under Linux, <strong>as root or as user</strong> I get a permission denied error when I try to open such an ICMP:</p> <pre><code>$ strace -e trace=socket python Python 2.7.5+ (default, Sep 19 2013, 13:48:49) [GCC 4.8.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import socket &gt;&gt;&gt; socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_ICMP) socket(PF_INET, SOCK_DGRAM, IPPROTO_ICMP) = -1 EACCES (Permission denied) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/socket.py", line 187, in __init__ _sock = _realsocket(family, type, proto) socket.error: [Errno 13] Permission denied </code></pre> <p>Under OpenBSD I get a "Protocol not supported" error:</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_ICMP) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/socket.py", line 187, in __init__ _sock = _realsocket(family, type, proto) socket.error: [Errno 43] Protocol not supported </code></pre> <p>May be someone could try under MacOS X or other BSDs, but anyway this socket type does not look like portable, to say the least!</p>
0
2014-01-23T12:23:12Z
[ "python", "ping", "icmp" ]
python non-privileged ICMP
1,189,389
<p>While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></li> <li><a href="http://stackoverflow.com/questions/316866/ping-a-site-in-python">ping a site in python</a></li> <li><a href="http://stackoverflow.com/questions/1151771/how-can-i-perform-a-ping-or-traceroute-using-native-python">How can I perform a ping or traceroute using native python?</a></li> </ul> <p>The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, <a href="http://code.activestate.com/recipes/409689/">icmplib</a> and <a href="http://svn.pylucid.net/pylucid/CodeSnippets/ping.py">M. Cowles and J. Diemer's ping.py</a> explicitly mention the need for root privileges, as does the <a href="http://www.secdev.org/projects/scapy/">scapy</a> <a href="http://www.secdev.org/projects/scapy/doc/usage.html?highlight=Root%20privileges">manual</a>.</p> <p>So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The <a href="http://www.manpagez.com/man/4/icmp/">man page for icmp</a>, on the other hand, seems to say it's possible: </p> <pre> Non-privileged ICMP ICMP sockets can be opened with the SOCK_DGRAM socket type without requiring root privileges. The synopsis is the following: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) Datagram oriented ICMP sockets offer a subset of the functionality avail- able to raw ICMP sockets. Only IMCP request messages of the following types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.</pre> <p>So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?</p>
15
2009-07-27T17:02:54Z
27,059,188
<p>Modern Linuxes ping uses libcap and asks libcap to do the work.This checks (capget/set funcitons) and manage permissions:</p> <pre><code>linux@jacax:~/WORK$ ldd /bin/ping linux-gate.so.1 =&gt; (0xb77b6000) libcap.so.2 =&gt; /lib/i386-linux-gnu/libcap.so.2 (0xb7796000) libc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xb75e7000) /lib/ld-linux.so.2 (0xb77b7000) </code></pre> <p>Lets say you have a "myping" program:</p> <pre><code>linux@jacax:~/WORK$ getcap ./myping linux@jacax:~/WORK$ (-&gt; nothing! ) linux@jacax:~/WORK$ setcap cap_net_raw=ep ./myping unable to set CAP_SETFCAP effective capability: Operation not permitted linux@jacax:~/WORK$ sudo setcap cap_net_raw=ep ./myping </code></pre> <p>Now do: </p> <pre><code>linux@jacax:~/WORK$ getcap ./myping ./ping = cap_net_raw+ep </code></pre> <p>Now, your "myping" will work without root. That is, as long as <code>myping</code> is in fact a binary program. If it is a script, this capability has to be set on the script interpreter instead.</p>
2
2014-11-21T10:30:35Z
[ "python", "ping", "icmp" ]
Django cache.set() causing duplicate key error
1,189,541
<p>My Django site recently started throwing errors from my caching code and I can't figure out why...</p> <p>I call:</p> <pre><code>from django.core.cache import cache cache.set('blogentry', some_value) </code></pre> <p>And the error thrown by Django is:</p> <pre><code>TransactionManagementError: This code isn't under transaction management </code></pre> <p>But looking at the PostgreSQL database logs, it seems to stem from this error:</p> <pre><code>STATEMENT: INSERT INTO cache_table (cache_key, value, expires) VALUES (E'blogentry', E'pickled_version_of_some_value', E'2009-07-27 11:10:26') ERROR: duplicate key value violates unique constraint "cache_table_pkey" </code></pre> <p>For the life of me I can't figure out why Django is trying to do an INSERT instead of an UPDATE. Any thoughts?</p>
4
2009-07-27T17:31:09Z
1,190,725
<p>The code in core/cache/backend/db.py reads in part:</p> <pre><code>cursor.execute("SELECT cache_key, expires FROM %s WHERE cache_key = %%s" % self._table, [key]) try: result = cursor.fetchone() if result and (mode == 'set' or (mode == 'add' and result[1] &lt; now)): cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % self._table, [encoded, str(exp), key]) else: cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)]) </code></pre> <p>So I'd say that you are doing the INSERT INTO instead of the UPDATE because <em>result</em> evaluates to false. For some reason, cursor.fetchone() returns 0 rows when there is actually one there.</p> <p>if you can't break in a debugger here, I'd put trace statements into the source to confirm that this is actually happening.</p>
0
2009-07-27T21:25:55Z
[ "python", "django", "postgresql", "caching" ]
Django cache.set() causing duplicate key error
1,189,541
<p>My Django site recently started throwing errors from my caching code and I can't figure out why...</p> <p>I call:</p> <pre><code>from django.core.cache import cache cache.set('blogentry', some_value) </code></pre> <p>And the error thrown by Django is:</p> <pre><code>TransactionManagementError: This code isn't under transaction management </code></pre> <p>But looking at the PostgreSQL database logs, it seems to stem from this error:</p> <pre><code>STATEMENT: INSERT INTO cache_table (cache_key, value, expires) VALUES (E'blogentry', E'pickled_version_of_some_value', E'2009-07-27 11:10:26') ERROR: duplicate key value violates unique constraint "cache_table_pkey" </code></pre> <p>For the life of me I can't figure out why Django is trying to do an INSERT instead of an UPDATE. Any thoughts?</p>
4
2009-07-27T17:31:09Z
1,190,793
<p>That's a typical race. It checks if the key you inserted exists; if it doesn't, it does an insert, but someone else can insert the key between the count and the insert. Transactions don't prevent this.</p> <p>The code appears to expect this and to try to deal with it, but when I looked at the code to handle this case I could see immediately that it was broken. Reported here: <a href="http://code.djangoproject.com/ticket/11569" rel="nofollow">http://code.djangoproject.com/ticket/11569</a></p> <p>I'd strongly recommend sticking to the memcache backend.</p>
4
2009-07-27T21:38:55Z
[ "python", "django", "postgresql", "caching" ]
Django cache.set() causing duplicate key error
1,189,541
<p>My Django site recently started throwing errors from my caching code and I can't figure out why...</p> <p>I call:</p> <pre><code>from django.core.cache import cache cache.set('blogentry', some_value) </code></pre> <p>And the error thrown by Django is:</p> <pre><code>TransactionManagementError: This code isn't under transaction management </code></pre> <p>But looking at the PostgreSQL database logs, it seems to stem from this error:</p> <pre><code>STATEMENT: INSERT INTO cache_table (cache_key, value, expires) VALUES (E'blogentry', E'pickled_version_of_some_value', E'2009-07-27 11:10:26') ERROR: duplicate key value violates unique constraint "cache_table_pkey" </code></pre> <p>For the life of me I can't figure out why Django is trying to do an INSERT instead of an UPDATE. Any thoughts?</p>
4
2009-07-27T17:31:09Z
7,854,628
<p>I solved this problem by creating a custom cache backend, overriding the _base_set() function and changing the INSERT INTO statement like this. This SQL trick prevents the INSERT from happening in the case the cache_key already exists.</p> <pre><code>cursor.execute("INSERT INTO %s (cache_key, value, expires) SELECT %%s, %%s, %%s WHERE NOT EXISTS (SELECT 1 FROM %s WHERE cache_key = %%s)" % (table, table), [key, encoded, connections[db].ops.value_to_db_datetime(exp), key]) </code></pre>
0
2011-10-21T19:57:42Z
[ "python", "django", "postgresql", "caching" ]
In Python, what's the correct way to instantiate a class from a variable?
1,189,649
<p>Suppose that I have class <code>C</code>.</p> <p>I can write <code>o = C()</code> to create an instance of <code>C</code> and assign it to <code>o</code>.</p> <p>However, what if I want to assign the class itself into a variable and then instantiate it?</p> <p>For example, suppose that I have two classes, such as <code>C1</code> and <code>C2</code>, and I want to do something like:</p> <pre><code>if (something): classToUse = C1 else: classToUse = C2 o = classToUse.instantiate() </code></pre> <p>What's the syntax for the actual <code>instantiate()</code>? Is a call to <code>__new__()</code> enough?</p>
4
2009-07-27T17:58:59Z
1,189,668
<pre><code>o = C2() </code></pre> <p>This will accomplish what you want. Or, in case you meant to use classToUse, simply use:</p> <pre><code>o = classToUse() </code></pre> <p>Hope this helps.</p>
14
2009-07-27T18:01:23Z
[ "python", "instantiation" ]
In Python, what's the correct way to instantiate a class from a variable?
1,189,649
<p>Suppose that I have class <code>C</code>.</p> <p>I can write <code>o = C()</code> to create an instance of <code>C</code> and assign it to <code>o</code>.</p> <p>However, what if I want to assign the class itself into a variable and then instantiate it?</p> <p>For example, suppose that I have two classes, such as <code>C1</code> and <code>C2</code>, and I want to do something like:</p> <pre><code>if (something): classToUse = C1 else: classToUse = C2 o = classToUse.instantiate() </code></pre> <p>What's the syntax for the actual <code>instantiate()</code>? Is a call to <code>__new__()</code> enough?</p>
4
2009-07-27T17:58:59Z
1,189,673
<p>It's simple, Python don't recognize where a varible is a class or function. It's just call that value.</p> <pre><code>class A: pass B=A b=B() </code></pre>
1
2009-07-27T18:02:42Z
[ "python", "instantiation" ]
In Python, what's the correct way to instantiate a class from a variable?
1,189,649
<p>Suppose that I have class <code>C</code>.</p> <p>I can write <code>o = C()</code> to create an instance of <code>C</code> and assign it to <code>o</code>.</p> <p>However, what if I want to assign the class itself into a variable and then instantiate it?</p> <p>For example, suppose that I have two classes, such as <code>C1</code> and <code>C2</code>, and I want to do something like:</p> <pre><code>if (something): classToUse = C1 else: classToUse = C2 o = classToUse.instantiate() </code></pre> <p>What's the syntax for the actual <code>instantiate()</code>? Is a call to <code>__new__()</code> enough?</p>
4
2009-07-27T17:58:59Z
1,189,701
<p>You're almost there. Instead of calling an instantiate() method, just call the variable directly. It's assigned to the class, and classes are callable:</p> <pre><code>if (something): classToUse = C1 else: classToUse = C2 o = classToUse() </code></pre>
10
2009-07-27T18:06:31Z
[ "python", "instantiation" ]
In Python, what's the correct way to instantiate a class from a variable?
1,189,649
<p>Suppose that I have class <code>C</code>.</p> <p>I can write <code>o = C()</code> to create an instance of <code>C</code> and assign it to <code>o</code>.</p> <p>However, what if I want to assign the class itself into a variable and then instantiate it?</p> <p>For example, suppose that I have two classes, such as <code>C1</code> and <code>C2</code>, and I want to do something like:</p> <pre><code>if (something): classToUse = C1 else: classToUse = C2 o = classToUse.instantiate() </code></pre> <p>What's the syntax for the actual <code>instantiate()</code>? Is a call to <code>__new__()</code> enough?</p>
4
2009-07-27T17:58:59Z
1,191,448
<p>A class is an object just like anything else, like an instance, a function, a string... a class is an instance too. So you can store it in a variable (or anywhere else that you can store stuff), and call it with () no matter where it comes from. </p> <pre><code>def f(): print "foo" class C: pass x = f x() # prints foo x = C instance = x() # instanciates C </code></pre>
0
2009-07-28T01:11:32Z
[ "python", "instantiation" ]
Event Handling in Chaco
1,189,864
<p>When hovering over a data point in Chaco, I would like a small text box to appear, with the text I desire. Also, when I click on a data point (or close enough), I would like my program to take a certain action. I have seen relevant parts of the Chaco documentation, but implementing them has proved difficult. Any help would be appreciated.</p> <p>Thanks.</p>
0
2009-07-27T18:40:13Z
1,189,980
<p>Focusing first on the first (hover->textbox) issue, can you better explain what you've tried so far and how it's not working? E.g.,</p> <pre><code>from enthought.enable.tools import hover_tool tool = hover_tool.HoverTool(theplot, callback=showtext) </code></pre> <p>etc? There's a more complex example of hover-tool use <a href="https://svn.enthought.com/enthought/browser/Chaco/trunk/examples/toolbar%5Fplot.py?rev=22527" rel="nofollow">here</a> (shows a PlotToolbar rather than just a textbox) which you might be able to adapt.</p>
0
2009-07-27T19:01:40Z
[ "python" ]
Alternative to cvs2svn for performing cvs to svn migration
1,190,413
<p>I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is:</p> <blockquote> <p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p> </blockquote> <p>I followed all the prescribed steps in the <a href="http://cvs2svn.tigris.org/faq.html#osxsetup" rel="nofollow">cvs2svn FAQ</a> but the error still persists. Does anyone know of an alternative way to accomplish this task, or another website that offer a different solution to this seemingly common problem?</p>
3
2009-07-27T20:24:55Z
1,190,431
<p>You could always manually install other dbm libraries using e.g. MacPorts.</p>
1
2009-07-27T20:28:23Z
[ "python", "osx", "xserver", "cvs2svn", "gdbm" ]
Alternative to cvs2svn for performing cvs to svn migration
1,190,413
<p>I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is:</p> <blockquote> <p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p> </blockquote> <p>I followed all the prescribed steps in the <a href="http://cvs2svn.tigris.org/faq.html#osxsetup" rel="nofollow">cvs2svn FAQ</a> but the error still persists. Does anyone know of an alternative way to accomplish this task, or another website that offer a different solution to this seemingly common problem?</p>
3
2009-07-27T20:24:55Z
1,190,437
<p>Since CVS and Subversion repositories are really just collections of files, one way to work around this problem might be to copy your CVS repository to a machine where cvs2svn can run successfully, run it to convert to Subversion, and then copy the new repository back to your server. The added benefit of this method is that you won't run the risk of accidentally messing up your server configuration while doing this conversion step.</p>
7
2009-07-27T20:29:25Z
[ "python", "osx", "xserver", "cvs2svn", "gdbm" ]
Alternative to cvs2svn for performing cvs to svn migration
1,190,413
<p>I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is:</p> <blockquote> <p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p> </blockquote> <p>I followed all the prescribed steps in the <a href="http://cvs2svn.tigris.org/faq.html#osxsetup" rel="nofollow">cvs2svn FAQ</a> but the error still persists. Does anyone know of an alternative way to accomplish this task, or another website that offer a different solution to this seemingly common problem?</p>
3
2009-07-27T20:24:55Z
1,190,742
<p>Maybe sounds a bit crazy or overkill, but think about using 'git' (e.g. MacPorts version). It clones the complete CVS history and pushes it into a Subversion repository. The following steps should do the work (look at the command's manuals, git help ´cmd´): </p> <pre> port install git-core cvs cvsps svn (if necessary) create directory for git and init cvs git repo (let´s say ´cd ~/cvsgit´): git cvsimport -v -d CVSROOT module create new subversion repository (svnadmin) with trunk, tags, branches now import this new repository to a git repository: git svn clone -s file:///path/to/svnrepo (without trunk, tags, branches) this creates a svnrepo directory; rename and move it to e.g. ~/svngit now add the cvs git repo to svn repo: cd ~/svngit git remote add cvsrepo ~/cvsgit git fetch cvsrepo now merge the cvs master branch to the local svn master branch: git merge remotes/cvsrepo/master finally commit to (real) svn repository: git svn dcommit </pre> <p>You're done!</p>
0
2009-07-27T21:28:39Z
[ "python", "osx", "xserver", "cvs2svn", "gdbm" ]
Alternative to cvs2svn for performing cvs to svn migration
1,190,413
<p>I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is:</p> <blockquote> <p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p> </blockquote> <p>I followed all the prescribed steps in the <a href="http://cvs2svn.tigris.org/faq.html#osxsetup" rel="nofollow">cvs2svn FAQ</a> but the error still persists. Does anyone know of an alternative way to accomplish this task, or another website that offer a different solution to this seemingly common problem?</p>
3
2009-07-27T20:24:55Z
1,191,095
<p>cvs2svn itself is available in MacPorts so, instead of just the dbm libraries, you could install cvs2svn using MacPorts:</p> <pre><code>port install cvs2svn </code></pre> <p>If not already installed, it will also install the MacPorts version of python2.5 and other dependencies. There's no harm in that but it will take a little time and a little extra space. The advantage is that you should have a working, supported version without having to fight further dependency problems.</p>
3
2009-07-27T22:56:40Z
[ "python", "osx", "xserver", "cvs2svn", "gdbm" ]
Alternative to cvs2svn for performing cvs to svn migration
1,190,413
<p>I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is:</p> <blockquote> <p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p> </blockquote> <p>I followed all the prescribed steps in the <a href="http://cvs2svn.tigris.org/faq.html#osxsetup" rel="nofollow">cvs2svn FAQ</a> but the error still persists. Does anyone know of an alternative way to accomplish this task, or another website that offer a different solution to this seemingly common problem?</p>
3
2009-07-27T20:24:55Z
11,745,542
<p>If you already have subversion installed , Did you make sure that the path is set right in your system variables?</p> <p>I had that same issue on mine and I ended up having to add the variables in Python_Home and path to use </p> <p>C:\Pyton27\ </p>
1
2012-07-31T17:15:54Z
[ "python", "osx", "xserver", "cvs2svn", "gdbm" ]
Executing current Python script in Emacs on Windows
1,190,595
<p>I've just started learning Emacs, and decided to start writing Python in it. I tried using C-c C-c to execute the current buffer, but I get the message <code>Searching for program: no such file or directory, python</code>.</p> <p>I've looked on google, but I'm none the wiser as to how to sort this out (bear in mind I know next to nothing about Emacs!)</p>
3
2009-07-27T21:04:09Z
1,190,812
<p>I managed to work it out, following the instructions <a href="http://www.emacswiki.org/emacs/PythonMode" rel="nofollow">here</a>. I used python-mode.el, when before I had been using Emacs' built-in python.el, but according to <a href="http://www.emacswiki.org/emacs/PythonMode" rel="nofollow">emacswiki</a>, "The version in Emacs 22 has a bunch of problems". Hope someone else running Emacs 22 on Windows XP finds this useful one day!</p>
3
2009-07-27T21:43:22Z
[ "python", "emacs" ]
Executing current Python script in Emacs on Windows
1,190,595
<p>I've just started learning Emacs, and decided to start writing Python in it. I tried using C-c C-c to execute the current buffer, but I get the message <code>Searching for program: no such file or directory, python</code>.</p> <p>I've looked on google, but I'm none the wiser as to how to sort this out (bear in mind I know next to nothing about Emacs!)</p>
3
2009-07-27T21:04:09Z
1,191,489
<p>Try adding <code>C:\Python26</code> (or whatever Python you have installed) to the <code>PATH</code> environment variable. </p> <p>I find <a href="http://www.emacswiki.org/emacs/PythonMode" rel="nofollow">python-mode</a> and <a href="http://code.google.com/p/yasnippet/" rel="nofollow">yasnippet</a> to be useful for writing Python in emacs.</p>
2
2009-07-28T01:24:26Z
[ "python", "emacs" ]
Django FileField with upload_to determined at runtime
1,190,697
<p>I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:</p> <pre><code>class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to='.') </code></pre> <p>So what I want is instead of '.' as the upload_to, have it be the user's name.</p> <p>I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.</p> <p>Thanks for the help!</p>
110
2009-07-27T21:22:38Z
1,190,866
<p>You've probably read <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload%5Fto">the documentation</a>, so here's an easy example to make it make sense:</p> <pre><code>def content_file_name(instance, filename): return '/'.join(['content', instance.user.username, filename]) class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to=content_file_name) </code></pre> <p>As you can see, you don't even need to use the filename given - you could override that in your upload_to callable too if you liked.</p>
225
2009-07-27T21:56:18Z
[ "python", "django", "django-models" ]
Django FileField with upload_to determined at runtime
1,190,697
<p>I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:</p> <pre><code>class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to='.') </code></pre> <p>So what I want is instead of '.' as the upload_to, have it be the user's name.</p> <p>I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.</p> <p>Thanks for the help!</p>
110
2009-07-27T21:22:38Z
21,841,322
<p>This really helped. For a bit more brevity's sake, decided to use lambda in my case:</p> <pre><code>file = models.FileField( upload_to=lambda instance, filename: '/'.join(['mymodel', str(instance.pk), filename]), ) </code></pre>
8
2014-02-17T23:23:23Z
[ "python", "django", "django-models" ]
Automatically Generated Python Code from an UML diagram?
1,190,854
<p><em>The question is not the same as <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">What’s the best way to generate a UML diagram from Python source code?</a>, but the other way around.</em></p> <p><a href="http://www.topcoder.com/tc?module=Static&amp;d1=dev&amp;d2=umltool&amp;d3=description">Topcoder UML tool</a> automatically generates code in only Java or C#. Since I need to create <a href="http://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db">a very depended data structure</a> at a point, I am hesitant to turn to Java. I want to use Python. So:</p> <ol> <li><p>Is there an UML-like tool that automatically generates Python code from your diagram?</p></li> <li><p>If there is, is it possible to generate it from the Topcoder UML tool?</p></li> <li><p>Can you shortly compare the tools?</p></li> </ol>
15
2009-07-27T21:53:05Z
1,190,892
<ul> <li><a href="http://sourceforge.net/projects/eclipse-pyuml/">PyUML</a> - a Python Roundtrip Tool for Eclipse</li> <li><a href="http://sourceforge.net/projects/pyidea/">PyIdea</a>: PyNSource UML &amp; Patterns IDE for Python</li> </ul>
6
2009-07-27T22:00:14Z
[ "python", "uml" ]
Automatically Generated Python Code from an UML diagram?
1,190,854
<p><em>The question is not the same as <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">What’s the best way to generate a UML diagram from Python source code?</a>, but the other way around.</em></p> <p><a href="http://www.topcoder.com/tc?module=Static&amp;d1=dev&amp;d2=umltool&amp;d3=description">Topcoder UML tool</a> automatically generates code in only Java or C#. Since I need to create <a href="http://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db">a very depended data structure</a> at a point, I am hesitant to turn to Java. I want to use Python. So:</p> <ol> <li><p>Is there an UML-like tool that automatically generates Python code from your diagram?</p></li> <li><p>If there is, is it possible to generate it from the Topcoder UML tool?</p></li> <li><p>Can you shortly compare the tools?</p></li> </ol>
15
2009-07-27T21:53:05Z
1,190,899
<p>Some tools:</p> <ul> <li><a href="http://gaphor.devjavu.com/" rel="nofollow">Gaphor</a></li> <li><a href="http://eclipse-pyuml.sourceforge.net/" rel="nofollow">pyUML for Eclipse</a></li> <li><a href="http://www.andypatterns.com/index.php?cID=65" rel="nofollow">pyNSource</a></li> </ul>
0
2009-07-27T22:02:05Z
[ "python", "uml" ]
Automatically Generated Python Code from an UML diagram?
1,190,854
<p><em>The question is not the same as <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">What’s the best way to generate a UML diagram from Python source code?</a>, but the other way around.</em></p> <p><a href="http://www.topcoder.com/tc?module=Static&amp;d1=dev&amp;d2=umltool&amp;d3=description">Topcoder UML tool</a> automatically generates code in only Java or C#. Since I need to create <a href="http://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db">a very depended data structure</a> at a point, I am hesitant to turn to Java. I want to use Python. So:</p> <ol> <li><p>Is there an UML-like tool that automatically generates Python code from your diagram?</p></li> <li><p>If there is, is it possible to generate it from the Topcoder UML tool?</p></li> <li><p>Can you shortly compare the tools?</p></li> </ol>
15
2009-07-27T21:53:05Z
1,190,901
<p>The <a href="http://uml.sourceforge.net/" rel="nofollow">Umbrello</a> UML modeller for KDE support Python as an export language.</p>
2
2009-07-27T22:02:25Z
[ "python", "uml" ]
Automatically Generated Python Code from an UML diagram?
1,190,854
<p><em>The question is not the same as <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">What’s the best way to generate a UML diagram from Python source code?</a>, but the other way around.</em></p> <p><a href="http://www.topcoder.com/tc?module=Static&amp;d1=dev&amp;d2=umltool&amp;d3=description">Topcoder UML tool</a> automatically generates code in only Java or C#. Since I need to create <a href="http://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db">a very depended data structure</a> at a point, I am hesitant to turn to Java. I want to use Python. So:</p> <ol> <li><p>Is there an UML-like tool that automatically generates Python code from your diagram?</p></li> <li><p>If there is, is it possible to generate it from the Topcoder UML tool?</p></li> <li><p>Can you shortly compare the tools?</p></li> </ol>
15
2009-07-27T21:53:05Z
1,191,770
<p>Search with Ubuntu found:</p> <pre><code>$ apt-cache search python uml boa-constructor - RAD tool for Python and WxWindows application dia2code - a dia-UML code generator spe - Stani's Python Editor </code></pre> <p>Quick testing revealed that DIA is the only program, where you can export your UML diagram to Python. I am very suspicious about the quality of DIA because it is less intuitive to use than the Topcoder UML program. Perhaps, the other programs, suggested by other repliers, are better.</p>
0
2009-07-28T03:18:14Z
[ "python", "uml" ]
Automatically Generated Python Code from an UML diagram?
1,190,854
<p><em>The question is not the same as <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">What’s the best way to generate a UML diagram from Python source code?</a>, but the other way around.</em></p> <p><a href="http://www.topcoder.com/tc?module=Static&amp;d1=dev&amp;d2=umltool&amp;d3=description">Topcoder UML tool</a> automatically generates code in only Java or C#. Since I need to create <a href="http://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db">a very depended data structure</a> at a point, I am hesitant to turn to Java. I want to use Python. So:</p> <ol> <li><p>Is there an UML-like tool that automatically generates Python code from your diagram?</p></li> <li><p>If there is, is it possible to generate it from the Topcoder UML tool?</p></li> <li><p>Can you shortly compare the tools?</p></li> </ol>
15
2009-07-27T21:53:05Z
1,194,326
<p><a href="http://www.sparxsystems.com.au/products/ea/index.html">Enterprise Architect</a> is able to generate python code code from UML diagrams.<br /> It is also able to also perform some reverse engineering, and therefore maintain the two versions (UML and python) synchronized together.</p> <p>However, I have never used it in that way, except for some small tests just to see it in action. I personally find productivity in Python so high, that even if I am really satisfied with EA, I prefer it just to document the design.</p>
9
2009-07-28T14:05:48Z
[ "python", "uml" ]
Automatically Generated Python Code from an UML diagram?
1,190,854
<p><em>The question is not the same as <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">What’s the best way to generate a UML diagram from Python source code?</a>, but the other way around.</em></p> <p><a href="http://www.topcoder.com/tc?module=Static&amp;d1=dev&amp;d2=umltool&amp;d3=description">Topcoder UML tool</a> automatically generates code in only Java or C#. Since I need to create <a href="http://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db">a very depended data structure</a> at a point, I am hesitant to turn to Java. I want to use Python. So:</p> <ol> <li><p>Is there an UML-like tool that automatically generates Python code from your diagram?</p></li> <li><p>If there is, is it possible to generate it from the Topcoder UML tool?</p></li> <li><p>Can you shortly compare the tools?</p></li> </ol>
15
2009-07-27T21:53:05Z
12,913,301
<p>You can use DIA, and then install dia2code, it will generate from UML to code in python. I use it in PHP5 and Java.</p> <pre><code>$ sudo apt-get install dia dia2code </code></pre>
4
2012-10-16T11:04:46Z
[ "python", "uml" ]
How do you reload your Python source into the console window in Eclipse/Pydev?
1,191,018
<p>In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the console interactively and inspect data structures there.</p> <p>Is there a way to do this with Eclipse/Pydev?</p> <p>So far I've been making do with this hack in my source file:</p> <pre><code>def relo(): execfile("/Path/To/Source.py", __builtins__) </code></pre> <p>I call <code>relo()</code> in the console after I save changes to the source. But I'd much rather just tap a key. I'm using pydev 1.4.7.2843.</p> <p>This is somewhat related to <a href="http://stackoverflow.com/questions/323581/eclipse-pydev-is-it-possible-to-assign-a-shortcut-to-send-selection-to-the-pyt">this</a> question, but I want to just reload the whole source file.</p>
10
2009-07-27T22:28:35Z
1,209,767
<p>Use the revert option on the File menu.</p> <p>You can bind a key to it in Windows > Preferences > General > Keys.</p> <p>Edit:</p> <p>The reload(module) function will update packages in the interactive console. It's built in for python 2.x and in the imp module for 3.x. Python docs link: <a href="http://docs.python.org/3.1/library/imp.html?#imp.reload" rel="nofollow">http://docs.python.org/3.1/library/imp.html?#imp.reload</a></p> <p>Couldn't find a way to run it by hotkey, I'd like to know if you find a way.</p>
1
2009-07-30T22:31:52Z
[ "python", "pydev" ]
How do you reload your Python source into the console window in Eclipse/Pydev?
1,191,018
<p>In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the console interactively and inspect data structures there.</p> <p>Is there a way to do this with Eclipse/Pydev?</p> <p>So far I've been making do with this hack in my source file:</p> <pre><code>def relo(): execfile("/Path/To/Source.py", __builtins__) </code></pre> <p>I call <code>relo()</code> in the console after I save changes to the source. But I'd much rather just tap a key. I'm using pydev 1.4.7.2843.</p> <p>This is somewhat related to <a href="http://stackoverflow.com/questions/323581/eclipse-pydev-is-it-possible-to-assign-a-shortcut-to-send-selection-to-the-pyt">this</a> question, but I want to just reload the whole source file.</p>
10
2009-07-27T22:28:35Z
2,017,129
<p>You can do it with <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Enter</kbd> on the latest <a href="http://pydev.org/manual_adv_interactive_console.html" rel="nofollow">Pydev</a> for details on what <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Enter</kbd> provides as it can do a number of things related to the interactive console.</p>
7
2010-01-06T23:27:46Z
[ "python", "pydev" ]
What's the best way to optimize this MySQL query?
1,191,105
<p><strong>This is a query that totals up every players game results from a game and displays the players who match the conditions.</strong> </p> <pre><code>select *, (kills / deaths) as killdeathratio, (totgames - wins) as losses from (select gp.name as name, gp.gameid as gameid, gp.colour as colour, Avg(dp.courierkills) as courierkills, Avg(dp.raxkills) as raxkills, Avg(dp.towerkills) as towerkills, Avg(dp.assists) as assists, Avg(dp.creepdenies) as creepdenies, Avg(dp.creepkills) as creepkills, Avg(dp.neutralkills) as neutralkills, Avg(dp.deaths) as deaths, Avg(dp.kills) as kills, sc.score as totalscore, Count(* ) as totgames, Sum(case when ((dg.winner = 1 and dp.newcolour &lt; 6) or (dg.winner = 2 and dp.newcolour &gt; 6)) then 1 else 0 end) as wins from gameplayers as gp, dotagames as dg, games as ga, dotaplayers as dp, scores as sc where dg.winner &lt;&gt; 0 and dp.gameid = gp.gameid and dg.gameid = dp.gameid and dp.gameid = ga.id and gp.gameid = dg.gameid and gp.colour = dp.colour and sc.name = gp.name group by gp.name having totgames &gt;= 30 ) as h order by totalscore desc </code></pre> <p>Now I'm not too sure what's the best way to go but what would in your opinion be to optimize this query?</p> <p>I run a Q6600 @ 2.4ghz, 4gb of ram, 64-bit Linux Ubuntu 9.04 system and this query can take up to 6.7 seconds to run (I do have a huge database).</p> <p>Also I would like to paginate the results as well and executing extra conditions on top of this query is far too slow.... </p> <p>I use django as a frontend so any methods that include using python +/- django methods would be great. MySQL, Apache2 tweaks are also welcome. And of course, I'm open to changing the query to make it run faster. </p> <p>Thanks for reading my question; look forward to reading your answers!</p> <p><strong>Edit: EXPLAIN QUERY RESULTS</strong></p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY &lt;derived2&gt; ALL NULL NULL NULL NULL 783 Using filesort 2 DERIVED sc ALL name,name_2 NULL NULL NULL 2099 Using temporary; Using filesort 2 DERIVED gp ref gameid,colour,name name 17 development.sc.name 2 2 DERIVED ga eq_ref PRIMARY,id,id_2 PRIMARY 4 development.gp.gameid 1 Using index 2 DERIVED dg ref gameid,winner gameid 4 development.ga.id 1 Using where 2 DERIVED dp ref gameid_2,colour gameid_2 4 development.ga.id 10 Using where </code></pre>
1
2009-07-27T23:00:39Z
1,191,257
<p>First of all, the SQL is badly formatted. The most obvious error is the line splitting before each <code>AS</code> clause. Second obvious problem is using implicit joins instead of explicitly using <code>INNER JOIN ... ON ...</code>.</p> <p>Now to answer the actual question. </p> <p>Without knowing the data or the environment, the first thing I'd look at would be some of the MySQL server settings, such as <code>sort_buffer</code> and <code>key_buffer</code>. If you haven't changed any of these, go read up on them. The defaults are extremely conservative and can often be raised more than ten times their default, particularly on the large iron like you have. </p> <p>Having reviewed that, I'd be running pieces of the query to see speed and what <code>EXPLAIN</code> says. The effect of indexing can be profound, but MySQL has a "fingers-and-toes" problem where it just can't use more than one per table. And <code>JOIN</code>s with filtering can need two. So it has to descend to a rowscan for the other check. But having said that, dicing up the query and trying different combinations will show you where it starts stumbling.</p> <p>Now you will have an idea where a "tipping point" might be: this is where a small increase in some raw data size, like how much it needs to extract, will result in a big loss of performance as some internal structure gets too big. At this point, you will probably want to raise the temporary tables size. Beware that this kind of optimization is a bit of a black art. :-)</p> <p>However, there is another approach: denormalization. In a simple implementation, regularly scheduled scripts will run this expensive query from time-to-time and poke the data into a separate table in a structure much closer to what you want to display. There are multiple variations of this approach. It can be possible to keep this up-to-date on-the-fly, either in the application, or using table triggers. At the other extreme, you could allow your application to run the expensive query occasionally, but cache the result for a little while. This is most effective if a lot of people will call it often: even 2 seconds cache on a request that is run 15 times a second will show a visible improvement. </p> <p>You could find ways of producing the same data by running half-a-dozen queries that each return some of the data, and post-processing the data. You could also run version of your original query that returns more data (which is likely to be much faster because it does less filtering) and post-process that. I have found several times that five simpler, smaller queries can be much faster - an order of magnitude, sometimes two - than one big query that is trying to do it all.</p>
2
2009-07-27T23:53:20Z
[ "python", "mysql", "django", "performance" ]
What's the best way to optimize this MySQL query?
1,191,105
<p><strong>This is a query that totals up every players game results from a game and displays the players who match the conditions.</strong> </p> <pre><code>select *, (kills / deaths) as killdeathratio, (totgames - wins) as losses from (select gp.name as name, gp.gameid as gameid, gp.colour as colour, Avg(dp.courierkills) as courierkills, Avg(dp.raxkills) as raxkills, Avg(dp.towerkills) as towerkills, Avg(dp.assists) as assists, Avg(dp.creepdenies) as creepdenies, Avg(dp.creepkills) as creepkills, Avg(dp.neutralkills) as neutralkills, Avg(dp.deaths) as deaths, Avg(dp.kills) as kills, sc.score as totalscore, Count(* ) as totgames, Sum(case when ((dg.winner = 1 and dp.newcolour &lt; 6) or (dg.winner = 2 and dp.newcolour &gt; 6)) then 1 else 0 end) as wins from gameplayers as gp, dotagames as dg, games as ga, dotaplayers as dp, scores as sc where dg.winner &lt;&gt; 0 and dp.gameid = gp.gameid and dg.gameid = dp.gameid and dp.gameid = ga.id and gp.gameid = dg.gameid and gp.colour = dp.colour and sc.name = gp.name group by gp.name having totgames &gt;= 30 ) as h order by totalscore desc </code></pre> <p>Now I'm not too sure what's the best way to go but what would in your opinion be to optimize this query?</p> <p>I run a Q6600 @ 2.4ghz, 4gb of ram, 64-bit Linux Ubuntu 9.04 system and this query can take up to 6.7 seconds to run (I do have a huge database).</p> <p>Also I would like to paginate the results as well and executing extra conditions on top of this query is far too slow.... </p> <p>I use django as a frontend so any methods that include using python +/- django methods would be great. MySQL, Apache2 tweaks are also welcome. And of course, I'm open to changing the query to make it run faster. </p> <p>Thanks for reading my question; look forward to reading your answers!</p> <p><strong>Edit: EXPLAIN QUERY RESULTS</strong></p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY &lt;derived2&gt; ALL NULL NULL NULL NULL 783 Using filesort 2 DERIVED sc ALL name,name_2 NULL NULL NULL 2099 Using temporary; Using filesort 2 DERIVED gp ref gameid,colour,name name 17 development.sc.name 2 2 DERIVED ga eq_ref PRIMARY,id,id_2 PRIMARY 4 development.gp.gameid 1 Using index 2 DERIVED dg ref gameid,winner gameid 4 development.ga.id 1 Using where 2 DERIVED dp ref gameid_2,colour gameid_2 4 development.ga.id 10 Using where </code></pre>
1
2009-07-27T23:00:39Z
1,191,304
<p>No index will help you since you are scanning entire tables. As your database grows the query will always get slower.</p> <p>Consider accumulating the stats : after every game, insert the row for that game, and also increment counters in the player's row, Then you don't need to count() and sum() because the information is available.</p>
0
2009-07-28T00:09:24Z
[ "python", "mysql", "django", "performance" ]
What's the best way to optimize this MySQL query?
1,191,105
<p><strong>This is a query that totals up every players game results from a game and displays the players who match the conditions.</strong> </p> <pre><code>select *, (kills / deaths) as killdeathratio, (totgames - wins) as losses from (select gp.name as name, gp.gameid as gameid, gp.colour as colour, Avg(dp.courierkills) as courierkills, Avg(dp.raxkills) as raxkills, Avg(dp.towerkills) as towerkills, Avg(dp.assists) as assists, Avg(dp.creepdenies) as creepdenies, Avg(dp.creepkills) as creepkills, Avg(dp.neutralkills) as neutralkills, Avg(dp.deaths) as deaths, Avg(dp.kills) as kills, sc.score as totalscore, Count(* ) as totgames, Sum(case when ((dg.winner = 1 and dp.newcolour &lt; 6) or (dg.winner = 2 and dp.newcolour &gt; 6)) then 1 else 0 end) as wins from gameplayers as gp, dotagames as dg, games as ga, dotaplayers as dp, scores as sc where dg.winner &lt;&gt; 0 and dp.gameid = gp.gameid and dg.gameid = dp.gameid and dp.gameid = ga.id and gp.gameid = dg.gameid and gp.colour = dp.colour and sc.name = gp.name group by gp.name having totgames &gt;= 30 ) as h order by totalscore desc </code></pre> <p>Now I'm not too sure what's the best way to go but what would in your opinion be to optimize this query?</p> <p>I run a Q6600 @ 2.4ghz, 4gb of ram, 64-bit Linux Ubuntu 9.04 system and this query can take up to 6.7 seconds to run (I do have a huge database).</p> <p>Also I would like to paginate the results as well and executing extra conditions on top of this query is far too slow.... </p> <p>I use django as a frontend so any methods that include using python +/- django methods would be great. MySQL, Apache2 tweaks are also welcome. And of course, I'm open to changing the query to make it run faster. </p> <p>Thanks for reading my question; look forward to reading your answers!</p> <p><strong>Edit: EXPLAIN QUERY RESULTS</strong></p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY &lt;derived2&gt; ALL NULL NULL NULL NULL 783 Using filesort 2 DERIVED sc ALL name,name_2 NULL NULL NULL 2099 Using temporary; Using filesort 2 DERIVED gp ref gameid,colour,name name 17 development.sc.name 2 2 DERIVED ga eq_ref PRIMARY,id,id_2 PRIMARY 4 development.gp.gameid 1 Using index 2 DERIVED dg ref gameid,winner gameid 4 development.ga.id 1 Using where 2 DERIVED dp ref gameid_2,colour gameid_2 4 development.ga.id 10 Using where </code></pre>
1
2009-07-27T23:00:39Z
1,191,357
<ul> <li>select * is bad most times - select only the columns you need</li> <li>break the select into multiple simple selects, use temporary tables when needed</li> <li>the sum(case part could be done with a subselect</li> <li>mysql has a very bad performance with or-expressions. use two selects which you union together</li> </ul>
0
2009-07-28T00:34:25Z
[ "python", "mysql", "django", "performance" ]
What's the best way to optimize this MySQL query?
1,191,105
<p><strong>This is a query that totals up every players game results from a game and displays the players who match the conditions.</strong> </p> <pre><code>select *, (kills / deaths) as killdeathratio, (totgames - wins) as losses from (select gp.name as name, gp.gameid as gameid, gp.colour as colour, Avg(dp.courierkills) as courierkills, Avg(dp.raxkills) as raxkills, Avg(dp.towerkills) as towerkills, Avg(dp.assists) as assists, Avg(dp.creepdenies) as creepdenies, Avg(dp.creepkills) as creepkills, Avg(dp.neutralkills) as neutralkills, Avg(dp.deaths) as deaths, Avg(dp.kills) as kills, sc.score as totalscore, Count(* ) as totgames, Sum(case when ((dg.winner = 1 and dp.newcolour &lt; 6) or (dg.winner = 2 and dp.newcolour &gt; 6)) then 1 else 0 end) as wins from gameplayers as gp, dotagames as dg, games as ga, dotaplayers as dp, scores as sc where dg.winner &lt;&gt; 0 and dp.gameid = gp.gameid and dg.gameid = dp.gameid and dp.gameid = ga.id and gp.gameid = dg.gameid and gp.colour = dp.colour and sc.name = gp.name group by gp.name having totgames &gt;= 30 ) as h order by totalscore desc </code></pre> <p>Now I'm not too sure what's the best way to go but what would in your opinion be to optimize this query?</p> <p>I run a Q6600 @ 2.4ghz, 4gb of ram, 64-bit Linux Ubuntu 9.04 system and this query can take up to 6.7 seconds to run (I do have a huge database).</p> <p>Also I would like to paginate the results as well and executing extra conditions on top of this query is far too slow.... </p> <p>I use django as a frontend so any methods that include using python +/- django methods would be great. MySQL, Apache2 tweaks are also welcome. And of course, I'm open to changing the query to make it run faster. </p> <p>Thanks for reading my question; look forward to reading your answers!</p> <p><strong>Edit: EXPLAIN QUERY RESULTS</strong></p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY &lt;derived2&gt; ALL NULL NULL NULL NULL 783 Using filesort 2 DERIVED sc ALL name,name_2 NULL NULL NULL 2099 Using temporary; Using filesort 2 DERIVED gp ref gameid,colour,name name 17 development.sc.name 2 2 DERIVED ga eq_ref PRIMARY,id,id_2 PRIMARY 4 development.gp.gameid 1 Using index 2 DERIVED dg ref gameid,winner gameid 4 development.ga.id 1 Using where 2 DERIVED dp ref gameid_2,colour gameid_2 4 development.ga.id 10 Using where </code></pre>
1
2009-07-27T23:00:39Z
25,435,283
<p><strong>Small Improvement</strong></p> <p><code>select *, (kills / deaths) as killdeathratio, (totgames - wins) as losses from (select gp.name as name, gp.gameid as gameid, gp.colour as colour, Avg(dp.courierkills) as courierkills, Avg(dp.raxkills) as raxkills, Avg(dp.towerkills) as towerkills, Avg(dp.assists) as assists, Avg(dp.creepdenies) as creepdenies, Avg(dp.creepkills) as creepkills, Avg(dp.neutralkills) as neutralkills, Avg(dp.deaths) as deaths, Avg(dp.kills) as kills, sc.score as totalscore, Count(1 ) as totgames, Sum(case when ((dg.winner = 1 and dp.newcolour &lt; 6) or (dg.winner = 2 and dp.newcolour &gt; 6)) then 1 else 0 end) as wins from gameplayers as gp, ( select * from dotagames dg1 where dg.winner &lt;&gt; 0 ) as dg, games as ga, dotaplayers as dp, scores as sc where and dp.gameid = gp.gameid and dg.gameid = dp.gameid and dp.gameid = ga.id and gp.gameid = dg.gameid and gp.colour = dp.colour and sc.name = gp.name group by gp.name having totgames &gt;= 30 ) as h order by totalscore desc</code></p> <p><strong>Changes:</strong> 1. count (*) chnaged to count(1) 2. In the FROM, The number of rows are reduced. </p>
0
2014-08-21T20:22:11Z
[ "python", "mysql", "django", "performance" ]
Hosting Mercurial with IIS 6
1,191,136
<p>I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following <a href="http://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis">this post</a> I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.</p> <p>However, when I trying to open the <a href="http://hostname/hg/hgwebdir.cgi">http://hostname/hg/hgwebdir.cgi</a> I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:</p> <ol> <li>Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.</li> <li>Created “Hello World” in the same dir and checked that it works fine.</li> <li>Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.</li> <li>Tried to apply two different patches from <a href="http://www.nabble.com/Mercurial-f24354.html">Mercurial mailing list</a>. Since they both are old I haven't success with it.</li> <li>INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.</li> <li>Tried to add 'Content-type: text/html' to the script.</li> </ol> <p>One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!</p>
15
2009-07-27T23:10:22Z
1,226,954
<p>Finally I got that "no headers" error returned on any python script error, so I checked script with console interpreter and fixed errors in my config file. And of course I should ask this question at ServerFault instead of StackOverflow - the lack of sleep did the job :) </p>
1
2009-08-04T11:31:36Z
[ "python", "iis-6", "mercurial" ]
Hosting Mercurial with IIS 6
1,191,136
<p>I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following <a href="http://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis">this post</a> I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.</p> <p>However, when I trying to open the <a href="http://hostname/hg/hgwebdir.cgi">http://hostname/hg/hgwebdir.cgi</a> I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:</p> <ol> <li>Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.</li> <li>Created “Hello World” in the same dir and checked that it works fine.</li> <li>Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.</li> <li>Tried to apply two different patches from <a href="http://www.nabble.com/Mercurial-f24354.html">Mercurial mailing list</a>. Since they both are old I haven't success with it.</li> <li>INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.</li> <li>Tried to add 'Content-type: text/html' to the script.</li> </ol> <p>One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!</p>
15
2009-07-27T23:10:22Z
3,320,927
<p>There's a pretty good post at <a href="http://vampirebasic.blogspot.com/2009/06/running-mercurial-on-windows.html" rel="nofollow">http://vampirebasic.blogspot.com/2009/06/running-mercurial-on-windows.html</a> that'll get you started, but if you need more detail or to go further than the writer did, I've got a 4 part blog post that covers everything you need to know about getting up and running on IIS, including Active Directory integration, pull/push privileges, customization of the UI:</p> <p><a href="http://www.endswithsaurus.com/2010/05/setting-up-and-configuring-mercurial-in.html" rel="nofollow">http://www.endswithsaurus.com/2010/05/setting-up-and-configuring-mercurial-in.html</a></p> <p>It's worth a read...</p>
1
2010-07-23T17:47:29Z
[ "python", "iis-6", "mercurial" ]
Hosting Mercurial with IIS 6
1,191,136
<p>I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following <a href="http://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis">this post</a> I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.</p> <p>However, when I trying to open the <a href="http://hostname/hg/hgwebdir.cgi">http://hostname/hg/hgwebdir.cgi</a> I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:</p> <ol> <li>Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.</li> <li>Created “Hello World” in the same dir and checked that it works fine.</li> <li>Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.</li> <li>Tried to apply two different patches from <a href="http://www.nabble.com/Mercurial-f24354.html">Mercurial mailing list</a>. Since they both are old I haven't success with it.</li> <li>INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.</li> <li>Tried to add 'Content-type: text/html' to the script.</li> </ol> <p>One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!</p>
15
2009-07-27T23:10:22Z
3,472,292
<p>Some more things that I needed to fix:</p> <ul> <li>Where the various HOWTOs say to use <code>c:\whatever\Python26\python.exe -u "%s" "%s"</code> instead use <code>c:\whatever\Python26\python.exe -u -O -B "%s" "%s"</code> -O causes it to also look for .pyo files (not just .py or .pyc, which at least in my version weren't present). -B causes it to not attempt to compile .py files that it finds into .pyo files (which fails due to lacking write permissions)</li> <li>I'd installed Python 2.7. Mercurial 1.6.2's .pyo files were compiled with Python 2.6. This resulted in a magic number error. Uninstalling 2.7 and installing 2.6.5 fixed this. (If you're reading this at some point in the future, this point may no longer be relevant - check the name of the DLL in Mercurial's directory, or TortoiseHg's directory, depending on where you took library.zip from)</li> <li>hgwebdir.cgi is now just hgweb.cgi - webdir was integrated into it</li> </ul>
5
2010-08-12T21:42:33Z
[ "python", "iis-6", "mercurial" ]
Hosting Mercurial with IIS 6
1,191,136
<p>I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following <a href="http://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis">this post</a> I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.</p> <p>However, when I trying to open the <a href="http://hostname/hg/hgwebdir.cgi">http://hostname/hg/hgwebdir.cgi</a> I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:</p> <ol> <li>Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.</li> <li>Created “Hello World” in the same dir and checked that it works fine.</li> <li>Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.</li> <li>Tried to apply two different patches from <a href="http://www.nabble.com/Mercurial-f24354.html">Mercurial mailing list</a>. Since they both are old I haven't success with it.</li> <li>INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.</li> <li>Tried to add 'Content-type: text/html' to the script.</li> </ol> <p>One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!</p>
15
2009-07-27T23:10:22Z
4,803,131
<p>In my situation, this error caused by line <code>application = hgwebdir('c:\somewhere\hgweb.config')</code> in hgweb.cgi, it should be <code>application = hgweb('c:\somewhere\hgweb.config')</code>. </p> <p>Besides, uncomment line <code>import cgitb; cgitb.enable()</code> in hgweb.cgi will give you more info about the error( and other errors).</p> <p>P.S. I use Python 2.6.6 and Mercurial 1.7.3 on Windows Server 2003 with IIS 6.0.</p>
1
2011-01-26T09:47:10Z
[ "python", "iis-6", "mercurial" ]
Hosting Mercurial with IIS 6
1,191,136
<p>I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following <a href="http://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis">this post</a> I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.</p> <p>However, when I trying to open the <a href="http://hostname/hg/hgwebdir.cgi">http://hostname/hg/hgwebdir.cgi</a> I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:</p> <ol> <li>Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.</li> <li>Created “Hello World” in the same dir and checked that it works fine.</li> <li>Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.</li> <li>Tried to apply two different patches from <a href="http://www.nabble.com/Mercurial-f24354.html">Mercurial mailing list</a>. Since they both are old I haven't success with it.</li> <li>INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.</li> <li>Tried to add 'Content-type: text/html' to the script.</li> </ol> <p>One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!</p>
15
2009-07-27T23:10:22Z
5,032,628
<p>In my case, the critical step that fixed it was using: c:\whatever\Python26\python.exe -u -O -B "%s" "%s</p> <p>Before that it was not working with the error: </p> <pre><code>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. c:\hg\hgweb.cgi in () 13 import cgitb; cgitb.enable() 14 15 from mercurial import demandimport; demandimport.enable() 16 from mercurial.hgweb import hgweb, wsgicgi 17 application = hgweb(config) mercurial undefined, demandimport undefined &lt;type 'exceptions.ImportError'&gt;: No module named mercurial args = ('No module named mercurial',) </code></pre>
1
2011-02-17T17:52:12Z
[ "python", "iis-6", "mercurial" ]
Bind event to wx.Menu() instead of to the menu item in wxPython
1,191,221
<p>My problem can be easily defined with the following code:</p> <pre><code>self.Bind(wx.EVT_MENU_OPEN, self.OnAbout) </code></pre> <p>This will mean that when I click on any wx.Menu() in the MenuBar, the function 'onAbout()' is called. How do I bind this event to a specific wx.Menu() which is called wx.MenuAbout() ?</p> <p>If you are feeling extra helpful, perhaps you could provide me with a link to the documentation for event handlers. I could find documentation for the event handler function but not for the actual event handlers (such as wx.EVT_MENU).</p> <p>Similar question but I am not looking to bind a range of wx.Menu()'s to the event: <a href="http://stackoverflow.com/questions/300032/is-it-possible-to-bind-an-event-against-a-menu-instead-of-a-menu-item-in-wxpython">http://stackoverflow.com/questions/300032/is-it-possible-to-bind-an-event-against-a-menu-instead-of-a-menu-item-in-wxpython</a></p> <p>Edit: Ideally, this is what I'd like to be able to do:</p> <pre><code>menuAbout = wx.Menu() self.Bind(wx.EVT_MENU, self.OnAbout, id=menuAbout.GetId()) </code></pre> <p>The result would be that any other items in the .menuBar() (such as: File, Edit, Tools) work as normal menu's, but 'About' works like a clickable link.</p> <p>Using the wx.EVT_MENU_OPEN means that the File menu can be opened, then when the mouse hovers over 'about', the self.OnAbout function get's called which I only what to happen when the user clicks specifically on the 'About' menu.</p>
1
2009-07-27T23:39:46Z
1,191,710
<p>Why don't you just bind to the menu items using <code>EVT_MENU</code> instead?</p> <p><code>EVT_MENU_OPEN</code> will fire as soon as any menu is opened. That being said, if that's what you really want, you can always do this:</p> <p>Where you define your menu:</p> <pre><code>self.about_menu = wx.Menu() # or whatever inherited class you have self.Bind(wx.EVT_MENU_OPEN, self.on_menu_open) </code></pre> <p>Then your callback:</p> <pre><code>def on_menu_open(self, event): if event.GetMenu()==self.about_menu: #do something </code></pre>
5
2009-07-28T02:55:50Z
[ "python", "wxpython" ]