title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
What to do with "The input line is too long" error message?
| 682,799
|
<p>I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. </p>
<p>When I try to call the command, I'm getting an error: <code>The input line is too long</code>.</p>
<p>I'm guessing there's a <code>255 character limit</code> (its built using a C system call, but I couldn't find the limitations on that either).</p>
<p>I tried changing the directory with <code>os.chdir()</code> to reduce the folder trail lengths, but when I try using <code>os.system()</code> with <code>"..\folder\filename"</code> it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths?</p>
| 10
|
2009-03-25T18:08:42Z
| 682,824
|
<p>You should use the subprocess module instead. See <a href="http://docs.python.org/library/subprocess.html#subprocess-replacements">this</a> little doc for how to rewrite os.system calls to use subprocess.</p>
| 6
|
2009-03-25T18:15:37Z
|
[
"python",
"command-line",
"windows-console"
] |
What to do with "The input line is too long" error message?
| 682,799
|
<p>I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. </p>
<p>When I try to call the command, I'm getting an error: <code>The input line is too long</code>.</p>
<p>I'm guessing there's a <code>255 character limit</code> (its built using a C system call, but I couldn't find the limitations on that either).</p>
<p>I tried changing the directory with <code>os.chdir()</code> to reduce the folder trail lengths, but when I try using <code>os.system()</code> with <code>"..\folder\filename"</code> it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths?</p>
| 10
|
2009-03-25T18:08:42Z
| 682,906
|
<p>You should use <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> instead of os.system.</p>
<p>subprocess has the advantage of being able to change the directory for you:</p>
<pre><code>import subprocess
my_cwd = r"..\folder\"
my_process = subprocess.Popen(["command name", "option 1", "option 2"], cwd=my_cwd)
my_process.wait() # wait for process to end
if my_process.returncode != 0:
print "Something went wrong!"
</code></pre>
<p>The subprocess module contains some helper functions as well if the above looks a bit verbose.</p>
| 2
|
2009-03-25T18:38:58Z
|
[
"python",
"command-line",
"windows-console"
] |
What to do with "The input line is too long" error message?
| 682,799
|
<p>I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. </p>
<p>When I try to call the command, I'm getting an error: <code>The input line is too long</code>.</p>
<p>I'm guessing there's a <code>255 character limit</code> (its built using a C system call, but I couldn't find the limitations on that either).</p>
<p>I tried changing the directory with <code>os.chdir()</code> to reduce the folder trail lengths, but when I try using <code>os.system()</code> with <code>"..\folder\filename"</code> it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths?</p>
| 10
|
2009-03-25T18:08:42Z
| 3,583,282
|
<p>Even it's a good idea to use <code>subprocess.Popen()</code>, this does not solve the issue.</p>
<p><strong>Your problem is not the 255 characters limit</strong>, this was true on DOS times, later increased to 2048 for Windows NT/2000, and increased again to 8192 for Windows XP+.</p>
<p>The <strong>real solution</strong> is to workaround a very old bug in Windows APIs: <a href="http://msdn.microsoft.com/en-us/library/96ayss4b.aspx">_popen() and _wpopen()</a>. </p>
<p>If you ever use quotes during the command line you have to add the entire command in quoates or you will get the <code>The input line is too long</code> error message.</p>
<p>All Microsoft operating systems starting with Windows XP had a 8192 characters limit which is now enough for any decent command line usage but they forgot to solve this bug. </p>
<p>To overcome their bug <strong>just include your entire command in double quotes</strong>, and if you want to know more real the <a href="http://msdn.microsoft.com/en-us/library/96ayss4b.aspx">MSDN comment on _popen()</a>. </p>
<p>Be careful because these works:</p>
<pre><code>prog
"prog"
""prog" param"
""prog" "param""
</code></pre>
<p>But these will not work:</p>
<pre><code>""prog param""
</code></pre>
<p>If you need a function that does add the quotes when they are needed you can take the one from <a href="http://github.com/ssbarnea/tendo/blob/master/tendo/tee.py">http://github.com/ssbarnea/tendo/blob/master/tendo/tee.py</a></p>
| 16
|
2010-08-27T10:29:48Z
|
[
"python",
"command-line",
"windows-console"
] |
What to do with "The input line is too long" error message?
| 682,799
|
<p>I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. </p>
<p>When I try to call the command, I'm getting an error: <code>The input line is too long</code>.</p>
<p>I'm guessing there's a <code>255 character limit</code> (its built using a C system call, but I couldn't find the limitations on that either).</p>
<p>I tried changing the directory with <code>os.chdir()</code> to reduce the folder trail lengths, but when I try using <code>os.system()</code> with <code>"..\folder\filename"</code> it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths?</p>
| 10
|
2009-03-25T18:08:42Z
| 4,378,603
|
<p>I got the same message but it was strange because the command was not that long (130 characters) and it used to work, it just stopped working one day.
I just closed the command window and opened a new one and it worked.
I have had the command window opened for a long time (maybe months, it's a remote virtual machine).
I guess is some windows bug with a buffer or something.</p>
| 1
|
2010-12-07T15:52:02Z
|
[
"python",
"command-line",
"windows-console"
] |
Redirecting function definitions in python
| 682,822
|
<p>This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful.</p>
<p>The example:</p>
<pre><code>class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem'
return dict.__getitem__(name)
class B(object):
def __init__(self):
self._a = A()
setattr(self, '__getitem__', self._a.__getitem__)
b = B()
c = b['a']
</code></pre>
<p>This outputs:</p>
<pre><code>c = b['a']
TypeError: 'B' object is unsubscriptable
</code></pre>
<p>Even though it's a bizarre way of doing this (clearly subclassing would be more logical), why doesn't it find the method I have explicitly set?</p>
<p>If I do this:</p>
<pre><code>dir(b)
</code></pre>
<p>I get this:</p>
<pre><code>['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a']
</code></pre>
<p>The same issue occurs with other methods such as <code>__iter__</code>. What is it about explicitly defining this method that works?</p>
| 2
|
2009-03-25T18:14:49Z
| 682,836
|
<p>This is because you can't override special class methods on the fly.</p>
<p>I wasn't able to find a reference about this but is basically because they are class methods and are not allowed to be instance methods.</p>
| 1
|
2009-03-25T18:19:25Z
|
[
"python",
"class-attributes"
] |
Redirecting function definitions in python
| 682,822
|
<p>This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful.</p>
<p>The example:</p>
<pre><code>class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem'
return dict.__getitem__(name)
class B(object):
def __init__(self):
self._a = A()
setattr(self, '__getitem__', self._a.__getitem__)
b = B()
c = b['a']
</code></pre>
<p>This outputs:</p>
<pre><code>c = b['a']
TypeError: 'B' object is unsubscriptable
</code></pre>
<p>Even though it's a bizarre way of doing this (clearly subclassing would be more logical), why doesn't it find the method I have explicitly set?</p>
<p>If I do this:</p>
<pre><code>dir(b)
</code></pre>
<p>I get this:</p>
<pre><code>['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a']
</code></pre>
<p>The same issue occurs with other methods such as <code>__iter__</code>. What is it about explicitly defining this method that works?</p>
| 2
|
2009-03-25T18:14:49Z
| 682,877
|
<p>When you use brackets <em><code>[]</code></em> python looks in the class. You must set the method in the class.</p>
<p>Here's your code adapted:</p>
<pre><code>class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem!'
return dict.__getitem__(self, name)
class B(object):
def __init__(self):
self._a = A()
B.__getitem__ = self._a.__getitem__
b = B()
c = b['a']
</code></pre>
| 7
|
2009-03-25T18:29:16Z
|
[
"python",
"class-attributes"
] |
Dynamically change the choices in a wx.ComboBox()
| 682,923
|
<p>I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way?</p>
<p>Oerjan Pettersen</p>
<pre><code>#!/usr/bin/python
#20_combobox.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.p1 = wx.Panel(self)
lst = ['1','2','3']
self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER)
self.st.Bind(wx.EVT_COMBOBOX, self.text_return)
def text_return(self, event):
lst = ['3','4']
self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '20_combobox.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
# wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
</code></pre>
| 13
|
2009-03-25T18:42:34Z
| 682,978
|
<p><a href="http://docs.wxwidgets.org/stable/classwx_combo_box.html" rel="nofollow">wx.ComboBox</a> derives from <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html" rel="nofollow">wx.ItemContainer</a>, which has methods for <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html#a8fdc0090e3eabc762ff0e49e925f8bc4" rel="nofollow">Appending</a>, <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html#aea621d4fdfbc3a06bf24dcc97304e2c1" rel="nofollow">Clearing</a>, <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html#a8844cacec8509fe6e637c6f85eb8b395" rel="nofollow">Inserting</a> and <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html#a0e8379f41e9d7b912564000828140a19" rel="nofollow">Deleting</a> items, all of these methods are available on wx.ComboBox.</p>
<p>One way to do what you want would be to define the text_return() method as follows:</p>
<pre><code>def text_return(self, event):
self.st.Clear()
self.st.Append('3')
self.st.Append('4')
</code></pre>
| 23
|
2009-03-25T18:58:43Z
|
[
"python",
"wxpython",
"wxwidgets"
] |
Data Synchronization framework / algorithm for server<->device?
| 682,951
|
<p>I'm looking to implement data synchronization between servers and distributed clients. The data source on the server is mysql with django on top. The client can vary. Updates can take place on either client or server, and the connection between server and client is not reliable (eg. changes can be made on a disconnected cell phone, should get sync'd when the cell phone has a connection again).</p>
<p>S. Lott suggests using a version control design pattern in <a href="http://stackoverflow.com/questions/413086/client-server-synchronization-pattern-algorithm">this question</a>, which makes sense. I'm wondering if there are any existing packages / implementations of this I can use. Or, should I directly make use of svn/git/etc?</p>
<p>Are there other alternatives? There must be synchronization frameworks or detailed descriptions of algorithms out there, but I'm not having a lot of luck finding them. I'd appreciate if you point me in the right direction.</p>
| 6
|
2009-03-25T18:48:46Z
| 683,394
|
<p>You may find this link useful: <a href="http://pdis.hiit.fi/pdis/download/" rel="nofollow">http://pdis.hiit.fi/pdis/download/</a></p>
<p>It is the Personal Distributed Information Store (PDIS) project download page, and lists out some relevant python packages.</p>
| 0
|
2009-03-25T20:52:49Z
|
[
"python",
"django",
"synchronization"
] |
Data Synchronization framework / algorithm for server<->device?
| 682,951
|
<p>I'm looking to implement data synchronization between servers and distributed clients. The data source on the server is mysql with django on top. The client can vary. Updates can take place on either client or server, and the connection between server and client is not reliable (eg. changes can be made on a disconnected cell phone, should get sync'd when the cell phone has a connection again).</p>
<p>S. Lott suggests using a version control design pattern in <a href="http://stackoverflow.com/questions/413086/client-server-synchronization-pattern-algorithm">this question</a>, which makes sense. I'm wondering if there are any existing packages / implementations of this I can use. Or, should I directly make use of svn/git/etc?</p>
<p>Are there other alternatives? There must be synchronization frameworks or detailed descriptions of algorithms out there, but I'm not having a lot of luck finding them. I'd appreciate if you point me in the right direction.</p>
| 6
|
2009-03-25T18:48:46Z
| 955,216
|
<p>Perhaps using plain old <a href="http://www.samba.org/rsync/" rel="nofollow">rsync</a> is enough.</p>
| 1
|
2009-06-05T10:30:05Z
|
[
"python",
"django",
"synchronization"
] |
Data Synchronization framework / algorithm for server<->device?
| 682,951
|
<p>I'm looking to implement data synchronization between servers and distributed clients. The data source on the server is mysql with django on top. The client can vary. Updates can take place on either client or server, and the connection between server and client is not reliable (eg. changes can be made on a disconnected cell phone, should get sync'd when the cell phone has a connection again).</p>
<p>S. Lott suggests using a version control design pattern in <a href="http://stackoverflow.com/questions/413086/client-server-synchronization-pattern-algorithm">this question</a>, which makes sense. I'm wondering if there are any existing packages / implementations of this I can use. Or, should I directly make use of svn/git/etc?</p>
<p>Are there other alternatives? There must be synchronization frameworks or detailed descriptions of algorithms out there, but I'm not having a lot of luck finding them. I'd appreciate if you point me in the right direction.</p>
| 6
|
2009-03-25T18:48:46Z
| 956,790
|
<p>AFAIK there isnt any generic solution to this mainly due to the diverse requirements for synchronization.</p>
<p>In one of our earlier projects we implemented a <a href="http://static.springsource.org/spring-batch/" rel="nofollow">Spring batching</a> based sync mechanism which relies on last updated timestamp field on each of the tables (that take part in sync).</p>
<p>I have heard about <a href="http://en.wikipedia.org/wiki/SyncML" rel="nofollow">SyncML</a> but dont have much experience with that.</p>
<p>If you have a single server and multiple clients, you could think of a JMS based approach.
The data is bundled and placed in Queues (or topics) and would be pulled by clients.</p>
<p>In your case, since updates are bi-directional, you need to handle conflict detection as well. This brings additional complexities.</p>
| 1
|
2009-06-05T16:18:05Z
|
[
"python",
"django",
"synchronization"
] |
Can pysvn 1.6.3 be made to work with Subversion 1.6 under linux?
| 683,278
|
<p>I see no reference on their website for this. I get pysvn to configure and build, but then it fails all the test. Has anyone had any luck getting this to work under linux?</p>
| 0
|
2009-03-25T20:19:33Z
| 749,823
|
<p>No, it cannot. </p>
<p>Your best bet is to use Subversion 1.5.5. See <a href="http://pysvn.tigris.org/project%5Fstatus.html" rel="nofollow">the site</a> for more details. </p>
| 1
|
2009-04-15T00:15:24Z
|
[
"python",
"linux",
"svn",
"pysvn"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 683,481
|
<p>Here's something, a Python wrapper around the SeaMonkey Javascript interpreter... <a href="http://pypi.python.org/pypi/python-spidermonkey">http://pypi.python.org/pypi/python-spidermonkey</a></p>
| 15
|
2009-03-25T21:13:09Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 683,618
|
<p>There's a bridge based on JavaScriptCore (from WebKit), but it's pretty incomplete:
<a href="http://code.google.com/p/pyjscore/" rel="nofollow">http://code.google.com/p/pyjscore/</a></p>
| 1
|
2009-03-25T21:47:03Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 683,682
|
<p>How about <a href="http://pyjs.org/" rel="nofollow">pyjs</a>?</p>
<p>From the above website:</p>
<blockquote>
<p>pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python.</p>
</blockquote>
| 21
|
2009-03-25T22:00:23Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 683,928
|
<p>If your just interested in sharing complex data types between javascript and python, check out <a href="http://jsonpickle.googlecode.com/svn/docs/index.html">jsonpickle</a>. It wraps the standard Python JSON libraries, but has some smarts in serializing and deserializing Python classes and other data types. </p>
<p>Quite a few Google App Engine projects have used this library. <a href="http://code.google.com/p/joose-js/">Joose</a> and <a href="http://github.com/darwin/firepython/tree/master">FirePython</a> both incorporate jsonpickle.</p>
| 6
|
2009-03-25T23:26:03Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 684,376
|
<p>You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.</p>
<p><a href="http://codespeak.net/pypy" rel="nofollow">http://codespeak.net/pypy</a></p>
<p>Also, check out the informative blog:</p>
<p><a href="http://morepypy.blogspot.com/" rel="nofollow">http://morepypy.blogspot.com/</a></p>
<p>Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).</p>
<p><a href="http://bub-n-bros.sourceforge.net" rel="nofollow">http://bub-n-bros.sourceforge.net</a></p>
| 2
|
2009-03-26T03:01:25Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 731,196
|
<p>there are two projects that allow an "obvious" transition between python objects and javascript objects, with "obvious" translations from int or float to Number and str or unicode to String: <a href="http://code.google.com/p/pyv8">PyV8</a> and, as one writer has already mentioned: <a href="http://pypi.python.org/pypi/python-spidermonkey">python-spidermonkey</a>.</p>
<p>there are actually two implementations of pyv8 - the original experiment was by sebastien louisel, and the second one (in active development) is by flier liu.</p>
<p>my interest in these projects has been to link them to <a href="http://pyjs.org">pyjamas</a>, a python-to-javascript compiler, to create a JIT python accelerator.</p>
<p>so there is plenty out there - it just depends what you want to do.</p>
| 8
|
2009-04-08T18:18:28Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 4,788,789
|
<p>another possibility is to use XPCOM, say in XUL based apps (like firefox, thunderbird, komodo etc.)</p>
| 1
|
2011-01-25T00:27:57Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 8,181,668
|
<p>I was playing with Pyjon some time ago and seems manage to write Javascript's eval directly in Python and ran simple programs... Although it is not complete implementation of JS and rather an experiment.
Get it here:</p>
<p><a href="http://code.google.com/p/pyjon/" rel="nofollow">http://code.google.com/p/pyjon/</a></p>
| 1
|
2011-11-18T11:27:41Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 25,085,533
|
<p><a href="https://pypi.python.org/pypi/PyExecJS" rel="nofollow">PyExecJS</a> is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.</p>
<pre><code>>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> execjs.get().name
'Node.js (V8)'
</code></pre>
| 1
|
2014-08-01T17:24:22Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 27,460,269
|
<p>Use <a href="https://github.com/PiotrDabkowski/Js2Py" rel="nofollow">Js2Py</a> to translate JavaScript to Python, this is the only tool available :)</p>
| 1
|
2014-12-13T15:08:56Z
|
[
"javascript",
"python"
] |
Best way to integrate Python and JavaScript?
| 683,462
|
<p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.mozilla.org/rhino/">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>).</p>
| 44
|
2009-03-25T21:08:11Z
| 39,096,005
|
<p>This question is not exactly young, but there have come up some alternatives:</p>
<ul>
<li>"<a href="http://www.skulpt.org" rel="nofollow">Skulpt</a> is an <em>entirely in-browser</em> implementation of Python."</li>
<li><a href="https://www.brython.info" rel="nofollow">Brython</a> - "A Python 3 implementation for client-side web programming"</li>
<li><a href="http://www.rapydscript.com" rel="nofollow">RapydScript</a> - "Python-like JavaScript without the extra overhead or quirks"</li>
<li><a href="http://www.transcrypt.org" rel="nofollow">Transcrypt</a> - "Lean and mean Python to JavaScript compiler with multiple inheritance, sourcemaps and selective operator overloading." (also <a href="https://github.com/JdeH/Transcrypt" rel="nofollow">on Github</a>)</li>
</ul>
| 2
|
2016-08-23T08:25:03Z
|
[
"javascript",
"python"
] |
Timeout on a HTTP request in python
| 683,493
|
<p>Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?</p>
| 1
|
2009-03-25T21:17:45Z
| 683,519
|
<p>Set the HTTP request timeout.</p>
| 2
|
2009-03-25T21:22:11Z
|
[
"python",
"httpwebrequest"
] |
Timeout on a HTTP request in python
| 683,493
|
<p>Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?</p>
| 1
|
2009-03-25T21:17:45Z
| 683,545
|
<p>The timeout parameter to <a href="http://docs.python.org/library/urllib2.html#urllib2.urlopen" rel="nofollow">urllib2.urlopen</a>, or <a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow">httplib</a>. The original urllib has no such convenient feature. You can also use an asynchronous HTTP client such as <a href="http://twistedmatrix.com/documents/8.1.0/api/twisted.web.client.html" rel="nofollow">twisted.web.client</a>, but that's probably not necessary.</p>
| 1
|
2009-03-25T21:28:29Z
|
[
"python",
"httpwebrequest"
] |
Timeout on a HTTP request in python
| 683,493
|
<p>Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?</p>
| 1
|
2009-03-25T21:17:45Z
| 683,574
|
<p>If you are making a lot of HTTP requests, you can change this globally by calling <a href="http://docs.python.org/library/socket.html#socket.setdefaulttimeout" rel="nofollow">socket.setdefaulttimeout</a></p>
| 1
|
2009-03-25T21:35:52Z
|
[
"python",
"httpwebrequest"
] |
How to save an xml file to disk?
| 683,494
|
<p>I did something similar to <a href="http://www.postneo.com/projects/pyxml/" rel="nofollow">this</a>, but couldn't find a way to write the result to an xml file.</p>
| 2
|
2009-03-25T21:17:56Z
| 683,505
|
<p>The code on the web page you linked to uses <code>doc.toprettyxml</code> to create a string from the XML DOM, so you can just write that string to a file:</p>
<pre><code>f = open("output.xml", "w")
try:
f.write(doc.toprettyxml(indent=" "))
finally:
f.close()
</code></pre>
<p>In Python 2.6 (or 2.7 I suppose, whenever it comes out), you can use the "<code>with</code>" statement:</p>
<pre><code>with open("output.xml", "w") as f:
f.write(doc.toprettyxml(indent=" "))
</code></pre>
<p>This also works in Python 2.5 if you put</p>
<pre><code>from __future__ import with_statement
</code></pre>
<p>at the beginning of the file.</p>
| 11
|
2009-03-25T21:19:59Z
|
[
"python",
"xml"
] |
How to save an xml file to disk?
| 683,494
|
<p>I did something similar to <a href="http://www.postneo.com/projects/pyxml/" rel="nofollow">this</a>, but couldn't find a way to write the result to an xml file.</p>
| 2
|
2009-03-25T21:17:56Z
| 683,510
|
<pre><code>f = open('yourfile.xml', 'w')
xml.dom.ext.PrettyPrint(doc, f)
f.close()
</code></pre>
| 1
|
2009-03-25T21:21:14Z
|
[
"python",
"xml"
] |
How to save an xml file to disk?
| 683,494
|
<p>I did something similar to <a href="http://www.postneo.com/projects/pyxml/" rel="nofollow">this</a>, but couldn't find a way to write the result to an xml file.</p>
| 2
|
2009-03-25T21:17:56Z
| 683,978
|
<p>coonj is kind of right, but xml.dom.ext.PrettyPrint is part of the increasingly neglected PyXML extension package. If you want to stay within the supplied-as-standard minidom, you'd say:</p>
<pre><code>f= open('yourfile.xml', 'wb')
doc.writexml(f, encoding= 'utf-8')
f.close()
</code></pre>
<p>(Or using the âwithâ statement as mentioned by David to make it slightly shorter. Use mode 'wb' to avoid unwanted CRLF newlines on Windows interfering with encodings like UTF-16. Because XML has its own mechanisms for handling newline interpretation, it should be treated as a binary file rather than text.)</p>
<p>If you don't include the âencodingâ argument (to either writexml or toprettyxml), it'll try to write a Unicode string direct to the file, so if there are any non-ASCII characters in it, you'll get a UnicodeEncodeError. Don't try to .encode() the results of toprettyxml yourself; for non-UTF-8 encodings this can generate non-well-formed XML.</p>
<p>There's no âwriteprettyxml()â function, but it's trivially simple to do it yourself:</p>
<pre><code>with open('output.xml', 'wb') as f:
doc.writexml(f, encoding= 'utf-8', indent= ' ', newl= '\n')
</code></pre>
| 8
|
2009-03-25T23:43:41Z
|
[
"python",
"xml"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,570
|
<p>Why don't you subclass Queue?</p>
<pre><code>
class MyQueue(Queue):
# by using *args, you can have a variable number of arguments
def put(self,*args):
for arg in args:
Queue.put(self,arg)
</code></pre>
<p>or, why don't you put a list?</p>
<pre><code>
list = [function_obj]
for arg in function_args:
list.append(arg)
queue.put(list)
</code></pre>
| -2
|
2009-03-25T21:35:34Z
|
[
"python",
"multithreading"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,611
|
<p>So simple:</p>
<pre><code>def DestinationThread( a ) :
while True :
items = q.get()
func = items[0]
args = items[1:]
func(*args)
</code></pre>
| 20
|
2009-03-25T21:46:41Z
|
[
"python",
"multithreading"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,612
|
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread() :
while True :
f, args = q.get()
f(*args)
start_new_thread( DestinationThread, tuple() )
print "start"
sleep( 1 )
q.put( (HandleMsg, [1, 2]) )
sleep( 1 )
q.put( (HandleAnotherMsg, [1, 2, 3]) )
sleep( 1 )
print "stop"
</code></pre>
| 7
|
2009-03-25T21:46:45Z
|
[
"python",
"multithreading"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,652
|
<p>It sounds like you want to use the <code>apply()</code> intrinsic or its successor:</p>
<pre><code>def f(x. y):
print x+y
args = ( 1, 2 )
apply(f, args) # old way
f(*args) # new way
</code></pre>
| 0
|
2009-03-25T21:54:18Z
|
[
"python",
"multithreading"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,755
|
<p>I've used a similar construct before:</p>
<pre><code>class Call:
def __init__(self, fn, *args, **kwargs):
self.fn = fn
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.fn(*self.args, **self.kwargs)
x = Call(zip, [0,1], [2,3], [4,5])
</code></pre>
<p>You should then be able to pass x to your other thread and call it from there:</p>
<pre><code>x() # returns the same as zip([0,1], [2,3], [4,5])
</code></pre>
| 2
|
2009-03-25T22:23:30Z
|
[
"python",
"multithreading"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,945
|
<p>You can create an abstract message class with a run method. Then for each function that need to be transmitted via the queue, subclass and implement the function as the run method.
The sending thread will create an instance of the proper sub class and put it into the queue. The receiving thread will get an object from the queue and blindly execute the run method.</p>
<p>This is usually called the Command pattern (Gamma et al.)</p>
<p>Example:</p>
<pre><code>class Message (object):
"""abstract message class"""
def __init__(self, **kwargs):
self.kwargs = kwargs
def run(self):
pass
class MessageOne (Message):
"""one message class"""
def run(self):
# perform this emssage's action using the kwargs
</code></pre>
<p>The sender will instantiate and send a message:</p>
<pre><code>queue.put(MessageOne(one='Eins', two='Deux'))
</code></pre>
<p>The receiver simply gets a message object and execute it run method (without having to it..else.. thru the available types of messages):</p>
<pre><code>msg = queue.get()
msg.run()
</code></pre>
| 0
|
2009-03-25T23:33:57Z
|
[
"python",
"multithreading"
] |
how to put a function and arguments into python queue?
| 683,542
|
<p>I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.</p>
<p>This task can be solved multiple ways. The easy one is tu put a big
'if...if..if' in destination thread's message pick cycle and call
function according to received message type and saved arguments. But this
will result in huge amounf of code ( or big lookup table ) and adding new
messages / handler function will evolve additonal step to write code in
message pick cycle.</p>
<p>Since python treats functions as first-class objects and have tuples, i want
to put a function and argumens inside a message, so than destination thread
picks a message it just call a functon saved within a message without any
knowledge what function it is.</p>
<p>I can write a code for a functions with specified number of arguments:</p>
<pre><code>from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread( a ) :
while True :
(f, a, b) = q.get()
f( a, b )
start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
</code></pre>
<p>The question is: how to modify a code so i can put() a function with
any number of arguments in queue? for example HandleAnotherMsg() ?
Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(</p>
| 8
|
2009-03-25T21:27:52Z
| 683,969
|
<p>Another interesting option is simply to pass in a lambda.</p>
<pre><code>q.put(lambda: HandleMsg(1,2))
q.put(lambda: HandleAnother(8, "hello", extra="foo"))
def DestinationThread() :
while True :
f = q.get()
f()
</code></pre>
| 10
|
2009-03-25T23:41:43Z
|
[
"python",
"multithreading"
] |
can you distinguish between a test & a variable setting?
| 684,109
|
<p>I like doctest but when you have complex arguments that you need to
set before you pass to a function it become really hard to read..
Hence, you start using multiple lines assigning then calling the
function that you would like to test.. This approach however, will
report that you have multiple tests rather then the real number of
tests that you have.. An example will illustrate what I mean..</p>
<pre><code>def returnme(x):
"""
Returns what you pass
>>> y = (2, 3, 5, 7)
>>> returnme(y)
(2, 3, 5, 7)
"""
return x
</code></pre>
<p>In the above snippet, there is only one test and the other is just a
variable assignment, however, this is what gets reported..</p>
<pre>
Trying:
y = (2, 3, 5, 7)
Expecting nothing
ok
Trying:
returnme(y)
Expecting:
(2, 3, 5, 7)
ok
2 tests in 2 items.
2 passed and 0 failed.
</pre>
<p>I've looked at the flags documented, surely I missing something..</p>
| 0
|
2009-03-26T00:52:51Z
| 684,122
|
<p>Prepend three periods to indicate that you want to continue the current line, like so:</p>
<pre><code>def returnme(x):
"""
Returns what you pass
>>> y = (2, 3, 5, 7)
... returnme(y) # Note the difference here.
... # Another blank line ends this test.
(2, 3, 5, 7)
"""
return x
</code></pre>
<p>That should do the trick. You can read more about how doctest interprets the individual tests <a href="http://docs.python.org/library/doctest.html#how-are-docstring-examples-recognized" rel="nofollow"><strong>here</strong></a>.</p>
| 5
|
2009-03-26T00:58:42Z
|
[
"python",
"unit-testing",
"doctest"
] |
XML schema
| 684,117
|
<p>I've a schema file (.xsd), I'd like to generate a xml document using this schema. Is there any online tool available,if not what is quickest way (like couple of lines of code using vb.net).</p>
<p>Thanks for your help.</p>
<p>-Vuppala </p>
| 1
|
2009-03-26T00:55:46Z
| 684,121
|
<p>If I'm understanding you correct, this tool might help.</p>
<p><a href="http://www.stylusstudio.com/xml%5Fgenerator.html" rel="nofollow">XML Generator</a></p>
<p>It's what I usually use when working with XML.</p>
<p>If you want a solution through code you can use this:</p>
<pre><code>XmlTextWriter textWriter = new XmlTextWriter("po.xml", null);
textWriter.Formatting = Formatting.Indented;
XmlQualifiedName qname = new XmlQualifiedName("PurchaseOrder",
"http://tempuri.org");
XmlSampleGenerator generator = new XmlSampleGenerator("po.xsd", qname);
genr.WriteXml(textWriter);
</code></pre>
<p>Taken from <a href="http://msdn.microsoft.com/en-us/library/aa302296.aspx" rel="nofollow">MSDN</a></p>
| 1
|
2009-03-26T00:58:30Z
|
[
"c#",
"python",
"ruby"
] |
XML schema
| 684,117
|
<p>I've a schema file (.xsd), I'd like to generate a xml document using this schema. Is there any online tool available,if not what is quickest way (like couple of lines of code using vb.net).</p>
<p>Thanks for your help.</p>
<p>-Vuppala </p>
| 1
|
2009-03-26T00:55:46Z
| 684,123
|
<p>Download <a href="http://pyxsd.org/" rel="nofollow">pyXSD</a>.</p>
<p>Use it to build Python class definitions from the XSD's.</p>
<p>Build objects from those class definitions.</p>
<p>Save the Python objects in XML notation.</p>
<p>An alternative is <a href="http://www.rexx.com/~dkuhlman/generateDS.html" rel="nofollow">GenerateDS</a>.</p>
| 0
|
2009-03-26T00:58:44Z
|
[
"c#",
"python",
"ruby"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 684,186
|
<p>"Reload is no longer a function in Python 3. Use imp.reload() instead" copied from comments</p>
<p>Use the <code>reload</code> builtin function:</p>
<p><a href="https://docs.python.org/2/library/functions.html#reload">https://docs.python.org/2/library/functions.html#reload</a></p>
<blockquote>
<p>When <code>reload(module)</code> is executed:</p>
<ul>
<li>Python modulesâ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the moduleâs dictionary. The init function of extension modules is not called a second time.</li>
<li>As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.</li>
<li>The names in the module namespace are updated to point to any new or changed objects.</li>
<li>Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.</li>
</ul>
</blockquote>
<p>Example:</p>
<pre><code># Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py
# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py
# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
</code></pre>
| 206
|
2009-03-26T01:25:34Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 684,229
|
<blockquote>
<p>So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
</blockquote>
<p>Yes, just saying <code>import</code> again gives you the existing copy of the module from <code>sys.modules</code>.</p>
<p>You can say <code>reload(module)</code> to update <code>sys.modules</code> and get a new copy of that single module, but if any other modules have a reference to the original module <em>or any object from the original module</em>, they will keep their old references and Very Confusing Things will happen.</p>
<p>So if you've got a module <code>a</code>, which depends on module <code>b</code>, and <code>b</code> changes, you have to âreload bâ followed by âreload aâ. If you've got two modules which depend on each other, which is extremely common when those modules are part of the same package, you can't reload them both: if you reload <code>p.a</code> it'll get a reference to the old <code>p.b</code>, and vice versa. The only way to do it is to unload them both at once by deleting their items from <code>sys.modules</code>, before importing them again. This is icky and has some practical pitfalls to do with modules entries being None as a failed-relative-import marker.</p>
<p>And if you've got a module which passes references to its objects to system modulesâââfor example it registers a codec, or adds a warnings handlerâââyou're stuck; you can't reload the system module without confusing the rest of the Python environment.</p>
<p>In summary: for all but the simplest case of one self-contained module being loaded by one standalone script, <code>reload()</code> is very tricky to get right; if, as you imply, you are using a âpackageâ, you will probably be better off continuing to cycle the interpreter.</p>
| 29
|
2009-03-26T01:46:28Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 684,311
|
<p>See here for a good explanation of how your dependent modules won't be reloaded and the effects that can have:</p>
<p><a href="http://pyunit.sourceforge.net/notes/reloading.html" rel="nofollow">http://pyunit.sourceforge.net/notes/reloading.html</a></p>
<p>The way pyunit solved it was to track dependent modules by overriding __import__ then to delete each of them from sys.modules and re-import. They probably could've just reload'ed them, though.</p>
| 3
|
2009-03-26T02:23:07Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 685,004
|
<p>Basically <a href="http://docs.python.org/library/functions.html#reload">reload</a> as in allyourcode's asnwer. But it won't change underlying the code of already instantiated object or referenced functions. Extending from his answer:</p>
<pre><code>#Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py
# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
>>> x = mymodule.x
>>> x()
version 1
>>> x is mymodule.x
True
# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py
# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
>>> x()
version 1
>>> x is mymodule.x
False
</code></pre>
| 9
|
2009-03-26T09:04:43Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 685,040
|
<p>Not sure if this does all expected things, but you can do just like that:</p>
<pre><code>>>> del mymodule
>>> import mymodule
</code></pre>
| 3
|
2009-03-26T09:22:16Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 8,637,233
|
<p>Short answer:</p>
<p>try using <a href="https://bitbucket.org/petershinners/reimport" rel="nofollow">reimport: a full featured reload for Python</a>.</p>
<p>Longer answer: </p>
<p>It looks like this question was asked/answered prior to the release of <a href="https://bitbucket.org/petershinners/reimport" rel="nofollow">reimport</a>, which bills itself as a "full featured reload for Python":</p>
<blockquote>
<p>This module intends to be a full featured replacement for Python's reload function. It is targeted towards making a reload that works for Python plugins and extensions used by longer running applications.</p>
<p>Reimport currently supports Python 2.4 through 2.6.</p>
<p>By its very nature, this is not a completely solvable problem. The goal of this module is to make the most common sorts of updates work well. It also allows individual modules and package to assist in the process. A more detailed description of what happens is on the overview page.</p>
</blockquote>
<p>Note: Although the <code>reimport</code> explicitly supports Python 2.4 through 2.6, I've been trying it on 2.7 and it seems to work just fine.</p>
| 10
|
2011-12-26T15:58:19Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 13,121,908
|
<p>In Python 3, the behaviour changes. </p>
<pre><code>>>> import my_stuff
</code></pre>
<p>... do something with my_stuff, then later:</p>
<pre><code>>>>> import imp
>>>> imp.reload(my_stuff)
</code></pre>
<p>and you get a brand new, reloaded my_stuff.</p>
| 20
|
2012-10-29T12:45:24Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 22,894,171
|
<p>All the answers above about reload() or imp.reload() are deprecated.</p>
<p>reload() is no longer a builtin function in python 3 and imp.reload() is marked deprecated (see help(imp)).</p>
<p>It's better to use <a href="https://docs.python.org/3.4/library/importlib.html#importlib.reload"><code>importlib.reload()</code></a> instead.</p>
| 102
|
2014-04-06T12:41:19Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 30,608,568
|
<pre><code>import sys
del sys.modules['module_name']
</code></pre>
| 0
|
2015-06-02T23:59:11Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 34,201,014
|
<p>dragonfly's answer worked for me (python 3.4.3).</p>
<pre><code>import sys
del sys.modules['module_name']
</code></pre>
<p>Here is a lower level solution :</p>
<pre><code>exec(open("MyClass.py").read(), globals())
</code></pre>
| -2
|
2015-12-10T11:42:49Z
|
[
"python"
] |
How to re import an updated package while in Python Interpreter?
| 684,171
|
<p>I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.</p>
| 252
|
2009-03-26T01:19:41Z
| 36,375,742
|
<p>No matter how many times you import a module, you'll get the same copy of the module from <code>sys.modules</code> - which was loaded at first <code>import mymodule</code></p>
<p>I am answering this late, as each of the above/previous answer has a bit of the answer, so I am attempting to sum it all up in a single answer.</p>
<p><strong>Using built-in function</strong>:</p>
<p>For <strong>Python 2.x</strong> - Use the built-in <a href="https://docs.python.org/2/library/functions.html#reload"><code>reload(mymodule)</code></a> function.</p>
<p>For <strong>Python 3.x</strong> - Use the <a href="https://docs.python.org/3.0/library/imp.html#imp.reload"><code>imp.reload(mymodule)</code></a>.</p>
<p>For <strong>Python 3.4</strong> - In Python 3.4 <code>imp</code> has been deprecated in favor of <code>importlib</code> i.e. <a href="https://docs.python.org/3.4/library/importlib.html#importlib.reload"><code>importlib.reload(mymodule)</code></a></p>
<p><strong>Few caveats</strong>: </p>
<ul>
<li>It is generally not very useful to reload built-in or dynamically
loaded modules. Reloading <code>sys</code>, <code>__main__</code>, <a href="https://docs.python.org/3.4/library/builtins.html#module-builtins"><code>builtins</code></a> and other key
modules is not recommended. </li>
<li>In many cases extension modules are not
designed to be initialized more than once, and may fail in arbitrary
ways when reloaded. If a module imports objects from another module
using <code>from</code> ... <code>import</code> ..., calling <code>reload()</code> for the other module does
not redefine the objects imported from it â one way around this is to
re-execute the <code>from</code> statement, another is to use <code>import</code> and qualified
names (module.name) instead. </li>
<li>If a module instantiates instances of a
class, reloading the module that defines the class does not affect
the method definitions of the instances â they continue to use the
old class definition. The same is true for derived classes.</li>
</ul>
<hr>
<p><strong>External packages</strong>:</p>
<p><a href="https://bitbucket.org/petershinners/reimport">reimport</a> - Reimport currently supports Python 2.4 through 2.7.</p>
<p><a href="http://svn.python.org/projects/sandbox/trunk/xreload/xreload.py">xreload</a>- This works by executing the module in a scratch namespace, and then
patching classes, methods and functions in place. This avoids the
need to patch instances. New objects are copied into the target
namespace.</p>
<p><a href="https://code.google.com/archive/p/livecoding/">livecoding</a> - Code reloading allows a running application to change its behaviour in response to changes in the Python scripts it uses. When the library detects a Python script has been modified, it reloads that script and replaces the objects it had previously made available for use with newly reloaded versions. As a tool, it allows a programmer to avoid interruption to their workflow and a corresponding loss of focus. It enables them to remain in a state of flow. Where previously they might have needed to restart the application in order to put changed code into effect, those changes can be applied immediately.</p>
| 7
|
2016-04-02T16:22:16Z
|
[
"python"
] |
Django Template if tag not working under FastCGI when checking bool True
| 684,371
|
<p>I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI.</p>
<p>If I have a template as such:</p>
<pre><code>{% with True as something %}
{%if something%}
It Worked!!!
{%endif%}
{%endwith%}
</code></pre>
<p>it should output the string "It Worked!!!". It does not on my production server with mod_fastcgi. </p>
<p>This works perfectly when I run locally with runserver.</p>
<p>I modified the code to the following to make it work for the sake of expediency, and the problem went away. </p>
<pre><code>{% with "True" as something %}
{%if something%}
It Worked!!!
{%endif%}
{%endwith%}
</code></pre>
<p>It seems that the template parser, when running under FastCGI, cannot ascertain Truthiness (or Truthitude)[kudos if you get the reference] of bool variables. </p>
<p>Has anyone seen this? Do you have a solution? </p>
| 2
|
2009-03-26T02:57:46Z
| 684,430
|
<p>Hmm... <code>True</code> is not a valid token in django template language, is it? I have no idea how it worked locally -- unless it's being added to the context with a non-zero value somewhere. Therefore, I think your second problem may not be related to the first one.</p>
| 3
|
2009-03-26T03:37:50Z
|
[
"python",
"django",
"templates",
"fastcgi",
"python-2.6"
] |
Is it safe to yield from within a "with" block in Python (and why)?
| 685,046
|
<p>The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.</p>
<p>The basic question is whether or not something like this works:</p>
<pre><code>def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
</code></pre>
<p>Which it does. (You can test it!)</p>
<p>The deeper concern is that <code>with</code> is supposed to be something an alternative to <code>finally</code>, where you ensure that a resource is released at the end of the block. Coroutines can suspend and resume execution from <em>within</em> the <code>with</code> block, so <strong>how is the conflict resolved?</strong></p>
<p>For example, if you open a file with read/write both inside and outside a coroutine while the coroutine hasn't yet returned:</p>
<pre><code>def coroutine():
with open('test.txt', 'rw+') as fh:
for line in fh:
yield line
a = coroutine()
assert a.next() # Open the filehandle inside the coroutine first.
with open('test.txt', 'rw+') as fh: # Then open it outside.
for line in fh:
print 'Outside coroutine: %r' % repr(line)
assert a.next() # Can we still use it?
</code></pre>
<h3>Update</h3>
<p>I was going for write-locked file handle contention in the previous example, but since most OSes allocate filehandles per-process there will be no contention there. (Kudos to @Miles for pointing out the example didn't make too much sense.) Here's my revised example, which shows a real deadlock condition:</p>
<pre><code>import threading
lock = threading.Lock()
def coroutine():
with lock:
yield 'spam'
yield 'eggs'
generator = coroutine()
assert generator.next()
with lock: # Deadlock!
print 'Outside the coroutine got the lock'
assert generator.next()
</code></pre>
| 33
|
2009-03-26T09:24:56Z
| 685,157
|
<p>I don't really understand what conflict you're asking about, nor the problem with the example: it's fine to have two coexisting, independent handles to the same file.</p>
<p>One thing I didn't know that I learned in response to your question it that there is a new close() method on generators:</p>
<blockquote>
<p><code>close()</code> raises a new <code>GeneratorExit</code> exception inside the generator to terminate the iteration. On receiving this exception, the generatorâs code must either raise <code>GeneratorExit</code> or <code>StopIteration</code>.</p>
<p><code>close()</code> is called when a generator is garbage-collected, so this means the generatorâs code gets one last chance to run before the generator is destroyed. This last chance means that <code>try...finally</code> statements in generators can now be guaranteed to work; the <code>finally</code> clause will now always get a chance to run. This seems like a minor bit of language trivia, but using generators and <code>try...finally</code> is actually necessary in order to implement the <code>with</code> statement described by PEP 343.</p>
<p><a href="http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features">http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features</a></p>
</blockquote>
<p>So that handles the situation where a <code>with</code> statement is used in a generator, but it yields in the middle but never returnsâthe context manager's <code>__exit__</code> method will be called when the generator is garbage-collected.</p>
<p><hr /></p>
<p><strong>Edit</strong>:</p>
<p>With regards to the file handle issue: I sometimes forget that there exist platforms that aren't POSIX-like. :)</p>
<p>As far as locks go, I think RafaÅ Dowgird hits the head on the nail <a href="#685248">when he says</a> "You just have to be aware that the generator is just like any other object that holds resources." I don't think the <code>with</code> statement is really that relevant here, since this function suffers from the same deadlock issues:</p>
<pre><code>def coroutine():
lock.acquire()
yield 'spam'
yield 'eggs'
lock.release()
generator = coroutine()
generator.next()
lock.acquire() # whoops!
</code></pre>
| 17
|
2009-03-26T10:12:08Z
|
[
"python",
"resources",
"coroutine"
] |
Is it safe to yield from within a "with" block in Python (and why)?
| 685,046
|
<p>The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.</p>
<p>The basic question is whether or not something like this works:</p>
<pre><code>def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
</code></pre>
<p>Which it does. (You can test it!)</p>
<p>The deeper concern is that <code>with</code> is supposed to be something an alternative to <code>finally</code>, where you ensure that a resource is released at the end of the block. Coroutines can suspend and resume execution from <em>within</em> the <code>with</code> block, so <strong>how is the conflict resolved?</strong></p>
<p>For example, if you open a file with read/write both inside and outside a coroutine while the coroutine hasn't yet returned:</p>
<pre><code>def coroutine():
with open('test.txt', 'rw+') as fh:
for line in fh:
yield line
a = coroutine()
assert a.next() # Open the filehandle inside the coroutine first.
with open('test.txt', 'rw+') as fh: # Then open it outside.
for line in fh:
print 'Outside coroutine: %r' % repr(line)
assert a.next() # Can we still use it?
</code></pre>
<h3>Update</h3>
<p>I was going for write-locked file handle contention in the previous example, but since most OSes allocate filehandles per-process there will be no contention there. (Kudos to @Miles for pointing out the example didn't make too much sense.) Here's my revised example, which shows a real deadlock condition:</p>
<pre><code>import threading
lock = threading.Lock()
def coroutine():
with lock:
yield 'spam'
yield 'eggs'
generator = coroutine()
assert generator.next()
with lock: # Deadlock!
print 'Outside the coroutine got the lock'
assert generator.next()
</code></pre>
| 33
|
2009-03-26T09:24:56Z
| 685,179
|
<p>That would be how I expected things to work. Yes, the block will not release its resources until it completes, so in that sense the resource has escaped it's lexical nesting. However but this is no different to making a function call that tried to use the same resource within a with block - nothing helps you in the case where the block has <em>not</em> yet terminated, for <em>whatever</em> reason. It's not really anything specific to generators.</p>
<p>One thing that might be worth worrying about though is the behaviour if the generator is <em>never</em> resumed. I would have expected the <code>with</code> block to act like a <code>finally</code> block and call the <code>__exit__</code> part on termination, but that doesn't seem to be the case.</p>
| 0
|
2009-03-26T10:19:42Z
|
[
"python",
"resources",
"coroutine"
] |
Is it safe to yield from within a "with" block in Python (and why)?
| 685,046
|
<p>The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.</p>
<p>The basic question is whether or not something like this works:</p>
<pre><code>def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
</code></pre>
<p>Which it does. (You can test it!)</p>
<p>The deeper concern is that <code>with</code> is supposed to be something an alternative to <code>finally</code>, where you ensure that a resource is released at the end of the block. Coroutines can suspend and resume execution from <em>within</em> the <code>with</code> block, so <strong>how is the conflict resolved?</strong></p>
<p>For example, if you open a file with read/write both inside and outside a coroutine while the coroutine hasn't yet returned:</p>
<pre><code>def coroutine():
with open('test.txt', 'rw+') as fh:
for line in fh:
yield line
a = coroutine()
assert a.next() # Open the filehandle inside the coroutine first.
with open('test.txt', 'rw+') as fh: # Then open it outside.
for line in fh:
print 'Outside coroutine: %r' % repr(line)
assert a.next() # Can we still use it?
</code></pre>
<h3>Update</h3>
<p>I was going for write-locked file handle contention in the previous example, but since most OSes allocate filehandles per-process there will be no contention there. (Kudos to @Miles for pointing out the example didn't make too much sense.) Here's my revised example, which shows a real deadlock condition:</p>
<pre><code>import threading
lock = threading.Lock()
def coroutine():
with lock:
yield 'spam'
yield 'eggs'
generator = coroutine()
assert generator.next()
with lock: # Deadlock!
print 'Outside the coroutine got the lock'
assert generator.next()
</code></pre>
| 33
|
2009-03-26T09:24:56Z
| 685,248
|
<p>I don't think there is a real conflict. You just have to be aware that the generator is just like any other object that holds resources, so it is the creator's responsibility to make sure it is properly finalized (and to avoid conflicts/deadlock with the resources held by the object). The only (minor) problem I see here is that generators don't implement the context management protocol (at least as of Python 2.5), so you cannot just:</p>
<pre><code>with coroutine() as cr:
doSomething(cr)
</code></pre>
<p>but instead have to:</p>
<pre><code>cr = coroutine()
try:
doSomething(cr)
finally:
cr.close()
</code></pre>
<p>The garbage collector does the <code>close()</code> anyway, but it's bad practice to rely on that for freeing resources.</p>
| 8
|
2009-03-26T10:44:15Z
|
[
"python",
"resources",
"coroutine"
] |
Is it safe to yield from within a "with" block in Python (and why)?
| 685,046
|
<p>The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.</p>
<p>The basic question is whether or not something like this works:</p>
<pre><code>def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
</code></pre>
<p>Which it does. (You can test it!)</p>
<p>The deeper concern is that <code>with</code> is supposed to be something an alternative to <code>finally</code>, where you ensure that a resource is released at the end of the block. Coroutines can suspend and resume execution from <em>within</em> the <code>with</code> block, so <strong>how is the conflict resolved?</strong></p>
<p>For example, if you open a file with read/write both inside and outside a coroutine while the coroutine hasn't yet returned:</p>
<pre><code>def coroutine():
with open('test.txt', 'rw+') as fh:
for line in fh:
yield line
a = coroutine()
assert a.next() # Open the filehandle inside the coroutine first.
with open('test.txt', 'rw+') as fh: # Then open it outside.
for line in fh:
print 'Outside coroutine: %r' % repr(line)
assert a.next() # Can we still use it?
</code></pre>
<h3>Update</h3>
<p>I was going for write-locked file handle contention in the previous example, but since most OSes allocate filehandles per-process there will be no contention there. (Kudos to @Miles for pointing out the example didn't make too much sense.) Here's my revised example, which shows a real deadlock condition:</p>
<pre><code>import threading
lock = threading.Lock()
def coroutine():
with lock:
yield 'spam'
yield 'eggs'
generator = coroutine()
assert generator.next()
with lock: # Deadlock!
print 'Outside the coroutine got the lock'
assert generator.next()
</code></pre>
| 33
|
2009-03-26T09:24:56Z
| 685,249
|
<p>Because <code>yield</code> can execute arbitrary code, I'd be very wary of holding a lock over a yield statement. You can get a similar effect in lots of other ways, though, including calling a method or functions which might be have been overridden or otherwise modified.</p>
<p>Generators, however, are always (nearly always) "closed", either with an explicit <code>close()</code> call, or just by being garbage-collected. Closing a generator throws a <code>GeneratorExit</code> exception inside the generator and hence runs finally clauses, with statement cleanup, etc. You can catch the exception, but you must throw or exit the function (i.e. throw a <code>StopIteration</code> exception), rather than yield. It's probably poor practice to rely on the garbage collector to close the generator in cases like you've written, because that could happen later than you might want, and if someone calls sys._exit(), then your cleanup might not happen at all.</p>
| 1
|
2009-03-26T10:44:54Z
|
[
"python",
"resources",
"coroutine"
] |
separate threads in pygtk application
| 685,224
|
<p>I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main_quit is called. This is confusing me.</p>
<p>The relevant code:</p>
<pre><code>class MTP_Connection(threading.Thread):
def __init__(self, HOME_DIR, username):
self.filename = HOME_DIR + "mtp-dump_" + username
threading.Thread.__init__(self)
def run(self):
#test run
for i in range(1, 10):
time.sleep(1)
print i
</code></pre>
<p>..........................</p>
<pre><code>start_time = time.time()
conn = MTP_Connection(self.HOME_DIR, self.username)
conn.start()
progress_bar = ProgressBar(self.tree.get_widget("progressbar"),
update_speed=100, pulse_mode=True)
while conn.isAlive():
while gtk.events_pending():
gtk.main_iteration()
if time.time() - start_time > 5:
self.write_info("problems closing connection.")
break
#after this the program continues normally, but my conn thread stops
</code></pre>
| 4
|
2009-03-26T10:36:01Z
| 686,045
|
<p>Firstly, don't subclass <code>threading.Thread</code>, use <code>Thread(target=callable).start()</code>.</p>
<p>Secondly, and probably the cause of your apparent block is that <code>gtk.main_iteration</code> takes a parameter <code>block</code>, which defaults to <code>True</code>, so your call to <code>gtk.main_iteration</code> will actually block when there are no events to iterate on. Which can be solved with:</p>
<pre><code>gtk.main_iteration(block=False)
</code></pre>
<p>However, there is no real explanation why you would use this hacked up loop rather than the actual gtk main loop. If you are already running this inside a main loop, then I would suggest that you are doing the wrong thing. I can expand on your options if you give us a bit more detail and/or the complete example.</p>
<p>Thirdly, and this only came up later: Always always <em>always</em> <strong><em>always</em></strong> make sure you have called <code>gtk.gdk.threads_init</code> in any pygtk application with threads. GTK+ has different code paths when running threaded, and it needs to know to use these.</p>
<p>I wrote <a href="http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html">a small article about pygtk and threads</a> that offers you a small abstraction so you never have to worry about these things. That post also includes a progress bar example.</p>
| 8
|
2009-03-26T14:31:59Z
|
[
"python",
"multithreading",
"pygtk"
] |
Hierarchy / Flyweight / Instancing Problem in Python
| 685,253
|
<p>Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so:</p>
<pre><code>1.A
1.B
1.C
2.A
3.D
4.B
5.F
</code></pre>
<p>(This is hard to illustrate - each number is the parent, each letter is the child).</p>
<ol>
<li><p>Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once.</p></li>
<li><p>The hierarchy needs to be easy to navigate.</p></li>
<li><p>Children in the hierarchy need to have just one parent.</p></li>
<li><p>Modifying the contents of the letter objects should be possible directly from the objects in the hierarchy.</p></li>
<li><p>There needs to be a central store containing all of the 'letter' objects (and only those in the hierarchy).</p></li>
<li><p>'letter' and 'number' objects need to be possible to create from a constructor (such as Letter(**kwargs) ).</p></li>
<li><p>It is perfectably acceptable to expect that when a letter changes from the hierarchy, all other letters will respect the same change.</p></li>
</ol>
<p>Hope this isn't too abstract to illustrate the problem.</p>
<p>What would be the best way of solving this? (Then I'll post my solution)</p>
<p>Here's an example script:</p>
<pre><code>one = Number('one')
a = Letter('a')
one.addChild(a)
two = Number('two')
a = Letter('a')
two.addChild(a)
for child in one:
child.method1()
for child in two:
print '%s' % child.method2()
</code></pre>
| 0
|
2009-03-26T10:45:11Z
| 685,387
|
<p>A basic approach will use builtin data types. If I get your drift, the <code>Letter</code> object should be created by a factory with a <code>dict</code> cache to keep previously generated <code>Letter</code> objects. The factory will create only one <code>Letter</code> object for each key.</p>
<p>A <code>Number</code> object can be a sub-class of <code>list</code> that will hold the <code>Letter</code> objects, so that <code>append()</code> can be used to add a child. A <code>list</code> is easy to navigate.</p>
<p>A crude outline of a caching factory:</p>
<pre><code>>>> class Letters(object):
... def __init__(self):
... self.cache = {}
... def create(self, v):
... l = self.cache.get(v, None)
... if l:
... return l
... l = self.cache[v] = Letter(v)
... return l
>>> factory=Letters()
>>> factory.cache
{}
>>> factory.create('a')
<__main__.Letter object at 0x00EF2950>
>>> factory.create('a')
<__main__.Letter object at 0x00EF2950>
>>>
</code></pre>
<p>To fulfill requirement 6 (constructor), here is
a more contrived example, using <code>__new__</code>, of a caching constructor. This is similar to <a href="http://code.activestate.com/recipes/413717/" rel="nofollow">Recipe 413717: Caching object creation </a>.</p>
<pre><code>class Letter(object):
cache = {}
def __new__(cls, v):
o = cls.cache.get(v, None)
if o:
return o
else:
o = cls.cache[v] = object.__new__(cls)
return o
def __init__(self, v):
self.v = v
self.refcount = 0
def addAsChild(self, chain):
if self.refcount > 0:
return False
self.refcount += 1
chain.append(self)
return True
</code></pre>
<p>Testing the cache functionality</p>
<pre><code>>>> l1 = Letter('a')
>>> l2 = Letter('a')
>>> l1 is l2
True
>>>
</code></pre>
<p>For enforcing a single parent, you'll need a method on <code>Letter</code> objects (not <code>Number</code>) - with a reference counter. When called to perform the addition it will refuse addition if the counter is greater than zero.</p>
<pre><code>l1.addAsChild(num4)
</code></pre>
| 0
|
2009-03-26T11:34:52Z
|
[
"python",
"design",
"design-patterns"
] |
Hierarchy / Flyweight / Instancing Problem in Python
| 685,253
|
<p>Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so:</p>
<pre><code>1.A
1.B
1.C
2.A
3.D
4.B
5.F
</code></pre>
<p>(This is hard to illustrate - each number is the parent, each letter is the child).</p>
<ol>
<li><p>Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once.</p></li>
<li><p>The hierarchy needs to be easy to navigate.</p></li>
<li><p>Children in the hierarchy need to have just one parent.</p></li>
<li><p>Modifying the contents of the letter objects should be possible directly from the objects in the hierarchy.</p></li>
<li><p>There needs to be a central store containing all of the 'letter' objects (and only those in the hierarchy).</p></li>
<li><p>'letter' and 'number' objects need to be possible to create from a constructor (such as Letter(**kwargs) ).</p></li>
<li><p>It is perfectably acceptable to expect that when a letter changes from the hierarchy, all other letters will respect the same change.</p></li>
</ol>
<p>Hope this isn't too abstract to illustrate the problem.</p>
<p>What would be the best way of solving this? (Then I'll post my solution)</p>
<p>Here's an example script:</p>
<pre><code>one = Number('one')
a = Letter('a')
one.addChild(a)
two = Number('two')
a = Letter('a')
two.addChild(a)
for child in one:
child.method1()
for child in two:
print '%s' % child.method2()
</code></pre>
| 0
|
2009-03-26T10:45:11Z
| 687,024
|
<blockquote>
<p>Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once.</p>
</blockquote>
<p>This is where I'd begin. It seems like it would be easy to get out of the way and would give you a lot more freedom to implement the last 6.</p>
<p>Perhaps you could consider a solution like <a href="http://gijsbert.org/cmemcache/" rel="nofollow">memcached</a>?</p>
| 0
|
2009-03-26T18:32:27Z
|
[
"python",
"design",
"design-patterns"
] |
Hierarchy / Flyweight / Instancing Problem in Python
| 685,253
|
<p>Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so:</p>
<pre><code>1.A
1.B
1.C
2.A
3.D
4.B
5.F
</code></pre>
<p>(This is hard to illustrate - each number is the parent, each letter is the child).</p>
<ol>
<li><p>Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once.</p></li>
<li><p>The hierarchy needs to be easy to navigate.</p></li>
<li><p>Children in the hierarchy need to have just one parent.</p></li>
<li><p>Modifying the contents of the letter objects should be possible directly from the objects in the hierarchy.</p></li>
<li><p>There needs to be a central store containing all of the 'letter' objects (and only those in the hierarchy).</p></li>
<li><p>'letter' and 'number' objects need to be possible to create from a constructor (such as Letter(**kwargs) ).</p></li>
<li><p>It is perfectably acceptable to expect that when a letter changes from the hierarchy, all other letters will respect the same change.</p></li>
</ol>
<p>Hope this isn't too abstract to illustrate the problem.</p>
<p>What would be the best way of solving this? (Then I'll post my solution)</p>
<p>Here's an example script:</p>
<pre><code>one = Number('one')
a = Letter('a')
one.addChild(a)
two = Number('two')
a = Letter('a')
two.addChild(a)
for child in one:
child.method1()
for child in two:
print '%s' % child.method2()
</code></pre>
| 0
|
2009-03-26T10:45:11Z
| 1,615,837
|
<p>I wonder if you have made this problem too abstract for people to give useful answers. It seems to me that you might be doing something with genetic codes, and if that is the case, you should look into <a href="http://biopython.org/wiki/Main%5FPage" rel="nofollow">BioPython</a>. Not only does it come with libraries for manipulating genetic sequences and accessing gene data repositories, but there is also a community of biology people using it who can advise on concrete best practices, knowing the data that is used and the manipulations that people want to do.</p>
| 0
|
2009-10-23T20:54:26Z
|
[
"python",
"design",
"design-patterns"
] |
querying through wmi & win32.client objects with python
| 685,351
|
<p>Could someone shed some lights upon querying through wmi and win32.client objects? </p>
<p>Anytime i try to query throught win32.client object i get this error: </p>
<blockquote>
<p><em>Error: '' object has no attribute 'UserName'</em></p>
</blockquote>
<p>though, i know (wmic class "Win32_ComputerSystem", wmiexplorer etc.) the certain attribute belongs to the object i'm trying to query on:</p>
<pre><code>import win32com.client
...
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root/cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ComputerSystem")
for objItem in colItems:{
print objItem.UserName #Error: '' object has no attribute 'UserName'
}
...
</code></pre>
<p>And when i run query on wmi object - everything is just fine: </p>
<pre><code>import wmi
...
c = wmi.WMI()
for objItem in c.query(colItems):{
print objItem.UserName # this works now
}
...
</code></pre>
<p>What is causing this "no attribute" error? Could this be my OS issue? Running winXP pro, version 2002, sp2. Or is this because of python 2.4 version i am working on?</p>
| 2
|
2009-03-26T11:18:44Z
| 685,639
|
<p>Why are you doing this?</p>
<pre><code>for objItem in colItems:{
print objItem.UserName #Error: '' object has no attribute 'UserName'
}
</code></pre>
<p>What causes you to think that the resulting columns will be attributes of the resulting object? </p>
<p>Try this to debug the problem.</p>
<pre><code>for objItem in colItems:{
print dir(objItem)
}
</code></pre>
<p>What actual attributes does it have? Perhaps the columns are identified by number? Perhaps you should be doing <code>objItem[0]</code>?</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p><strong>what caused the change of attributes in class "Win32_ComputerSystem"??</strong></p>
<p>Nothing. Attributes don't change. The class is not what you think it should be.</p>
<p>Here's another debugging aid.</p>
<pre><code>colItems = objSWbemServices.ExecQuery("Select * from Win32_ComputerSystem")
print type(colItems)
print dir(colItems)
</code></pre>
| 0
|
2009-03-26T12:52:24Z
|
[
"python",
"winapi"
] |
querying through wmi & win32.client objects with python
| 685,351
|
<p>Could someone shed some lights upon querying through wmi and win32.client objects? </p>
<p>Anytime i try to query throught win32.client object i get this error: </p>
<blockquote>
<p><em>Error: '' object has no attribute 'UserName'</em></p>
</blockquote>
<p>though, i know (wmic class "Win32_ComputerSystem", wmiexplorer etc.) the certain attribute belongs to the object i'm trying to query on:</p>
<pre><code>import win32com.client
...
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root/cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ComputerSystem")
for objItem in colItems:{
print objItem.UserName #Error: '' object has no attribute 'UserName'
}
...
</code></pre>
<p>And when i run query on wmi object - everything is just fine: </p>
<pre><code>import wmi
...
c = wmi.WMI()
for objItem in c.query(colItems):{
print objItem.UserName # this works now
}
...
</code></pre>
<p>What is causing this "no attribute" error? Could this be my OS issue? Running winXP pro, version 2002, sp2. Or is this because of python 2.4 version i am working on?</p>
| 2
|
2009-03-26T11:18:44Z
| 696,368
|
<p>Okay guys, here is another piece of code (from <a href="http://win32com.goermezer.de/content/view/211/189/" rel="nofollow">http://win32com.goermezer.de/content/view/211/189/</a>):</p>
<pre><code>import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Environment")
for objItem in colItems:{
print "Caption: ", objItem.Caption
print "Description: ", objItem.Description
print "Install Date: ", objItem.InstallDate
print "Name: ", objItem.Name
print "Status: ", objItem.Status
print "System Variable: ", objItem.SystemVariable
print "User Name: ", objItem.UserName
print "Variable Value: ", objItem.VariableValue
}
</code></pre>
<p>And again the same error is being displayed:</p>
<pre><code>Caption: Error: '' object has no attribute 'Caption'
</code></pre>
<p>What is happening? How come class is different from the specified one in ExecQuery? I mean, if one says "Select * from Win32_ComputerSystem", how can it query different class than Win32_ComputerSystem?</p>
<p>By the way, I am running python 2.4 code through spyce 2.0.3 server. </p>
<p>p.s. I found that brackets {} is one way to get python code block interpreted right - otherwise "expected an indented block" error is thrown</p>
| 0
|
2009-03-30T08:10:49Z
|
[
"python",
"winapi"
] |
querying through wmi & win32.client objects with python
| 685,351
|
<p>Could someone shed some lights upon querying through wmi and win32.client objects? </p>
<p>Anytime i try to query throught win32.client object i get this error: </p>
<blockquote>
<p><em>Error: '' object has no attribute 'UserName'</em></p>
</blockquote>
<p>though, i know (wmic class "Win32_ComputerSystem", wmiexplorer etc.) the certain attribute belongs to the object i'm trying to query on:</p>
<pre><code>import win32com.client
...
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root/cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ComputerSystem")
for objItem in colItems:{
print objItem.UserName #Error: '' object has no attribute 'UserName'
}
...
</code></pre>
<p>And when i run query on wmi object - everything is just fine: </p>
<pre><code>import wmi
...
c = wmi.WMI()
for objItem in c.query(colItems):{
print objItem.UserName # this works now
}
...
</code></pre>
<p>What is causing this "no attribute" error? Could this be my OS issue? Running winXP pro, version 2002, sp2. Or is this because of python 2.4 version i am working on?</p>
| 2
|
2009-03-26T11:18:44Z
| 3,954,429
|
<p>To find out about the "keys" and "values" in WMI query result, you can use "Properties_"</p>
<pre><code>from win32com.client import Dispatch, GetObject import win32con
server = Dispatch("WbemScripting.SWbemLocator")
c = server.ConnectServer("localhost", "root\\cimv2")
p = c.ExecQuery("Select * from Win32_OperatingSystem")
for i in w.p[0].Properties_:
print i.Name, " = ", i.Value
</code></pre>
| 2
|
2010-10-17T17:41:19Z
|
[
"python",
"winapi"
] |
querying through wmi & win32.client objects with python
| 685,351
|
<p>Could someone shed some lights upon querying through wmi and win32.client objects? </p>
<p>Anytime i try to query throught win32.client object i get this error: </p>
<blockquote>
<p><em>Error: '' object has no attribute 'UserName'</em></p>
</blockquote>
<p>though, i know (wmic class "Win32_ComputerSystem", wmiexplorer etc.) the certain attribute belongs to the object i'm trying to query on:</p>
<pre><code>import win32com.client
...
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root/cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ComputerSystem")
for objItem in colItems:{
print objItem.UserName #Error: '' object has no attribute 'UserName'
}
...
</code></pre>
<p>And when i run query on wmi object - everything is just fine: </p>
<pre><code>import wmi
...
c = wmi.WMI()
for objItem in c.query(colItems):{
print objItem.UserName # this works now
}
...
</code></pre>
<p>What is causing this "no attribute" error? Could this be my OS issue? Running winXP pro, version 2002, sp2. Or is this because of python 2.4 version i am working on?</p>
| 2
|
2009-03-26T11:18:44Z
| 5,159,813
|
<p>try to access properties of colItems this way:</p>
<pre>
for objItem in colItems[o].Properties_:
print objItem.Name, objItem.Value
</pre>
<p>in other circumstances you may prefer to use </p>
<pre>
repr(objItem.Value)
</pre>
<p>and</p>
<pre>
repr(objItem.Value)
</pre>
| 1
|
2011-03-01T20:15:58Z
|
[
"python",
"winapi"
] |
PyUnit: stop after first failing test?
| 685,424
|
<p>I'm using the following code in my testing framework:</p>
<pre><code>testModules = ["test_foo", "test_bar"]
suite = unittest.TestLoader().loadTestsFromNames(testModules)
runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
results = runner.run(suite)
return results.wasSuccessful()
</code></pre>
<p>Is there a way to make the reporting (<code>runner.run</code>?) abort after the first failure to prevent excessive verbosity?</p>
| 6
|
2009-03-26T11:48:21Z
| 685,503
|
<p>It's a feature. If you want to override this, you'll need to subclass <code>TestCase</code> and/or <code>TestSuite</code> classes and override logic in the <code>run()</code> method.</p>
<p>P.S.:
I think you have to subclass <code>unittest.TestCase</code> and override method <code>run()</code> in your class:</p>
<pre><code>def run(self, result=None):
if result is None: result = self.defaultTestResult()
result.startTest(self)
testMethod = getattr(self, self._testMethodName)
try:
try:
self.setUp()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
return
ok = False
try:
testMethod()
ok = True
except self.failureException:
result.addFailure(self, self._exc_info())
result.stop()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
result.stop()
try:
self.tearDown()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
ok = False
if ok: result.addSuccess(self)
finally:
result.stopTest(self)
</code></pre>
<p>(I've added two <code>result.stop()</code> calls to the default <code>run</code> definition).</p>
<p>Then you'll have to modify all your testcases to make them subclasses of this new class, instead of <code>unittest.TestCase</code>.</p>
<p><strong><em>WARNING</em></strong>: I didn't test this code. :)</p>
| 5
|
2009-03-26T12:12:55Z
|
[
"python",
"unit-testing"
] |
PyUnit: stop after first failing test?
| 685,424
|
<p>I'm using the following code in my testing framework:</p>
<pre><code>testModules = ["test_foo", "test_bar"]
suite = unittest.TestLoader().loadTestsFromNames(testModules)
runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
results = runner.run(suite)
return results.wasSuccessful()
</code></pre>
<p>Is there a way to make the reporting (<code>runner.run</code>?) abort after the first failure to prevent excessive verbosity?</p>
| 6
|
2009-03-26T11:48:21Z
| 690,286
|
<p>Based on Eugene's guidance, I've come up with the following:</p>
<pre><code>class TestCase(unittest.TestCase):
def run(self, result=None):
if result.failures or result.errors:
print "aborted"
else:
super(TestCase, self).run(result)
</code></pre>
<p>While this works fairly well, it's a bit annoying that each individual test module has to define whether it wants to use this custom class or the default one (a command-line switch, similar to <code>py.test</code>'s <code>--exitfirst</code>, would be ideal)...</p>
| 5
|
2009-03-27T15:44:25Z
|
[
"python",
"unit-testing"
] |
PyUnit: stop after first failing test?
| 685,424
|
<p>I'm using the following code in my testing framework:</p>
<pre><code>testModules = ["test_foo", "test_bar"]
suite = unittest.TestLoader().loadTestsFromNames(testModules)
runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
results = runner.run(suite)
return results.wasSuccessful()
</code></pre>
<p>Is there a way to make the reporting (<code>runner.run</code>?) abort after the first failure to prevent excessive verbosity?</p>
| 6
|
2009-03-26T11:48:21Z
| 11,466,102
|
<p>Building on AnC's answer, this is what I'm using...</p>
<pre><code>def aborting_run(self, result=None):
if result.failures or result.errors:
print "aborted"
else:
original_run(self, result)
original_run = unittest.TestCase.run
unittest.TestCase.run = aborting_run
</code></pre>
| 0
|
2012-07-13T07:36:25Z
|
[
"python",
"unit-testing"
] |
Handling file attributes in python 3.0
| 685,488
|
<p>I am currently developing an application in python 3 and i need to be able to hide certain files from the view of people. i found a few places that used the win32api and win32con but they don't seem to exist in python 3.</p>
<p>Does anyone know if this is possible without rolling back or writing my own attribute library in C++</p>
| 1
|
2009-03-26T12:09:36Z
| 685,548
|
<p>You can use <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> to directly access functions from kernel32.dll. </p>
<p>The function you're looking for is <code>windll.kernel32.SetFileAttributesA</code></p>
| 3
|
2009-03-26T12:28:01Z
|
[
"python",
"windows",
"python-3.x"
] |
Handling file attributes in python 3.0
| 685,488
|
<p>I am currently developing an application in python 3 and i need to be able to hide certain files from the view of people. i found a few places that used the win32api and win32con but they don't seem to exist in python 3.</p>
<p>Does anyone know if this is possible without rolling back or writing my own attribute library in C++</p>
| 1
|
2009-03-26T12:09:36Z
| 685,599
|
<p>You need the <a href="http://sourceforge.net/project/showfiles.php?group%5Fid=78018&package%5Fid=79063&release%5Fid=661475">pywin32</a> Python Extensions for Windows. Recently released for Python 3.</p>
| 5
|
2009-03-26T12:40:05Z
|
[
"python",
"windows",
"python-3.x"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 685,546
|
<p>The usual tool for converting Microsoft Office documents to HTML or other formats was mswordview, which has since been renamed to <a href="http://wvware.sourceforge.net/" rel="nofollow">vwWare</a>.</p>
<p>If you're looking for a command-line tool, they actually recommend using AbiWord to perform the conversion:</p>
<pre><code>AbiWord --to=txt
</code></pre>
<p>If you're looking for a library, start on the <a href="http://wvware.sourceforge.net/wvWare.html" rel="nofollow">wvWare overview page</a>. They also maintain <a href="http://wvware.sourceforge.net/wvInfo.html" rel="nofollow">a list of libraries and tools which read MS Office documents</a>.</p>
| 5
|
2009-03-26T12:27:42Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 685,558
|
<p>For dealing with Excel Spreadsheets <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> is good. But it won't help with <code>.doc</code> and <code>.ppt</code> files.</p>
<p>(You may have also heard of PyExcelerator. xlwt is a fork of this and better maintained so I think you'd be better of with xlwt.)</p>
| 1
|
2009-03-26T12:31:10Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 685,562
|
<p>You can access <a href="http://wiki.services.openoffice.org/wiki/Python" rel="nofollow">OpenOffice via Python API</a>.</p>
<p>Try using this as a base: <a href="http://wiki.services.openoffice.org/wiki/Odt2txt.py" rel="nofollow">http://wiki.services.openoffice.org/wiki/Odt2txt.py</a></p>
| 9
|
2009-03-26T12:32:11Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 685,583
|
<p>At the command line, <a href="http://www.winfield.demon.nl/" rel="nofollow">antiword</a> or <a href="http://wvware.sourceforge.net/" rel="nofollow">wv</a> work very nicely for .doc files. (Not a Python solution, but they're easy to install and fast.)</p>
| 1
|
2009-03-26T12:36:45Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 685,656
|
<p>I've had some success at using XSLT to process the XML-based office files into something usable in the past. It's not necessarily a python-based solution, but it does get the job done.</p>
| 0
|
2009-03-26T12:56:01Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 687,876
|
<p>I'd go for the command line-solution (and then use the <a href="http://docs.python.org/library/subprocess.html">Python subprocess module</a> to run the tools from Python).</p>
<p>Convertors for msword (<strong>catdoc</strong>), excel (<strong>xls2csv</strong>) and ppt (<strong>catppt</strong>) can be found (in source form) here: <a href="http://vitus.wagner.pp.ru/software/catdoc/">http://vitus.wagner.pp.ru/software/catdoc/</a>.</p>
<p>Can't really comment on the usefullness of catppt but catdoc and xls2csv work great!</p>
<p>But be sure to first search your distributions repositories... On ubuntu for example catdoc is just one fast apt-get away.</p>
| 8
|
2009-03-26T22:57:39Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 4,229,904
|
<p>Interestingly enough, it looks like if you use OpenOffice to create a .ppt file, (saving it as Microsoft PowerPoint 97/2000/XP), then catppt will fail to extract the words from it. </p>
| 0
|
2010-11-19T22:21:31Z
|
[
"python",
"linux",
"ms-office"
] |
python convert microsoft office docs to plain text on linux
| 685,533
|
<p>Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.</p>
| 11
|
2009-03-26T12:24:44Z
| 9,243,843
|
<p>Same problem here. Below is my simple script to convert all doc files in dir 'docs/' to dir 'txts/' using catdoc. Hope it will help someone:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob, re, os
f = glob.glob('docs/*.doc') + glob.glob('docs/*.DOC')
outDir = 'txts'
if not os.path.exists(outDir):
os.makedirs(outDir)
for i in f:
os.system("catdoc -w '%s' > '%s'" %
(i, outDir + '/' + re.sub(r'.*/([^.]+)\.doc', r'\1.txt', i,
flags=re.IGNORECASE)))
</code></pre>
| 1
|
2012-02-11T20:36:52Z
|
[
"python",
"linux",
"ms-office"
] |
Problem using Python comtypes library to add a querytable to Excel
| 685,589
|
<p>I'm trying to create a QueryTable in an excel spreadsheet using the Python comtypes library, but getting a rather uninformative error...</p>
<p>In vba (in a module within the workbook), the following code works fine:</p>
<pre><code>Sub CreateQuery()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Dim qt As QueryTable
Set ws = ActiveWorkbook.Sheets(1)
Set con = New ADODB.Connection
con.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\to\Db.mdb;")
Set rs = New ADODB.Recordset
rs.Open "Select * from [tbl Base Data];", con
Set qt = ws.QueryTables.Add(rs, ws.Range("A1"))
qt.Refresh
End Sub
</code></pre>
<p>But the following Python code:</p>
<pre><code>import sys
import comtypes.client as client
def create_querytable():
constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Path\\to\\Db.mdb"
conn = client.CreateObject("ADODB.Connection", dynamic = True)
rs = client.CreateObject("ADODB.Recordset", dynamic = True)
SQL = "Select * from [tbl Base Data];"
conn.Open(constring)
rs.Open(SQL, conn)
excel = client.CreateObject("Excel.Application", dynamic = True)
excel.Visible = True
ws = excel.Workbooks.Add().Sheets(1)
qt = ws.QueryTables.Add(rs, ws.Range["A1"])
qt.Refresh()
rs.Close()
conn.Close()
</code></pre>
<p>Throws the unhelpful error message:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
create_querytable()
File "C:/Documents and Settings/cvmne250/Desktop/temp.py", line 17, in create_querytable
qt = ws.QueryTables.Add(rs, ws.Range["A1"])
File "G:\ISA\SPSS\comtypes\lib\comtypes\client\lazybind.py", line 160, in caller
File "G:\ISA\SPSS\comtypes\lib\comtypes\automation.py", line 628, in _invoke
COMError: (-2147352567, 'Exception occurred.', (None, None, None, 0, None))
</code></pre>
<p>Any ideas on what's happening here?</p>
<p>Thanks!</p>
| 5
|
2009-03-26T12:37:53Z
| 685,690
|
<p>It looks like your error is on this line:</p>
<pre><code>qt = ws.QueryTables.Add(rs, ws.Range["A1"])
</code></pre>
<p>I think your problem is that you are using python syntax to look up a value in a VBA Collection. Try changing your square brackets to parentheses.</p>
<p>i.e.</p>
<pre><code>qt = ws.QueryTables.Add(rs, ws.Range("A1"))
</code></pre>
<p>The reason being that in VBA when you invoke a Collection like this, <code>Range("A1")</code>, you are actually calling it's default method, <code>Range.Item("A1")</code>. Basically, VBA Collections do not translate to python dictionaries.</p>
<p>I'm getting this from this <a href="http://mail.python.org/pipermail/python-list/2001-December/116793.html" rel="nofollow">forum thread</a>, and my experience with VBA.</p>
<p><hr /></p>
<p>Edit due to comment:</p>
<blockquote>
<p>Unfortunately, I've tried both: as
noted in your link, they sometimes
don't do the same thing, but my gut
feeling here is that the '[' is more
likely to be what I want. â mavnn</p>
</blockquote>
<p>Do you know if <code>comtypes.client.CreateObject</code> works the same as <code>win32com.client.Dispatch</code>? You might try creating your com object with the win32com package and see if that makes a difference.</p>
| 1
|
2009-03-26T13:05:30Z
|
[
"python",
"excel",
"vba",
"com",
"comtypes"
] |
Problem using Python comtypes library to add a querytable to Excel
| 685,589
|
<p>I'm trying to create a QueryTable in an excel spreadsheet using the Python comtypes library, but getting a rather uninformative error...</p>
<p>In vba (in a module within the workbook), the following code works fine:</p>
<pre><code>Sub CreateQuery()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ws As Worksheet
Dim qt As QueryTable
Set ws = ActiveWorkbook.Sheets(1)
Set con = New ADODB.Connection
con.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\to\Db.mdb;")
Set rs = New ADODB.Recordset
rs.Open "Select * from [tbl Base Data];", con
Set qt = ws.QueryTables.Add(rs, ws.Range("A1"))
qt.Refresh
End Sub
</code></pre>
<p>But the following Python code:</p>
<pre><code>import sys
import comtypes.client as client
def create_querytable():
constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Path\\to\\Db.mdb"
conn = client.CreateObject("ADODB.Connection", dynamic = True)
rs = client.CreateObject("ADODB.Recordset", dynamic = True)
SQL = "Select * from [tbl Base Data];"
conn.Open(constring)
rs.Open(SQL, conn)
excel = client.CreateObject("Excel.Application", dynamic = True)
excel.Visible = True
ws = excel.Workbooks.Add().Sheets(1)
qt = ws.QueryTables.Add(rs, ws.Range["A1"])
qt.Refresh()
rs.Close()
conn.Close()
</code></pre>
<p>Throws the unhelpful error message:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
create_querytable()
File "C:/Documents and Settings/cvmne250/Desktop/temp.py", line 17, in create_querytable
qt = ws.QueryTables.Add(rs, ws.Range["A1"])
File "G:\ISA\SPSS\comtypes\lib\comtypes\client\lazybind.py", line 160, in caller
File "G:\ISA\SPSS\comtypes\lib\comtypes\automation.py", line 628, in _invoke
COMError: (-2147352567, 'Exception occurred.', (None, None, None, 0, None))
</code></pre>
<p>Any ideas on what's happening here?</p>
<p>Thanks!</p>
| 5
|
2009-03-26T12:37:53Z
| 686,763
|
<p>I simplified your code and this should work fine (I'll explain the changes below):</p>
<pre><code>def create_querytable2():
constring = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\path\to\db.mdb;"
SQL = "Select * from tblName;"
excel = client.CreateObject("Excel.Application", dynamic=True)
excel.Visible = True
ws = excel.Workbooks.Add().Worksheets(1)
ws.QueryTables.Add(constring, ws.Range["A1"], SQL).Refresh()
</code></pre>
<p>The QueryTables.Add() function can create the Connection and Recordset objects for you, so that simplifies a lot of things... you just need to add what type of connection it is in the conneciton string (the "OLEDB" part).</p>
<p>Letting Excel do most of the work seems to solve your problem :)</p>
| 2
|
2009-03-26T17:23:07Z
|
[
"python",
"excel",
"vba",
"com",
"comtypes"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 685,694
|
<p>This code should work:</p>
<pre><code>duplicates = set()
found = set()
for item in source:
if item in found:
duplicates.add(item)
else:
found.add(item)
</code></pre>
| 19
|
2009-03-26T13:06:04Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 685,705
|
<p>This will create the list in one line:</p>
<pre><code>L = [1, 2, 3, 3, 4, 4, 4]
L_dup = set([i for i in L if L.count(i) > 1])
</code></pre>
| 4
|
2009-03-26T13:08:43Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 685,710
|
<p>Definitely not the fastest way to do that, but it seem to work solve the problem:</p>
<pre><code>>>> lst = [23, 32, 23, None]
>>> set(i for i in lst if lst.count(i) > 1)
{23}
</code></pre>
| 3
|
2009-03-26T13:09:41Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 685,719
|
<p><code>groupby</code> from <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools</a> will probably be useful here:</p>
<pre><code>
from itertools import groupby
duplicated=[k for (k,g) in groupby(sorted(l)) if len(list(g)) > 1]
</code></pre>
<p>Basically you use it to find elements that appear more than once...</p>
<p>NB. the call to <code>sorted</code> is needed, as <code>groupby</code> only works properly if the input is sorted.</p>
| 6
|
2009-03-26T13:12:03Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 685,724
|
<p>If you don't care about the order of the duplicates:</p>
<pre><code>a = [1, 2, 3, 4, 5, 4, 6, 4, 7, 8, 8]
b = sorted(a)
duplicates = set([x for x, y in zip(b[:-1], b[1:]) if x == y])
</code></pre>
| 1
|
2009-03-26T13:13:36Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 685,794
|
<p>EDIT : Ok, doesn't work since you want duplicates only.</p>
<h2>Whith python > 2.4 :</h2>
<p>You have set, just do :</p>
<pre><code>my_filtered_list = list(set(mylist))
</code></pre>
<p>Set is a data structure that doesn't have duplicate by nature.</p>
<h2>With older Python versions :</h2>
<pre><code>my_filtered_list = list(dict.fromkeys(mylist).keys())
</code></pre>
<p>Dictionary map a unique key to a value. We use the "unique" caracteristc to get rid of the duplicate.</p>
| -1
|
2009-03-26T13:29:55Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 687,905
|
<p>Personally, I think this is the simplest way to do it with performance O(n). Similar to vartec's solution but no <code>import</code> required and no Python version dependencies to worry about:</p>
<pre><code>def getDuplicates(iterable):
d = {}
for i in iterable:
d[i] = d.get(i, 0) + 1
return [i for i in d if d[i] > 1]
</code></pre>
| 0
|
2009-03-26T23:10:18Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 970,635
|
<p>the solutions based on 'set' have a small drawback, namely they only work for hashable objects.</p>
<p>the solution based on itertools.groupby on the other hand works for all comparable objects (e.g.: dictionaries and lists).</p>
| 0
|
2009-06-09T15:06:01Z
|
[
"python"
] |
In Python, how do I take a list and reduce it to a list of duplicates?
| 685,671
|
<p>I have a list of strings that should be unique. I want to be able to check for duplicates quickly. Specifically, I'd like to be able to take the original list and produce a new list containing any repeated items. I don't care how many times the items are repeated so it doesn't have to have a word twice if there are two duplicates.</p>
<p>Unfortunately, I can't think of a way to do this that wouldn't be clunky. Any suggestions?</p>
<p>EDIT:
Thanks for the answers and I thought I'd make a clarification. I'm not concerned with having a list of uniques for it's own sake. I'm generating the list based off of text files and I want to know what the duplicates are so I can go in the text files and remove them if any show up.</p>
| 0
|
2009-03-26T13:01:52Z
| 5,751,556
|
<p>Here's a simple 1-liner:</p>
<pre><code>>>> l = ['a', 'a', 3, 'r', 'r', 's', 's', 2, 3, 't', 'y', 'a', 'w', 'r']
>>> [v for i, v in enumerate(l) if l[i:].count(v) > 1 and l[:i].count(v) == 0]
['a', 3, 'r', 's']
</code></pre>
<p><code>enumerate</code> returns an indexed list which we use to splice our input list determining whether there are any duplicates ahead of our current index in the loop and whether we have already found a duplicate behind.</p>
| 2
|
2011-04-22T01:49:19Z
|
[
"python"
] |
Is there any particular reason why this syntax is used for instantiating a class?
| 685,713
|
<p>I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class?</p>
<p>Python:</p>
<pre><code>class MyClass:
def __init__(self):
x = MyClass()
</code></pre>
<p>Ruby:</p>
<pre><code>class AnotherClass
def initialize()
end
end
x = AnotherClass.new()
</code></pre>
<p>I can't understand why the syntax used for the constructor and the syntax used to actually get an instance of the class are so different. Sure, I know it doesn't really make a difference but, for example, in ruby what's wrong with making the constructor "new()"?</p>
| 0
|
2009-03-26T13:10:05Z
| 685,726
|
<p>Actually in Python the constructor is <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fnew%5F%5F" rel="nofollow"><code>__new__()</code></a>, while <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Finit%5F%5F" rel="nofollow"><code>__init__()</code></a> is instance initializer. </p>
<p><code>__new__()</code> is static class method, thus it has to be called first, as a first parameter (usually named <code>cls</code> or <code>klass</code>) it gets the class . It creates object instance, which is then passed to <code>__init__()</code> as first parameter (usually named <code>self</code>), along with all the rest of <code>__new__</code>'s parameters.</p>
| 4
|
2009-03-26T13:13:51Z
|
[
"python",
"ruby",
"constructor"
] |
Is there any particular reason why this syntax is used for instantiating a class?
| 685,713
|
<p>I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class?</p>
<p>Python:</p>
<pre><code>class MyClass:
def __init__(self):
x = MyClass()
</code></pre>
<p>Ruby:</p>
<pre><code>class AnotherClass
def initialize()
end
end
x = AnotherClass.new()
</code></pre>
<p>I can't understand why the syntax used for the constructor and the syntax used to actually get an instance of the class are so different. Sure, I know it doesn't really make a difference but, for example, in ruby what's wrong with making the constructor "new()"?</p>
| 0
|
2009-03-26T13:10:05Z
| 685,751
|
<p>When you are creating an object of a class, you are doing more than just initializing it. You are allocating the memory for it, then initializing it, then returning it.</p>
<p>Note also that in Ruby, <code>new()</code> is a class method, while <code>initialize()</code> is an instance method. If you simply overrode <code>new()</code>, you would have to create the object first, then operate on that object, and return it, rather than the simpler <code>initialize()</code> where you can just refer to <code>self</code>, as the object has already been created for you by the built-in <code>new()</code> (or in Ruby, leave <code>self</code> off as it's implied).</p>
<p>In Objective-C, you can actually see what's going on a little more clearly (but more verbosely) because you need to do the allocation and initialization separately, since Objective-C can't pass argument lists from the allocation method to the initialization one:</p>
<pre><code>[[MyClass alloc] initWithFoo: 1 bar: 2];
</code></pre>
| 5
|
2009-03-26T13:20:56Z
|
[
"python",
"ruby",
"constructor"
] |
Is there any particular reason why this syntax is used for instantiating a class?
| 685,713
|
<p>I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class?</p>
<p>Python:</p>
<pre><code>class MyClass:
def __init__(self):
x = MyClass()
</code></pre>
<p>Ruby:</p>
<pre><code>class AnotherClass
def initialize()
end
end
x = AnotherClass.new()
</code></pre>
<p>I can't understand why the syntax used for the constructor and the syntax used to actually get an instance of the class are so different. Sure, I know it doesn't really make a difference but, for example, in ruby what's wrong with making the constructor "new()"?</p>
| 0
|
2009-03-26T13:10:05Z
| 685,756
|
<p>This is useful because in Python, a constructor is just another function. For example, I've done this several times:</p>
<pre><code>def ClassThatShouldntBeDirectlyInstantiated():
return _classThatShouldntBeDirectlyInstantiated()
class _classThatShouldntBeDirectlyInstantiated(object):
...
</code></pre>
<p>Of course, that's a contrived example, but you get the idea. Essentially, most people that use your class will probably think of ClassThatShouldntBeDirectlyInstantiated as your class, and there's no need to let them think otherwise. Doing things this way, all you have to do is document the factory function as the class it instantiates and not confuse anyone using the class.</p>
<p>In a language like C# or Java, I sometimes find it annoying to make classes like this because it can be difficult to determine whether you should use the constructor or some factory function. I'm not sure if this is also the case in Ruby though.</p>
| 0
|
2009-03-26T13:21:36Z
|
[
"python",
"ruby",
"constructor"
] |
How to compile Python 1.0
| 685,732
|
<p>For some perverse reason, I want to try Python 1.0.. How would I go about compiling it, or rather, what is the earlier version that will compile cleanly with current compilers?</p>
<p>I'm using Mac OS X 10.5, although since it's for nothing more than curiosity (about how the language has changed), compiling in a Linux virtual machine is possible too..</p>
| 1
|
2009-03-26T13:16:07Z
| 685,753
|
<p>Python 1.0.1 compiles perfectly under Ubuntu 8.10 using GCC 4.3.2. It should compile under Leopard, too.</p>
<p>Download the source <a href="http://www.python.org/download/releases/src/python1.0.1.tar.gz">here</a>, and compile the usual way:</p>
<pre><code>./configure
make
</code></pre>
<p><strong>UPDATE:</strong> I tested it, and it compiles under Leopard, too.</p>
| 9
|
2009-03-26T13:21:13Z
|
[
"python",
"installation",
"legacy"
] |
How to compile Python 1.0
| 685,732
|
<p>For some perverse reason, I want to try Python 1.0.. How would I go about compiling it, or rather, what is the earlier version that will compile cleanly with current compilers?</p>
<p>I'm using Mac OS X 10.5, although since it's for nothing more than curiosity (about how the language has changed), compiling in a Linux virtual machine is possible too..</p>
| 1
|
2009-03-26T13:16:07Z
| 688,259
|
<p>Going further backwards in time, I pulled the 0.9.1p1 source from alt.sources via Google Groups' archive. That's 18+ year old code!</p>
<p>I made a few changes (documented in README.reconstructed) to get it to compile on my OS 10.4 box. <a href="http://www.dalkescientific.com/writings/diary/archive/2009/03/27/python%5F0%5F9%5F1p1.html" rel="nofollow">Source available</a> for your enjoyment. I've also sent email to python.org maintainers to see if they want a copy of it.</p>
<p>It doesn't compile cleanly. There are some warnings, mostly to do lack of prototypes. But it does work.</p>
| 4
|
2009-03-27T02:00:58Z
|
[
"python",
"installation",
"legacy"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 685,802
|
<p>If you have a for loop you don't really have any condition statement. So break is your choice if you like to abort and then else can serve perfectly to handle the case where you were not happy.</p>
<pre><code>for fruit in basket:
if fruit.kind in ['Orange', 'Apple']:
fruit.eat()
break
else:
print 'The basket contains no desirable fruit'
</code></pre>
| 6
|
2009-03-26T13:32:16Z
|
[
"for-loop",
"python"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 685,820
|
<p>Without using <code>break</code>, <code>else</code> blocks have no benefit for <code>for</code> and <code>while</code> statements. The following two examples are equivalent:</p>
<pre><code>for x in range(10):
pass
else:
print "else"
for x in range(10):
pass
print "else"
</code></pre>
<p>The only reason for using <code>else</code> with <code>for</code> or <code>while</code> is to do something after the loop if it terminated normally, meaning without an explicit <code>break</code>.</p>
<p>After a lot of thinking, I can finally come up with a case where this might be useful:</p>
<pre><code>def commit_changes(directory):
for file in directory:
if file_is_modified(file):
break
else:
# No changes
return False
# Something has been changed
send_directory_to_server()
return True
</code></pre>
| 3
|
2009-03-26T13:36:16Z
|
[
"for-loop",
"python"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 685,833
|
<p>Here you go:</p>
<pre><code>a = ('y','a','y')
for x in a:
print x,
else:
print '!'
</code></pre>
<p>It's for the caboose.</p>
<p>edit:</p>
<pre><code># What happens if we add the ! to a list?
def side_effect(your_list):
your_list.extend('!')
for x in your_list:
print x,
claimant = ['A',' ','g','u','r','u']
side_effect(claimant)
print claimant[-1]
# oh no, claimant now ends with a '!'
</code></pre>
<p>edit:</p>
<pre><code>a = (("this","is"),("a","contrived","example"),("of","the","caboose","idiom"))
for b in a:
for c in b:
print c,
if "is" == c:
break
else:
print
</code></pre>
| -1
|
2009-03-26T13:39:31Z
|
[
"for-loop",
"python"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 686,145
|
<p>What could be more pythonic than PyPy? </p>
<p>Look at what I discovered starting at line 284 in ctypes_configure/configure.py:</p>
<pre><code> for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
</code></pre>
<p>And here, from line 425 in pypy/annotation/annrpython.py (<a href="http://codespeak.net/pypy/dist/pypy/annotation/annrpython.py">clicky</a>)</p>
<pre><code>if cell.is_constant():
return Constant(cell.const)
else:
for v in known_variables:
if self.bindings[v] is cell:
return v
else:
raise CannotSimplify
</code></pre>
<p>In pypy/annotation/binaryop.py, starting at line 751:</p>
<pre><code>def is_((pbc1, pbc2)):
thistype = pairtype(SomePBC, SomePBC)
s = super(thistype, pair(pbc1, pbc2)).is_()
if not s.is_constant():
if not pbc1.can_be_None or not pbc2.can_be_None:
for desc in pbc1.descriptions:
if desc in pbc2.descriptions:
break
else:
s.const = False # no common desc in the two sets
return s
</code></pre>
<p>A non-one-liner in pypy/annotation/classdef.py, starting at line 176:</p>
<pre><code>def add_source_for_attribute(self, attr, source):
"""Adds information about a constant source for an attribute.
"""
for cdef in self.getmro():
if attr in cdef.attrs:
# the Attribute() exists already for this class (or a parent)
attrdef = cdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
# we should reflow from all the reader's position,
# but as an optimization we try to see if the attribute
# has really been generalized
if attrdef.s_value != s_prev_value:
attrdef.mutated(cdef) # reflow from all read positions
return
else:
# remember the source in self.attr_sources
sources = self.attr_sources.setdefault(attr, [])
sources.append(source)
# register the source in any Attribute found in subclasses,
# to restore invariant (III)
# NB. add_constant_source() may discover new subdefs but the
# right thing will happen to them because self.attr_sources
# was already updated
if not source.instance_level:
for subdef in self.getallsubdefs():
if attr in subdef.attrs:
attrdef = subdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
if attrdef.s_value != s_prev_value:
attrdef.mutated(subdef) # reflow from all read positions
</code></pre>
<p>Later in the same file, starting at line 307, an example with an illuminating comment:</p>
<pre><code>def generalize_attr(self, attr, s_value=None):
# if the attribute exists in a superclass, generalize there,
# as imposed by invariant (I)
for clsdef in self.getmro():
if attr in clsdef.attrs:
clsdef._generalize_attr(attr, s_value)
break
else:
self._generalize_attr(attr, s_value)
</code></pre>
| 15
|
2009-03-26T14:56:44Z
|
[
"for-loop",
"python"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 696,324
|
<p>Perhaps the best answer comes from the official Python tutorial:</p>
<p><a href="http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">break and continue Statements, and else Clauses on Loops</a>:</p>
<blockquote>
<p><em>Loop statements may have an else
clause; it is executed when the loop
terminates through exhaustion of the
list (with for) or when the condition
becomes false (with while), but not
when the loop is terminated by a break
statement</em></p>
</blockquote>
| 2
|
2009-03-30T07:46:48Z
|
[
"for-loop",
"python"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 1,980,927
|
<p>Basically, it simplifies any loop that uses a boolean flag like this:</p>
<pre><code>found = False # <-- initialize boolean
for divisor in range(2, n):
if n % divisor == 0:
found = True # <-- update boolean
break # optional, but continuing would be a waste of time
if found: # <-- check boolean
print n, "is composite"
else:
print n, "is prime"
</code></pre>
<p>and allows you to skip the management of the flag:</p>
<pre><code>for divisor in range(2, n):
if n % divisor == 0:
print n, "is composite"
break
else:
print n, "is prime"
</code></pre>
<p>Note that there is already a natural place for code to execute when you do find a divisor - right before the <code>break</code>. The only new feature here is a place for code to execute when you tried all divisor and did not find any.</p>
<p><em>This helps only in conjuction with <code>break</code></em>. You still need booleans if you can't break (e.g. because you looking for the last match, or have to track several conditions in parallel).</p>
<p>Oh, and BTW, this works for while loops just as well.</p>
<h2>any/all</h2>
<p>Nowdays, if the only purpose of the loop is a yes-or-no answer, you might be able to write it much shorter with the <code>any()</code>/<code>all()</code> functions with a generator or generator expression that yields booleans:</p>
<pre><code>if any(n % divisor == 0
for divisor in range(2, n)):
print n, "is composite"
else:
print n, "is prime"
</code></pre>
<p>Note the elegancy! The code is 1:1 what you want to say!</p>
<p>[This is as effecient as a loop with a <code>break</code>, because the <code>any()</code> function is short-circuiting, only running the generator expression until it yeilds <code>True</code>. In fact it's usually even faster than a loop. Simpler Python code tends to have less overhear.]</p>
<p>This is less workable if you have other side effects - for example if you want to find the divisor. You can still do it (ab)using the fact that non-0 value are true in Python:</p>
<pre><code>divisor = any(d for d in range(2, n) if n % d == 0)
if divisor:
print n, "is divisible by", divisor
else:
print n, "is prime"
</code></pre>
<p>but as you see this is getting shaky - wouldn't work if 0 was a possible divisor value...</p>
| 4
|
2009-12-30T16:03:08Z
|
[
"for-loop",
"python"
] |
Pythonic ways to use 'else' in a for loop
| 685,758
|
<p>I have hardly ever noticed a python program that uses else in a for loop.</p>
<p>I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.</p>
<p>What is the pythonic way to use an else in a for loop? Are there any notable use cases?</p>
<p>And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.</p>
<p>Worth noting that for loop has an else since the language inception, the first ever version.</p>
| 13
|
2009-03-26T13:22:32Z
| 20,862,778
|
<p>I was introduced to a wonderful idiom in which you can use a <code>for</code>/<code>break</code>/<code>else</code> scheme with an iterator to save both time and LOC. The example at hand was searching for the candidate for an incompletely qualified path. If you care to see the original context, please see <a href="http://stackoverflow.com/a/18988504/691859">the original question</a>.</p>
<pre><code>def match(path, actual):
path = path.strip('/').split('/')
actual = iter(actual.strip('/').split('/'))
for pathitem in path:
for item in actual:
if pathitem == item:
break
else:
return False
return True
</code></pre>
<p>What makes the use of <code>for</code>/<code>else</code> so great here is the elegance of avoiding juggling a confusing boolean around. Without <code>else</code>, but hoping to achieve the same amount of short-circuiting, it might be written like so:</p>
<pre><code>def match(path, actual):
path = path.strip('/').split('/')
actual = iter(actual.strip('/').split('/'))
failed = True
for pathitem in path:
failed = True
for item in actual:
if pathitem == item:
failed = False
break
if failed:
break
return not failed
</code></pre>
<p>I think the use of <code>else</code> makes it more elegant and more obvious.</p>
| 0
|
2013-12-31T20:15:58Z
|
[
"for-loop",
"python"
] |
mysqldb on python 2.6+ (win32)
| 685,869
|
<p>I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6?</p>
| 10
|
2009-03-26T13:45:56Z
| 686,631
|
<p>There are versions of mysqldb for python 2.6, they're just not available on the official site. It took me a while (and unfortunately I lost the link) but you can search google and find people who have compiled and released 2.6 versions of mysqldb for windows x64 and x32.</p>
<p>EDIT:</p>
<p><a href="http://sourceforge.net/forum/forum.php?thread_id=3108914&forum_id=70460">http://sourceforge.net/forum/forum.php?thread_id=3108914&forum_id=70460</a></p>
<p><a href="http://sourceforge.net/forum/forum.php?thread_id=2316047&forum_id=70460">http://sourceforge.net/forum/forum.php?thread_id=2316047&forum_id=70460</a></p>
<p>That fourm has a link to versions of mysqldb for Python 2.6</p>
| 11
|
2009-03-26T16:50:17Z
|
[
"python",
"mysql"
] |
mysqldb on python 2.6+ (win32)
| 685,869
|
<p>I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6?</p>
| 10
|
2009-03-26T13:45:56Z
| 1,603,137
|
<p>This one has both 32 and 64 versions for 2.6:<br />
<a href="http://www.codegood.com/archives/4">http://www.codegood.com/archives/4</a></p>
| 7
|
2009-10-21T19:42:56Z
|
[
"python",
"mysql"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.