title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
limit downloaded page size
1,224,910
<p>Is there a way to limit amount of data downloaded by python's urllib2 module ? Sometimes I encounter with broken sites with sort of /dev/random as a page and it turns out that they use up all memory on a server.</p>
3
2009-08-03T22:20:20Z
1,224,950
<p><code>urllib2.urlopen</code> returns a file-like object, and you can (at least in theory) <code>.read(N)</code> from such an object to limit the amount of data returned to N bytes at most.</p> <p>This approach is not entirely fool-proof, because an actively-hostile site may go to quite some lengths to fool a reasonably trusty received, like urllib2's default opener; in this case, you'll need to implement and install your own opener that knows how to guard itself against such attacks (for example, getting no more than a MB at a time from the open socket, etc, etc).</p>
3
2009-08-03T22:34:24Z
[ "python", "urllib2" ]
Query strange behaviour. Google App Engine datastore
1,224,939
<p>I have a model like this:</p> <pre><code>class Group(db.Model): name = db.StringProperty() description = db.TextProperty() </code></pre> <p>Sometimes when executing queries like:</p> <pre><code>groups = Group.all().order("name").fetch(20) </code></pre> <p>or</p> <pre><code>groups = Group.all() </code></pre> <p>I'm getting error massages like this:</p> <pre><code>Traceback (most recent call last): File "/opt/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__ handler.get(*groups) File "/home/al/Desktop/p/mwr-dev/main.py", line 638, in get groups = Group.all() AttributeError: type object 'Group' has no attribute 'all' </code></pre> <p>But when I'm using GQL queries with the same meaning, everything goes fine.</p> <p>Why does that happens? I'm don't getting why GAE thinks that 'all' is attribute?</p> <p><hr /></p> <p>UPDATE: Oops ... I've found out that I also had request handler named the same as model ;(</p>
1
2009-08-03T22:28:24Z
1,224,967
<p><code>all</code> is indeed an attribute (specifically an executable one, a method) but as Group inherits from Model it should have that attribute; clearly something strange is going on, for example the name Group at the point does not refer to the object you think it does. I suggest putting a <code>try</code> / <code>except AttributeError, e:</code> around your <code>groups = Group.all()</code> call, and in the <code>except</code> branch emit (e.g. by logging) all possible information you can find about <code>Group</code>, including what <code>__bases__</code> it actually has, its <code>dir()</code>, and so forth.</p> <p>This is about how far one can go in trying to help you (diagnosing that something very weird must have happened to the name <code>Group</code> and suggesting how to pinpoint details) without seeing your many hundreds of lines of code that could be doing who-knows-what to that name!-).</p>
4
2009-08-03T22:40:22Z
[ "python", "google-app-engine", "gae-datastore" ]
Can anyone explain this strange python turtle occurance?
1,224,944
<p>If you don't know, python turtle is an application for helping people learn python. You are given a python interpreter and an onscreen turtle that you can pass directions to using python. </p> <p>go(10) will cause the turtle to move 10 pixels turn(10) will cause it to turn 10 degrees clockwise</p> <p>now look at this</p> <p><img src="http://i28.tinypic.com/29bzoet.jpg" alt="alt text" /></p> <p>code:</p> <pre><code>import random while(1): r = random.randint(1,10) go (r) r = random.randint(-90,90) turn (r) </code></pre> <p>can anyone explain this behavior? Notice the straight line. Is there something wrong with pythons random module?</p>
1
2009-08-03T22:31:29Z
1,225,007
<p>When debugging a problem like this, it might be worthwhile to print out the value of each instruction as you perform it. Hopefully your turtle environment has a way to print values to some window on the screen. You might do something like this:</p> <pre><code>while(1): r = random.randint(1,10) print "going:", r go (r) r = random.randint(-90, 90) print "turning:", r turn (r) </code></pre> <p>This technique goes by many names, but the one I like is "When in doubt, print more out." Doing this may provide some insight into why your turtle is showing the behaviour you see.</p>
7
2009-08-03T22:52:40Z
[ "python", "random" ]
Can anyone explain this strange python turtle occurance?
1,224,944
<p>If you don't know, python turtle is an application for helping people learn python. You are given a python interpreter and an onscreen turtle that you can pass directions to using python. </p> <p>go(10) will cause the turtle to move 10 pixels turn(10) will cause it to turn 10 degrees clockwise</p> <p>now look at this</p> <p><img src="http://i28.tinypic.com/29bzoet.jpg" alt="alt text" /></p> <p>code:</p> <pre><code>import random while(1): r = random.randint(1,10) go (r) r = random.randint(-90,90) turn (r) </code></pre> <p>can anyone explain this behavior? Notice the straight line. Is there something wrong with pythons random module?</p>
1
2009-08-03T22:31:29Z
1,225,041
<p>Try printing out the values. Here's a little Python program based on your code snippet that does this:</p> <pre><code>import random while(1): distance = random.randint(1,10) angle = random.randint(-90, 90) print distance, angle </code></pre> <p>I tried this myself, and at no point does angle "get stuck". I suspect there may be some sort of bug in python turtle, but without trying out in that environment it's hard to say for sure.</p> <p>Is there a way to ask python turtle for the current angle of the turtle? You may want to print that value out as well.</p>
0
2009-08-03T23:01:40Z
[ "python", "random" ]
Can anyone explain this strange python turtle occurance?
1,224,944
<p>If you don't know, python turtle is an application for helping people learn python. You are given a python interpreter and an onscreen turtle that you can pass directions to using python. </p> <p>go(10) will cause the turtle to move 10 pixels turn(10) will cause it to turn 10 degrees clockwise</p> <p>now look at this</p> <p><img src="http://i28.tinypic.com/29bzoet.jpg" alt="alt text" /></p> <p>code:</p> <pre><code>import random while(1): r = random.randint(1,10) go (r) r = random.randint(-90,90) turn (r) </code></pre> <p>can anyone explain this behavior? Notice the straight line. Is there something wrong with pythons random module?</p>
1
2009-08-03T22:31:29Z
1,230,057
<p>I am the creator of <a href="http://pythonturtle.com" rel="nofollow">PythonTurtle</a>.</p> <p>First of all, I'm really honored to see the first question about it in StackOverflow.</p> <p>About your question: I tried running the code, and it didn't produce the bug, but since this is involving randomness, I can't really reproduce what happened in your computer.</p> <p>It seems like a bug, but I can't really guess what is causing it. If this kind of bug happens to you again, preferably when randomness is not involved, I'd appreciate if you'll send me the screenshot and the code snippet. My mail is cool-rr@cool-rr.com.</p>
1
2009-08-04T21:38:46Z
[ "python", "random" ]
Create properties using lambda getter and setter
1,224,962
<p>I have something like this:</p> <pre><code>class X(): def __init__(self): self.__name = None def _process_value(self, value): # do something pass def get_name(self): return self.__name def set_name(self, value): self.__name = self._process_value(value) name = property(get_name, set_name) </code></pre> <p>Can I replace <code>get_name</code> and <code>set_name</code> using lambda functions?</p> <p>I've tried this:</p> <pre><code>name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value)) </code></pre> <p>but compiler doesn't like my setter function.</p>
3
2009-08-03T22:39:33Z
1,224,977
<p>Your problem is that lambda's body must be an expression and assignment is a statement (a strong, deep distinction in Python). If you insist on perpetrating <code>lambda</code>s you'll meet many such cases and learn the workarounds (there's usually one, though not always), such as, in this case:</p> <pre><code>name = property(lambda self: self.__name, lambda self, value: setattr(self, '_X__name', self.process_value(value))) </code></pre> <p>i.e. use the built-in <code>setattr</code> (which is a function and thus acceptable in a <code>lambda</code>'s body) rather than assignment (which is a statement and thus unacceptable in a <code>lambda</code>'s body).</p> <p><strong>Edit</strong>: You also need to perform the name-mangling for the dual-underscore attribute manually (changing <code>__name</code> to <code>_X__name</code> as you're in class X) where the attribute name is presented as a quoted string, as it must be in setattr, as the Pyhon compiler only does the name mangling in question for suitable identifiers, not for string literals.</p>
14
2009-08-03T22:44:28Z
[ "python", "lambda", "properties" ]
Create properties using lambda getter and setter
1,224,962
<p>I have something like this:</p> <pre><code>class X(): def __init__(self): self.__name = None def _process_value(self, value): # do something pass def get_name(self): return self.__name def set_name(self, value): self.__name = self._process_value(value) name = property(get_name, set_name) </code></pre> <p>Can I replace <code>get_name</code> and <code>set_name</code> using lambda functions?</p> <p>I've tried this:</p> <pre><code>name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value)) </code></pre> <p>but compiler doesn't like my setter function.</p>
3
2009-08-03T22:39:33Z
13,780,286
<p>If you are extending a <code>list</code>, you can also use <code>__setitem__</code>, like this:</p> <pre><code>class Position(list): def __init__(self,x=0, y=0, z=0): super(Position, self).__init__((x,y,z)) x = property(lambda self: self[0], lambda self,value: self.__setitem__(0, value)) y = property(lambda self: self[1], lambda self,value: self.__setitem__(1, value)) z = property(lambda self: self[2], lambda self,value: self.__setitem__(2, value)) </code></pre>
0
2012-12-08T18:07:14Z
[ "python", "lambda", "properties" ]
How to setup mod_python configuration variables?
1,224,978
<p>I'm running a Python server with mod_python, and I've run into some issues with configuration variables. This is actually two questions rolled into one, because I think they are highly related:</p> <ol> <li><p>I need a way to configure variables that will be available in Python while running. I currently just have a module that sets some name-value pairs that I import into other modules, but I was reading up on <a href="http://www.modpython.org/live/current/doc-html/dir-other-po.html" rel="nofollow">PythonOption</a> recently and was wondering what advantages would be gained from using that instead.</p></li> <li><p>I need a way to store state on the server. I've got access to an API that's limited to running X number of times a day, and once it hits that limit, I need to revert to my (lesser) code. I'm wondering how I can keep track of how many times I've run the query in a day.</p></li> </ol> <p>I thought about using a file or the database, but I'm afraid I will slow down requests by having everyone try to access the same file or row at once. Is there a better way to set this up in mod_python?</p>
0
2009-08-03T22:44:52Z
1,225,721
<ol> <li><p>Using <code>PythonOption</code> lets you configure stuff that may need to change from server to server. I wouldn't use it too much, though, because messing with the Apache configuration directives is kind of a pain (plus it requires reloading the server). You might consider something like using <code>PythonOption</code> to specify the name of a settings file that contains the actual configuration variables. (Or you could just look in a standard location for the settings file, like most frameworks do)</p></li> <li><p>If you really don't want to consider a file or a database, try <code>memcached</code>. It's basically a very simple database (get, set, and clear by key only) that's stored entirely in RAM, so it's very fast. If all you need to store is a counter variable, though, you could probably just stick it in a Python module as a global variable, unless you're worried about the counter being reset when the module gets reloaded.</p></li> </ol>
1
2009-08-04T04:24:15Z
[ "python", "configuration", "mod-python" ]
How to setup mod_python configuration variables?
1,224,978
<p>I'm running a Python server with mod_python, and I've run into some issues with configuration variables. This is actually two questions rolled into one, because I think they are highly related:</p> <ol> <li><p>I need a way to configure variables that will be available in Python while running. I currently just have a module that sets some name-value pairs that I import into other modules, but I was reading up on <a href="http://www.modpython.org/live/current/doc-html/dir-other-po.html" rel="nofollow">PythonOption</a> recently and was wondering what advantages would be gained from using that instead.</p></li> <li><p>I need a way to store state on the server. I've got access to an API that's limited to running X number of times a day, and once it hits that limit, I need to revert to my (lesser) code. I'm wondering how I can keep track of how many times I've run the query in a day.</p></li> </ol> <p>I thought about using a file or the database, but I'm afraid I will slow down requests by having everyone try to access the same file or row at once. Is there a better way to set this up in mod_python?</p>
0
2009-08-03T22:44:52Z
1,226,722
<ol> <li><p>I need a way to configure variables that will be available in Python while running. </p> <p>Do what Django does. Use a simple importable script of Python assignment statements.</p></li> <li><p>I need a way to store state on the server. </p> <p>Do what Django does. Use SQLite3.</p></li> </ol> <p>Also, read <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a> and structure your application components to support WSGI. This should be a relatively small revision to have the proper WSGI structure to existing code.</p> <p>When you switch from mod_python to mod_wsgi, you can find numerous components to do these things for you and reduce the amount of code you've written.</p>
0
2009-08-04T10:20:49Z
[ "python", "configuration", "mod-python" ]
Haskell equivalent of Python's "Construct"
1,225,053
<p><a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a> is a DSL implemented in Python used to describe data structures (binary and textual). Once you have the data structure described, construct can parse and build it for you. Which is good ("DRY", "Declarative", "Denotational-Semantics"...)</p> <p>Usage example:</p> <pre><code># code from construct.formats.graphics.png itxt_info = Struct("itxt_info", CString("keyword"), UBInt8("compression_flag"), compression_method, CString("language_tag"), CString("translated_keyword"), OnDemand( Field("text", lambda ctx: ctx._.length - (len(ctx.keyword) + len(ctx.language_tag) + len(ctx.translated_keyword) + 5), ), ), ) </code></pre> <p>I am in need for such a tool for Haskell and I wonder if something like this exists.</p> <p>I know of:</p> <ul> <li>Data.Binary: User implements parsing and building seperately</li> <li>Parsec: Only for parsing? Only for text?</li> </ul> <p>I guess one must use Template Haskell to achieve this?</p>
2
2009-08-03T23:05:15Z
1,225,340
<p>I don't know anything about Python or Construct, so this is probably not what you are searching for, but for simple data structures you can always just derive read:</p> <pre><code>data Test a = I Int | S a deriving (Read,Show) </code></pre> <p>Now, for the expression</p> <pre><code>read "S 123" :: Test Double </code></pre> <p>GHCi will emit: S 123.0</p> <p>For anything more complex, you can make an instance of Read using Parsec.</p>
0
2009-08-04T01:09:45Z
[ "python", "parsing", "haskell", "dsl", "construct" ]
Haskell equivalent of Python's "Construct"
1,225,053
<p><a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a> is a DSL implemented in Python used to describe data structures (binary and textual). Once you have the data structure described, construct can parse and build it for you. Which is good ("DRY", "Declarative", "Denotational-Semantics"...)</p> <p>Usage example:</p> <pre><code># code from construct.formats.graphics.png itxt_info = Struct("itxt_info", CString("keyword"), UBInt8("compression_flag"), compression_method, CString("language_tag"), CString("translated_keyword"), OnDemand( Field("text", lambda ctx: ctx._.length - (len(ctx.keyword) + len(ctx.language_tag) + len(ctx.translated_keyword) + 5), ), ), ) </code></pre> <p>I am in need for such a tool for Haskell and I wonder if something like this exists.</p> <p>I know of:</p> <ul> <li>Data.Binary: User implements parsing and building seperately</li> <li>Parsec: Only for parsing? Only for text?</li> </ul> <p>I guess one must use Template Haskell to achieve this?</p>
2
2009-08-03T23:05:15Z
1,227,818
<p>I'd say it depends what you want to do, and if you need to comply with any existing format.</p> <p><a href="http://hackage.haskell.org/package/binary" rel="nofollow">Data.Binary</a> will (surprise!) help you with binary data, both reading and writing. You can either write the code to read/write yourself, or let go of the details and generate the required code for your data structures using some additional tools like <a href="http://repetae.net/computer/haskell/DrIFT/" rel="nofollow">DrIFT</a> or <a href="http://community.haskell.org/~ndm/derive/" rel="nofollow">Derive</a>. DrIFT works as a preprocessor, while Derive can work as a preprocessor and with TemplateHaskell.</p> <p><a href="http://www.haskell.org/haskellwiki/Parsec" rel="nofollow">Parsec</a> will only help you with parsing text. No binary data (as easily), and no writing. Work is done with regular <code>String</code>s. There are <code>ByteString</code> equivalents on hackage.</p> <p>For your example above I'd use Data.Binary and write custom <code>put</code>/<code>get</code>ers myself. Have a look at the <a href="http://hackage.haskell.org/packages/archive/pkg-list.html#cat:parsing" rel="nofollow">parser category at hackage</a> for more options.</p>
1
2009-08-04T14:21:23Z
[ "python", "parsing", "haskell", "dsl", "construct" ]
Haskell equivalent of Python's "Construct"
1,225,053
<p><a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a> is a DSL implemented in Python used to describe data structures (binary and textual). Once you have the data structure described, construct can parse and build it for you. Which is good ("DRY", "Declarative", "Denotational-Semantics"...)</p> <p>Usage example:</p> <pre><code># code from construct.formats.graphics.png itxt_info = Struct("itxt_info", CString("keyword"), UBInt8("compression_flag"), compression_method, CString("language_tag"), CString("translated_keyword"), OnDemand( Field("text", lambda ctx: ctx._.length - (len(ctx.keyword) + len(ctx.language_tag) + len(ctx.translated_keyword) + 5), ), ), ) </code></pre> <p>I am in need for such a tool for Haskell and I wonder if something like this exists.</p> <p>I know of:</p> <ul> <li>Data.Binary: User implements parsing and building seperately</li> <li>Parsec: Only for parsing? Only for text?</li> </ul> <p>I guess one must use Template Haskell to achieve this?</p>
2
2009-08-03T23:05:15Z
1,346,693
<p>Currently (afaik) there is no equivalent to Construct in Haskell.</p> <p>One can be implemented using Template Haskell.</p>
0
2009-08-28T12:26:29Z
[ "python", "parsing", "haskell", "dsl", "construct" ]
How can I determine the monitor refresh rate?
1,225,057
<p>Is there a cross platform way to get the monitor's refresh rate in python (2.6)? I'm using Pygame and PyOpenGL, if that helps.</p> <p>I don't need to change the refresh rate, I just need to know what it is.</p>
2
2009-08-03T23:07:02Z
1,225,763
<p>I am not sure about the platform you use, but on window you can use ctypes or win32api to get details about devices e.g. using win32api</p> <pre><code>import win32api def printInfo(device): print device.DeviceName, device.DeviceString settings = win32api.EnumDisplaySettings(device.DeviceName, 0) for varName in ['Color', 'BitsPerPel', 'DisplayFrequency']: print "%s: %s"%(varName, getattr(settings, varName)) device = win32api.EnumDisplayDevices() printInfo(device) </code></pre> <p>output on my system:</p> <pre><code>\\.\DISPLAY1 Mobile Intel(R) 945GM Express Chipset Family Color: 0 BitsPerPel: 8 DisplayFrequency: 60 </code></pre>
3
2009-08-04T04:40:50Z
[ "python", "pygame", "pyopengl" ]
Flexible 'em' style Fonts with wxPython
1,225,248
<p>Im looking for a way to present a flexible font, that will increase and decrease in size according to to the size of the screen resolution. I want to be able to do this without the HTML window class. Is there a way? I thought I've done quite a bit of googling without success.</p> <p><strong>EDIT</strong> This seems a good question, I changed the title to reflect closer what I was looking for.</p> <p><strong>EDIT</strong></p> <p>So now I've realized that the regular pixel sizes will scale in the way I mentioned already - but I saw this the other day and realized it might be helpful if someone wanted to use CSS with their wxPython Apps - its a library that allows you to 'skin' your application and I can think of a dozen neat ways to use it already - here is a link in lieu of a more well thought out question :)</p> <p><a href="http://wiki.wxpython.org/TG.Skinning" rel="nofollow">link text</a></p>
4
2009-08-04T00:23:23Z
1,246,679
<p>Maybe something like this? You can scale any wx.Window in this way. Not sure if this is exactly what you mean though.</p> <pre><code>import wx def scale(widget, percentage): font = widget.GetFont() font.SetPointSize(int(font.GetPointSize() * percentage / 100.0)) widget.SetFont(font) class Frame(wx.Frame): def __init__(self): super(Frame, self).__init__(None, -1, 'Scaling Fonts') panel = wx.Panel(self, -1) sizer = wx.BoxSizer(wx.VERTICAL) for i in range(50, 201, 25): widget = wx.StaticText(panel, -1, 'Scale Factor = %d' % i) scale(widget, i) sizer.Add(widget, 0, wx.ALL, 5) panel.SetSizer(sizer) if __name__ == '__main__': app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() </code></pre>
1
2009-08-07T19:49:59Z
[ "python", "fonts", "wxpython", "font-size" ]
Python: How to import part of a namespace
1,225,481
<p>I have a structure such this works :</p> <pre><code>import a.b.c a.b.c.foo() </code></pre> <p>and this also works :</p> <pre><code>from a.b import c c.foo() </code></pre> <p>but this doesn't work :</p> <pre><code>from a import b.c b.c.foo() </code></pre> <p>nor does :</p> <pre><code>from a import b b.c.foo() </code></pre> <p>How can I do the import so that <code>b.c.foo()</code> works?</p>
3
2009-08-04T02:25:08Z
1,225,490
<p>In your '<code>b</code>' package, you need to add '<code>import c</code>' so that it is always accessible as part of <code>b</code>.</p>
2
2009-08-04T02:27:44Z
[ "python", "import", "namespaces" ]
Python: How to import part of a namespace
1,225,481
<p>I have a structure such this works :</p> <pre><code>import a.b.c a.b.c.foo() </code></pre> <p>and this also works :</p> <pre><code>from a.b import c c.foo() </code></pre> <p>but this doesn't work :</p> <pre><code>from a import b.c b.c.foo() </code></pre> <p>nor does :</p> <pre><code>from a import b b.c.foo() </code></pre> <p>How can I do the import so that <code>b.c.foo()</code> works?</p>
3
2009-08-04T02:25:08Z
1,225,506
<pre><code>from a import b from a.b import c b.c = c </code></pre>
2
2009-08-04T02:37:29Z
[ "python", "import", "namespaces" ]
Python: How to import part of a namespace
1,225,481
<p>I have a structure such this works :</p> <pre><code>import a.b.c a.b.c.foo() </code></pre> <p>and this also works :</p> <pre><code>from a.b import c c.foo() </code></pre> <p>but this doesn't work :</p> <pre><code>from a import b.c b.c.foo() </code></pre> <p>nor does :</p> <pre><code>from a import b b.c.foo() </code></pre> <p>How can I do the import so that <code>b.c.foo()</code> works?</p>
3
2009-08-04T02:25:08Z
1,225,515
<pre><code>import a.b.c from a import b b.c.foo() </code></pre> <p>The order of the import statements doesn't matter.</p>
0
2009-08-04T02:42:13Z
[ "python", "import", "namespaces" ]
Python: How to import part of a namespace
1,225,481
<p>I have a structure such this works :</p> <pre><code>import a.b.c a.b.c.foo() </code></pre> <p>and this also works :</p> <pre><code>from a.b import c c.foo() </code></pre> <p>but this doesn't work :</p> <pre><code>from a import b.c b.c.foo() </code></pre> <p>nor does :</p> <pre><code>from a import b b.c.foo() </code></pre> <p>How can I do the import so that <code>b.c.foo()</code> works?</p>
3
2009-08-04T02:25:08Z
1,225,522
<p>Just rename it:</p> <pre><code> from a.b import c as BAR BAR.foo() </code></pre>
9
2009-08-04T02:46:04Z
[ "python", "import", "namespaces" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,225,565
<p>You can use <a href="http://search.cpan.org/dist/Spreadsheet-ParseExcel/lib/Spreadsheet/ParseExcel.pm" rel="nofollow"><code>Spreadsheet::ParseExcel</code></a> to read a spreadsheet. Unfortunately that is all I can help you with because, frankly, the description of your problem makes no sense.</p>
6
2009-08-04T03:08:04Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,225,581
<p>You could use Visual Basic for Applications to <a href="http://msdn.microsoft.com/en-us/library/aa221353%28office.11%29.aspx" rel="nofollow">loop over the cells</a> and then <a href="http://www.vbaexpress.com/kb/getarticle.php?kb%5Fid=805" rel="nofollow">save to a text file</a>.</p> <p>OR</p> <p>Save the file as a comma separated value file and use perl or python to easily parse the lines. (split on the comma for columns, end of line character for rows)</p>
-1
2009-08-04T03:13:13Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,225,629
<p>In python, you can use <a href="http://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a> to read an Excel spreadsheet into data you can work with. See the <a href="http://www.lexicon.net/sjmachin/README.html" rel="nofollow">README</a> for sample usage. You can then use <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> to create new spreadsheets.</p>
1
2009-08-04T03:35:48Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,226,481
<p>in Excel, save your file as CSV.</p> <p>in Python, use the CSV reader module to read it (read the python docs, search for csv)</p> <p>now you say you have rows of maybe 20 columns and you want to put columns 1..10 in file A and columns 11..20 in file B, yes ?</p> <p>open 2 csv writers (let's call them A and B)</p> <p>you will read rows :</p> <p>for row in csvreader: A.writerow( row[:10 ] ) B.writerow( row[11: ] )</p> <p>that's it.</p> <p>go here : <a href="http://stackoverflow.com/questions/1223967/how-can-i-merge-fields-in-a-csv-string-using-python">http://stackoverflow.com/questions/1223967/how-can-i-merge-fields-in-a-csv-string-using-python</a></p>
1
2009-08-04T09:24:09Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,228,425
<p>I think the <a href="http://www.lexicon.net/sjmachin/xlrd.htm" rel="nofollow">xlrd</a> and xlwt modules are the way to go in Python.</p> <pre><code># Read the first 5 rows and columns of an excel file import xlrd # Import the package book = xlrd.open_workbook("sample.xls") # Open an .xls file sheet = book.sheet_by_index(0) # Get the first sheet for row in range(5): # Loop for five times (five rows) # grab the current row rowValues = sheet.row_values(row, start_col=0, end_colx=4) # Do magic here, like printing import xlrd # Import the package print "%-10s | %-10s | %-10s | %-10s | %-10s" % tuple(rowValues) </code></pre> <p>Now if you feel like writing back Excel files...</p> <pre><code>import xlwt # Import the package wbook = xlwt.Workbook() # Create a new workbook sheet = wbook.add_sheet("Sample Sheet") # Create a sheet data = "Sample data" # Something to write into the sheet for rowx in range(5): # Loop through the first five rows for colx in range(5): # Loop through the first five columns # Write the data to rox, column sheet.write(rowx, colx, data) # Save our workbook on the harddrive wbook.save(&amp;amp;quot;myFile.xls&amp;amp;quot;) </code></pre> <p>I have used this method in the part extensively to read/write data from Excel files for Input/Output models to use in NetworkX. The above examples are from my blog entries talking about that adventure.</p> <p>As I am a new user, I can only post one link. Maybe you can Google xlwt? :)</p>
0
2009-08-04T16:08:30Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,229,443
<p>As others have commented your question is almost totally incomprehensible. Based on the difficulty you have describing your issue, you might want to take a look at <a href="http://stackoverflow.com/questions/1120016/hash-arrays-combining-files-how/1122992#1122992">this post</a>.</p> <p>Some here have suggested saving your file as a CSV. Saving your file as a CSV file will greatly simplify the job of parsing it, but it will make converting to and from excel format a manual process. This may be acceptable if you have a small number of files to process. If you have hundreds, it won't work so well. </p> <p>The <a href="http://search.cpan.org/dist/Spreadsheet-ParseExcel/lib/Spreadsheet/ParseExcel.pm" rel="nofollow">Spreadsheet::ParseExcel</a> and <a href="http://search.cpan.org/dist/Spreadsheet-WriteExcel/" rel="nofollow">Spreadsheet::WriteExcel</a> modules will help your read and write your spreadsheet file in native format.</p> <p>The <a href="http://search.cpan.org/dist/Text-CSV%5FXS/" rel="nofollow">Text::CSV_XS</a> module provides a powerful, fast CSV parser for perl.</p>
1
2009-08-04T19:29:02Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
1,230,735
<p>Use Python and xlrd &amp; xlwt. See <a href="http://www.python-excel.org" rel="nofollow">http://www.python-excel.org</a></p> <p>The following script should do what you want:</p> <pre><code>import xlrd, xlwt, sys def raj_split(in_path, out_stem): in_book = xlrd.open_workbook(in_path) in_sheet = in_book.sheet_by_index(0) first_row = in_sheet.row_values(0) # find the rightmost 1 value in the first row split_pos = max( colx for colx, value in enumerate(first_row) if value == 1.0 ) + 1 out_book = xlwt.Workbook() out_sheet = out_book.add_sheet("Sheet1", cell_overwrite_ok=True) # copy the common cells for rowx in xrange(in_sheet.nrows): row_vals = in_sheet.row_values(rowx, end_colx=split_pos) for colx in xrange(split_pos): out_sheet.write(rowx, colx, row_vals[colx]) out_num = 0 # for each output file ... for out_col in range(split_pos, in_sheet.ncols): out_num += 1 # ... overwrite the `split_pos` column for rowx, value in enumerate(in_sheet.col_values(colx=out_col)): out_sheet.write(rowx, split_pos, value) # ... and save the file. out_book.save("%s_%03d.xls" % (out_stem, out_num)) raj_split(*sys.argv[1:3]) </code></pre>
2
2009-08-05T01:21:47Z
[ "python", "perl" ]
Need to make multiple files from a single excel file
1,225,550
<p>I have a excel file. With many columns . I need to make multiple files using this </p> <p>Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others. </p> <p>Thank you all for ur reply. To simplify the question: </p> <ol> <li>I have a excel file as i mentioned with number of columns and rows. The columns are named as </li> </ol> <p><img src="http://img44.imageshack.us/img44/3397/84200961244pm.png" alt="alt text" /></p> <p>Now I need to split this file into many excel files the 1st will have </p> <p>A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on. </p>
-1
2009-08-04T03:01:19Z
2,236,866
<p>Actually, this is exactly what xlutils' filter functionality was designed for.</p> <p>See the 'xutils.filter' section in the tutorial on <a href="http://www.python-excel.org" rel="nofollow">http://www.python-excel.org</a></p> <p>There's also more here:</p> <p><a href="https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/filter.txt" rel="nofollow">https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/filter.txt</a></p> <p>cheers,</p> <p>Chris</p>
0
2010-02-10T12:54:47Z
[ "python", "perl" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
1,225,590
<p>I found a <a href="http://snippets.dzone.com/posts/show/4024" rel="nofollow">pretty good snippet</a> when I wanted to do this same thing (and the example uses gmail). Also check out the <a href="http://www.google.com/search?q=Checking+email+with+Python&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=com.ubuntu:en-US:unofficial&amp;client=firefox-a" rel="nofollow">google search results</a> on this.</p>
1
2009-08-04T03:18:07Z
[ "python", "email" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
1,225,592
<p>Gmail provides an atom <a href="https://mail.google.com/mail/feed/atom">feed</a> for new email messages. You should be able to monitor this by authenticating with py cURL (or some other net library) and pulling down the feed. Making a GET request for each new message should mark it as read, so you won't have to keep track of which emails you've read.</p>
14
2009-08-04T03:18:24Z
[ "python", "email" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
1,225,707
<p>While not Python-specific, I've always loved <a href="http://www.procmail.org/">procmail</a> wherever I could install it...!</p> <p>Just use as some of your action lines for conditions of your choice <code>| pathtoyourscript</code> (vertical bar AKA pipe followed by the script you want to execute in those cases) and your mail gets piped, under the conditions of your choice, to the script of your choice, for it to do whatever it wants -- hard to think of a more general approach to "trigger actions of your choice upon receipt of mails that meet your specific conditions!! Of course there are no limits to how many conditions you can check, how many action lines a single condition can trigger (just enclose all the action lines you want in <code>{ }</code> braces), etc, etc.</p>
7
2009-08-04T04:17:40Z
[ "python", "email" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
1,225,847
<p>I recently solved this problem by using procmail and python</p> <p>Read the documentation for procmail. You can tell it to send all incoming email to a python script like this in a special procmail config file</p> <pre><code>:0: | ./scripts/ppm_processor.py </code></pre> <p>Python has an "email" package available that can do anything you could possibly want to do with email. Read up on the following ones....</p> <pre><code>from email.generator import Generator from email import Message from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.mime.multipart import MIMEMultipart </code></pre>
0
2009-08-04T05:49:42Z
[ "python", "email" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
1,228,982
<p>People seem to be pumped up about Lamson:</p> <p><a href="https://github.com/zedshaw/lamson" rel="nofollow">https://github.com/zedshaw/lamson</a></p> <p>It's an SMTP server written entirely in Python. I'm sure you could leverage that to do everything you need - just forward the gmail messages to that SMTP server and then do what you will.</p> <p>However, I think it's probably easiest to do the ATOM feed recommendation above.</p> <p>EDIT: Lamson has been abandoned</p>
4
2009-08-04T17:51:44Z
[ "python", "email" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
1,231,136
<p>Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily:</p> <pre><code>import poplib from email import parser pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user('username') pop_conn.pass_('password') #Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print message['subject'] pop_conn.quit() </code></pre> <p>You would just need to run this script as a cron job. Not sure what platform you're on so YMMV as to how that's done.</p>
52
2009-08-05T04:04:04Z
[ "python", "email" ]
Checking email with Python
1,225,586
<p>I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that?</p> <p>Thank you, Sasha</p>
38
2009-08-04T03:15:46Z
20,632,538
<pre><code>print('please enter str') def email(n=str): if ('@' and '.') in n: z=n.find('@') c=n.find('.') if type(n[:z] and n[z:c] and n[c:])==str: print('valid email') else: print('unvalid email') else: print('unvalid email') </code></pre>
-6
2013-12-17T11:09:06Z
[ "python", "email" ]
Inserting the same value multiple times when formatting a string
1,225,637
<p>I have a string of this form</p> <pre><code>s='arbit' string='%s hello world %s hello world %s' %(s,s,s) </code></pre> <p>All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)</p>
67
2009-08-04T03:42:20Z
1,225,648
<pre><code>incoming = 'arbit' result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming} </code></pre> <p>You may like to have a read of this to get an understanding: <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">String Formatting Operations</a>.</p>
30
2009-08-04T03:46:06Z
[ "python", "string", "format" ]
Inserting the same value multiple times when formatting a string
1,225,637
<p>I have a string of this form</p> <pre><code>s='arbit' string='%s hello world %s hello world %s' %(s,s,s) </code></pre> <p>All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)</p>
67
2009-08-04T03:42:20Z
1,225,656
<p>You can use <a href="http://www.python.org/dev/peps/pep-3101/">advanced string formatting</a>, available in Python 2.6 and Python 3.x:</p> <pre><code>incoming = 'arbit' result = '{0} hello world {0} hello world {0}'.format(incoming) </code></pre>
127
2009-08-04T03:49:01Z
[ "python", "string", "format" ]
Inserting the same value multiple times when formatting a string
1,225,637
<p>I have a string of this form</p> <pre><code>s='arbit' string='%s hello world %s hello world %s' %(s,s,s) </code></pre> <p>All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)</p>
67
2009-08-04T03:42:20Z
1,225,681
<p>You can use the dictionary type of formatting:</p> <pre><code>s='arbit' string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,} </code></pre>
13
2009-08-04T03:59:59Z
[ "python", "string", "format" ]
Inserting the same value multiple times when formatting a string
1,225,637
<p>I have a string of this form</p> <pre><code>s='arbit' string='%s hello world %s hello world %s' %(s,s,s) </code></pre> <p>All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)</p>
67
2009-08-04T03:42:20Z
1,225,724
<p>Depends on what you mean by better. This works if your goal is removal of redundancy.</p> <pre><code>s='foo' string='%s bar baz %s bar baz %s bar baz' % (3*(s,)) </code></pre>
10
2009-08-04T04:26:12Z
[ "python", "string", "format" ]
Inserting the same value multiple times when formatting a string
1,225,637
<p>I have a string of this form</p> <pre><code>s='arbit' string='%s hello world %s hello world %s' %(s,s,s) </code></pre> <p>All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)</p>
67
2009-08-04T03:42:20Z
12,084,650
<pre><code>&gt;&gt;&gt; s1 ='arbit' &gt;&gt;&gt; s2 = 'hello world '.join( [s]*3 ) &gt;&gt;&gt; print s2 arbit hello world arbit hello world arbit </code></pre>
3
2012-08-23T04:14:55Z
[ "python", "string", "format" ]
How to control Webpage dialog with python
1,225,686
<p>When I try to automatically download a file from some webpage using Python, I get Webpage Dialog window (I use IE). The window has two buttons, such as 'Continue' and 'Cancel'. I cannot figure out how to click on the Continue Button. The problem is that I don't know how to control Webpage Dialog with Python. I tried to use winGuiAuto to find the controls of the window, but it fails to recognize any Button type controls... An ideas?</p> <p>Sasha</p> <p>A clarification of my question:</p> <p>My purpose is to download stock data from a certain web site. I need to perform it for many stocks so I need python to do it for me in a repetitive way. This specific site exports the data by letting me download it in Excel file by clicking a link. However after clicking the link I get a Web Page dialog box asking me if I am sure that I want to download this file. This Web page dialog is my problem - it is not an html page and it is not a regular windows dialog box. It is something else and I cannot configure how to control it with python. It has two buttons and I need to click on one of them (i.e. Continue). It seems like it is a special kind of window implemented in IE. It is distinguished by its title which looks like this: Webpage Dialog -- Download blalblabla. If I click Continue mannually it opens a regular windows dialog box (open,save,cancel) which i know how to handle with winGuiAuto library. Tried to use this library for the Webpage Dialog window with no luck. Tried to recognize the buttons with Autoit Info tool -no luck either. In fact, maybe these are not buttons, but actually links, however I cannot see the links and there is no source code visible... What I need is someone to tell me what this Web page Dialog box is and how to control it with Python. That was my question.</p>
0
2009-08-04T04:03:09Z
1,226,061
<p>You can't, and you don't want to. When you ask a question, try explaining what you are trying to achieve, and not just the task immediately before you. You are likely barking down the wrong path. There is some other way of doing what you are trying to do.</p>
0
2009-08-04T07:15:07Z
[ "python", "dialog", "webpage" ]
How to control Webpage dialog with python
1,225,686
<p>When I try to automatically download a file from some webpage using Python, I get Webpage Dialog window (I use IE). The window has two buttons, such as 'Continue' and 'Cancel'. I cannot figure out how to click on the Continue Button. The problem is that I don't know how to control Webpage Dialog with Python. I tried to use winGuiAuto to find the controls of the window, but it fails to recognize any Button type controls... An ideas?</p> <p>Sasha</p> <p>A clarification of my question:</p> <p>My purpose is to download stock data from a certain web site. I need to perform it for many stocks so I need python to do it for me in a repetitive way. This specific site exports the data by letting me download it in Excel file by clicking a link. However after clicking the link I get a Web Page dialog box asking me if I am sure that I want to download this file. This Web page dialog is my problem - it is not an html page and it is not a regular windows dialog box. It is something else and I cannot configure how to control it with python. It has two buttons and I need to click on one of them (i.e. Continue). It seems like it is a special kind of window implemented in IE. It is distinguished by its title which looks like this: Webpage Dialog -- Download blalblabla. If I click Continue mannually it opens a regular windows dialog box (open,save,cancel) which i know how to handle with winGuiAuto library. Tried to use this library for the Webpage Dialog window with no luck. Tried to recognize the buttons with Autoit Info tool -no luck either. In fact, maybe these are not buttons, but actually links, however I cannot see the links and there is no source code visible... What I need is someone to tell me what this Web page Dialog box is and how to control it with Python. That was my question.</p>
0
2009-08-04T04:03:09Z
15,988,283
<p>The title 'Webpage Dialog' suggests that is a Javascript-generated input box, hence why you can't access it via winGuiAuto. What you're asking directly is unlikely to be possible.</p> <p>However, making the assumption that what you want to do is just download this data from the site, why are you using the GUI at all? Python provides everything you need to download files from the internet without controlling IE. The process you will want to follow is:</p> <ol> <li>Download the host page</li> <li>Find the url for your download in the page (if it changes)</li> <li>Download the file from that url to a local file</li> </ol> <p>In Python this would look something like this:</p> <pre><code>import urllib,re f = urllib.urlopen('http://yoursitehere') # Original page where the download button is html = f.read() f.close() m = re.search('/[\'"](.*\.xls)["\']/', html, re.S) # Find file ending .xls in page if m: urllib.urlretrieve(m.group(1), 'local_filename.xls') # Retrieve the Excel file </code></pre>
0
2013-04-13T13:24:39Z
[ "python", "dialog", "webpage" ]
How to control Webpage dialog with python
1,225,686
<p>When I try to automatically download a file from some webpage using Python, I get Webpage Dialog window (I use IE). The window has two buttons, such as 'Continue' and 'Cancel'. I cannot figure out how to click on the Continue Button. The problem is that I don't know how to control Webpage Dialog with Python. I tried to use winGuiAuto to find the controls of the window, but it fails to recognize any Button type controls... An ideas?</p> <p>Sasha</p> <p>A clarification of my question:</p> <p>My purpose is to download stock data from a certain web site. I need to perform it for many stocks so I need python to do it for me in a repetitive way. This specific site exports the data by letting me download it in Excel file by clicking a link. However after clicking the link I get a Web Page dialog box asking me if I am sure that I want to download this file. This Web page dialog is my problem - it is not an html page and it is not a regular windows dialog box. It is something else and I cannot configure how to control it with python. It has two buttons and I need to click on one of them (i.e. Continue). It seems like it is a special kind of window implemented in IE. It is distinguished by its title which looks like this: Webpage Dialog -- Download blalblabla. If I click Continue mannually it opens a regular windows dialog box (open,save,cancel) which i know how to handle with winGuiAuto library. Tried to use this library for the Webpage Dialog window with no luck. Tried to recognize the buttons with Autoit Info tool -no luck either. In fact, maybe these are not buttons, but actually links, however I cannot see the links and there is no source code visible... What I need is someone to tell me what this Web page Dialog box is and how to control it with Python. That was my question.</p>
0
2009-08-04T04:03:09Z
25,562,482
<p>It is better to use selenium Python bindings:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common import alert from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException class AlertsManager: def alertsManager(self,url): self.url_to_visit=url self.driver=webdriver.Ie() self.driver.get(self.url_to_visit) try: while WebDriverWait(self.driver,1).until(EC.alert_is_present()): self.alert=self.driver.switch_to_alert() self.driver.switch_to_alert().accept() except TimeoutException: pass if __name__=='__main__': AM=AlertsManager() url="http://htmlite.com/JS006.php" # This website has 2 popups AM.alertsManager(url) </code></pre>
0
2014-08-29T06:02:51Z
[ "python", "dialog", "webpage" ]
Terminate long running python threads
1,226,091
<p>What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since</p> <blockquote> <p>Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); <strong>only the main thread can set a new signal handler, and the main thread will be the only one to receive signals</strong> (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication.Use locks instead.</p> </blockquote> <p>Update: each thread in my case blocks -- it is downloading a web page using urllib2 module and sometimes operation takes too many time on an extremely slow sites. That's why I want to terminate such slow threads</p>
5
2009-08-04T07:25:14Z
1,226,100
<p>If you are trying to kill a thread whose code you do not have control over, it depends if the thread is in a blocking call or not. In my experience if the thread is properly blocking, there is no recommended and portable way of doing this.</p> <p>I've run up against this when trying to work with code in the standard library (<a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.managers.BaseManager.serve%5Fforever" rel="nofollow">multiprocessing.manager</a> I'm looking at you) with loops coded with no exit condition: nice!</p> <p>There are some interuptable thread implementations out there (<a href="http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">see here for an example</a>), but then, if you have the control of the threaded code yourself, you should be able to write them in a manner where you can interupt them with a condition variable of some sort.</p>
1
2009-08-04T07:28:09Z
[ "python", "multithreading" ]
Terminate long running python threads
1,226,091
<p>What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since</p> <blockquote> <p>Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); <strong>only the main thread can set a new signal handler, and the main thread will be the only one to receive signals</strong> (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication.Use locks instead.</p> </blockquote> <p>Update: each thread in my case blocks -- it is downloading a web page using urllib2 module and sometimes operation takes too many time on an extremely slow sites. That's why I want to terminate such slow threads</p>
5
2009-08-04T07:25:14Z
1,226,101
<p>Use synchronization objects and ask the thread to terminate. Basically, write co-operative handling of this.</p> <p>If you start yanking out the thread beneath the python interpreter, all sorts of odd things can occur, and it's not just in Python either, most runtimes have this problem.</p> <p>For instance, let's say you kill a thread after it has opened a file, there's no way that file will be closed until the application terminates.</p>
1
2009-08-04T07:28:40Z
[ "python", "multithreading" ]
Terminate long running python threads
1,226,091
<p>What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since</p> <blockquote> <p>Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); <strong>only the main thread can set a new signal handler, and the main thread will be the only one to receive signals</strong> (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication.Use locks instead.</p> </blockquote> <p>Update: each thread in my case blocks -- it is downloading a web page using urllib2 module and sometimes operation takes too many time on an extremely slow sites. That's why I want to terminate such slow threads</p>
5
2009-08-04T07:25:14Z
1,227,814
<p>Since abruptly killing a thread that's in a blocking call is not feasible, a better approach, when possible, is to avoid using threads in favor of other multi-tasking mechanisms that don't suffer from such issues.</p> <p>For the OP's specific case (the threads' job is to download web pages, and some threads block forever due to misbehaving sites), the ideal solution is <a href="http://twistedmatrix.com/trac/">twisted</a> -- as it generally is for networking tasks. In other cases, <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> might be better.</p> <p>More generally, when threads give unsolvable issues, I recommend switching to other multitasking mechanisms rather than trying heroic measures in the attempt to make threads perform tasks for which, at least in CPython, they're unsuitable.</p>
6
2009-08-04T14:20:53Z
[ "python", "multithreading" ]
Terminate long running python threads
1,226,091
<p>What is the recommended way to terminate unexpectedly long running threads in python ? I can't use SIGALRM, since</p> <blockquote> <p>Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); <strong>only the main thread can set a new signal handler, and the main thread will be the only one to receive signals</strong> (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication.Use locks instead.</p> </blockquote> <p>Update: each thread in my case blocks -- it is downloading a web page using urllib2 module and sometimes operation takes too many time on an extremely slow sites. That's why I want to terminate such slow threads</p>
5
2009-08-04T07:25:14Z
1,806,891
<p>As Alex Martelli suggested, you could use the multiprocessing module. It is very similar to the Threading module so that should get you off to a start easily. Your code could be like this for example:</p> <pre><code>import multiprocessing def get_page(*args, **kwargs): # your web page downloading code goes here def start_get_page(timeout, *args, **kwargs): p = multiprocessing.Process(target=get_page, args=args, kwargs=kwargs) p.start() p.join(timeout) if p.is_alive(): # stop the downloading 'thread' p.terminate() # and then do any post-error processing here if __name__ == "__main__": start_get_page(timeout, *args, **kwargs) </code></pre> <p>Of course you need to somehow get the return values of your page downloading code. For that you could use multiprocessing.Pipe or multiprocessing.Queue (or other ways available with multiprocessing). There's more information, as well as samples you could check at <a href="http://docs.python.org/library/multiprocessing.html">http://docs.python.org/library/multiprocessing.html</a>.</p> <p>Lastly, the multiprocessing module is included in python 2.6. It is also available for python 2.5 and 2.4 at pypi (you can use </p> <blockquote> <p>easy_install multiprocessing</p> </blockquote> <p>)</p> <p>or just visit pypi and download and install the packages manually.</p> <p>Note: I realize this has been posted awhile ago. I was having a similar problem to this and stumbled here and saw Alex Martelli's suggestion. Had it implemented for my problem and decided to share it. (I'd like to thank Alex for pointing me in the right direction.)</p>
5
2009-11-27T05:18:22Z
[ "python", "multithreading" ]
Django ManyToMany relation add() error
1,226,290
<p>I've got a model that looks like this,</p> <pre><code>class PL(models.Model): locid = models.AutoField(primary_key=True) mentionedby = models.ManyToManyField(PRT) class PRT(models.Model): tid = .. </code></pre> <p>The resulting many to many table in mysql is formed as,</p> <pre><code>+------------------+------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | PL_id | int(11) | NO | MUL | NULL | | | PRT_id | bigint(64) | NO | MUL | NULL | | +------------------+------------+------+-----+---------+----------------+ </code></pre> <p>Now, if pl is an object of PL and prt that of PRT, then doing</p> <pre><code>pl.mentionedby.add(prt) </code></pre> <p>gives me an error</p> <blockquote> <p>Incorrect integer value: 'PRT object' for column 'prt_id' at row 1"</p> </blockquote> <p>whereas </p> <pre><code>pl.mentionedby.add(prt.tid) </code></pre> <p>works fine - with one caveat.</p> <p>I can see all the elements in <code>pl.mentionedby.all()</code>, but I can't go to a mentioned PRT object and see its <code>prt.mentionedby_set.all()</code>.</p> <p>Does anyone know why this happens? Whats the best way to fix it?</p> <p>Thanks!</p>
2
2009-08-04T08:26:19Z
1,226,317
<p>Are these the complete models? I can only assume that something's been overriden somewhere, that probably shouldn't have been.</p> <p>Can you post the full code?</p>
0
2009-08-04T08:33:25Z
[ "python", "django", "django-models", "many-to-many" ]
Django ManyToMany relation add() error
1,226,290
<p>I've got a model that looks like this,</p> <pre><code>class PL(models.Model): locid = models.AutoField(primary_key=True) mentionedby = models.ManyToManyField(PRT) class PRT(models.Model): tid = .. </code></pre> <p>The resulting many to many table in mysql is formed as,</p> <pre><code>+------------------+------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | PL_id | int(11) | NO | MUL | NULL | | | PRT_id | bigint(64) | NO | MUL | NULL | | +------------------+------------+------+-----+---------+----------------+ </code></pre> <p>Now, if pl is an object of PL and prt that of PRT, then doing</p> <pre><code>pl.mentionedby.add(prt) </code></pre> <p>gives me an error</p> <blockquote> <p>Incorrect integer value: 'PRT object' for column 'prt_id' at row 1"</p> </blockquote> <p>whereas </p> <pre><code>pl.mentionedby.add(prt.tid) </code></pre> <p>works fine - with one caveat.</p> <p>I can see all the elements in <code>pl.mentionedby.all()</code>, but I can't go to a mentioned PRT object and see its <code>prt.mentionedby_set.all()</code>.</p> <p>Does anyone know why this happens? Whats the best way to fix it?</p> <p>Thanks!</p>
2
2009-08-04T08:26:19Z
1,843,427
<p>Adding <code>prt</code> directly should work on first try. How are you retrieving <code>pl</code> and <code>prt</code>? Assuming you have some data in your database, try those commands from the Django shell and see if it works. There seems to be some missing information from the question. After running <code>python manage.py shell</code>:</p> <pre><code>from yourapp.models import PL pl = PL.objects.get(id=1) prt = PRT.objects.get(id=1) pl.mentionedby.add(prt) </code></pre>
5
2009-12-03T22:26:13Z
[ "python", "django", "django-models", "many-to-many" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
1,226,683
<p>Using CPython's threading model will not give you any performance improvement, because the threads are not actually executed in parallel, due to the way garbage collection is handled. Multiprocess would allow parallel execution. Obviously in this case you have to have multiple cores available to farm out your parallel jobs to.</p> <p>There is much more information available in <a href="http://stackoverflow.com/questions/1190206/threading-in-python">this related question</a>.</p>
0
2009-08-04T10:10:58Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
1,226,759
<p>For small collections of data, simply create subprocesses with <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow">subprocess.Popen</a>.</p> <p>Each subprocess can simply get it's piece of data from stdin or from command-line arguments, do it's processing, and simply write the result to an output file.</p> <p>When the subprocesses have all finished (or timed out), you simply merge the output files.</p> <p>Very simple.</p>
7
2009-08-04T10:31:42Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
1,226,873
<p>You might consider looking into <a href="http://www.stackless.com/">Stackless Python</a>. If you have control over the function that takes a long time, you can just throw some <code>stackless.schedule()</code>s in there (saying yield to the next coroutine), or else you can <a href="http://www.stackless.com/wiki/Scheduling">set Stackless to preemptive multitasking</a>.</p> <p>In Stackless, you don't have threads, but <em>tasklets</em> or <em>greenlets</em> which are essentially very lightweight threads. It works great in the sense that there's a pretty good framework with very little setup to get multitasking going.</p> <p>However, Stackless hinders portability because you have to replace a few of the standard Python libraries -- Stackless removes reliance on the C stack. It's very portable if the next user also has Stackless installed, but that will rarely be the case.</p>
7
2009-08-04T11:06:41Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
1,227,204
<p>If you are truly compute bound, using the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing" rel="nofollow">multiprocessing module</a> is probably the lightest weight solution (in terms of both memory consumption and implementation difficulty.)</p> <p>If you are I/O bound, using the <a href="http://docs.python.org/library/threading.html#module-threading" rel="nofollow">threading module</a> will usually give you good results. Make sure that you use thread safe storage (like the Queue) to hand data to your threads. Or else hand them a single piece of data that is unique to them when they are spawned.</p> <p><a href="http://pypy.org/features.html" rel="nofollow">PyPy</a> is focused on performance. It has a number of features that can help with compute-bound processing. They also have support for Software Transactional Memory, although that is not yet production quality. The promise is that you can use simpler parallel or concurrent mechanisms than multiprocessing (which has some awkward requirements.) </p> <p><a href="http://en.wikipedia.org/wiki/Stackless_Python" rel="nofollow">Stackless Python</a> is also a nice idea. Stackless has portability issues as indicated above. <a href="http://en.wikipedia.org/wiki/Unladen_Swallow" rel="nofollow">Unladen Swallow</a> was promising, but is now defunct. <a href="https://github.com/dropbox/pyston" rel="nofollow">Pyston</a> is another (unfinished) Python implementation focusing on speed. It is taking an approach different to PyPy, which may yield better (or just different) speedups. </p>
29
2009-08-04T12:26:14Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
1,227,628
<p>If you can easily partition and separate the data you have, it sounds like you should just do that partitioning externally, and feed them to several processes of your program. (i.e. several processes instead of threads)</p>
0
2009-08-04T13:45:04Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
1,252,808
<p>IronPython has real multithreading, unlike CPython and it's GIL. So depending on what you're doing it may be worth looking at. But it sounds like your use case is better suited to the multiprocessing module.</p> <p>To the guy who recommends stackless python, I'm not an expert on it, but it seems to me that he's talking about software "multithreading", which is actually not parallel at all (still runs in one physical thread, so cannot scale to multiple cores.) It's merely an alternative way to structure asynchronous (but still single-threaded, non-parallel) application.</p>
0
2009-08-10T01:31:12Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
2,137,311
<p>Tasks runs like sequentially but you have the illusion that are run in parallel. Tasks are good when you use for file or connection I/O and because are lightweights.</p> <p>Multiprocess with Pool may be the right solution for you because processes runs in parallel so are very good with intensive computing because each process run in one CPU (or core).</p> <p>Setup multiprocess may be very easy:</p> <pre><code>from multiprocessing import Pool def worker(input_item): output = do_some_work() return output pool = Pool() # it make one process for each CPU (or core) of your PC. Use "Pool(4)" to force to use 4 processes, for example. list_of_results = pool.map(worker, input_list) # Launch all automatically </code></pre>
9
2010-01-26T03:13:17Z
[ "python", "multithreading", "multiprocess" ]
multiprocess or threading in python?
1,226,584
<p>I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation?</p> <p>I attempted to use threading but had some trouble, often some of the tasks would never actually fire.</p>
31
2009-08-04T09:47:19Z
2,137,331
<p>You may want to look at <a href="http://www.twistedmatrix.com" rel="nofollow">Twisted</a>. It is designed for asynchronous network tasks. </p>
0
2010-01-26T03:17:43Z
[ "python", "multithreading", "multiprocess" ]
What is a good configuration file library for c thats not xml (preferably has python bindings)?
1,227,031
<p>I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?</p>
5
2009-08-04T11:48:37Z
1,227,227
<p>You could use a pure python solution like <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</a> and then simply use the CPython API to query for settings. This assumes that your application embeds Python. If it doesn't, and if you are shipping Python anyway, it might make sense to just embed it. Your C .exe won't get that much bigger if it's a dynamic link, and you will have all the flexibility of Python at your disposal.</p>
0
2009-08-04T12:29:52Z
[ "python", "c", "configuration-management" ]
What is a good configuration file library for c thats not xml (preferably has python bindings)?
1,227,031
<p>I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?</p>
5
2009-08-04T11:48:37Z
1,227,256
<p>Despite being hated by techies and disowned by Microsoft, INI files are actually quite popular with users, as they are easy to understand and edit. They are also very simple to write parsers for, should your libraries not already support them.</p>
0
2009-08-04T12:35:56Z
[ "python", "c", "configuration-management" ]
What is a good configuration file library for c thats not xml (preferably has python bindings)?
1,227,031
<p>I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?</p>
5
2009-08-04T11:48:37Z
1,227,272
<p><a href="http://www.yaml.org/">YaML</a> :)</p>
5
2009-08-04T12:38:53Z
[ "python", "c", "configuration-management" ]
What is a good configuration file library for c thats not xml (preferably has python bindings)?
1,227,031
<p>I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?</p>
5
2009-08-04T11:48:37Z
1,227,797
<p>If you're not married to Python, try <a href="http://www.lua.org/" rel="nofollow">Lua</a>. It was originally designed for configuration.</p>
1
2009-08-04T14:17:38Z
[ "python", "c", "configuration-management" ]
Substitutions inside links in reST / Sphinx
1,227,037
<p>I am using Sphinx to document a webservice that will be deployed in different servers. The documentation is full of URL examples for the user to click and they should just work. My problem is that the host, port and deployment root will vary and the documentation will have to be re-generated for every deployment.</p> <p>I tried defining substitutions like this:</p> <pre><code>|base_url|/path .. |base_url| replace:: http://localhost:8080 </code></pre> <p>But the generated HTML is not what I want (doesn't include "/path" in the generated link):</p> <pre><code>&lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;/path </code></pre> <p>Does anybody know how to work around this?</p>
16
2009-08-04T11:49:27Z
1,232,671
<p>You can write a Sphinx <a href="http://sphinx.pocoo.org/extensions.html" rel="nofollow">extension</a> that creates a <a href="http://sphinx.pocoo.org/markup/inline.html" rel="nofollow">role</a> like</p> <pre><code>:apilink:`path` </code></pre> <p>and generates the link from that. I never did this, so I can't help more than giving this pointer, sorry. You should try to look at how the various roles are implemented. Many are very similar to what you need, I think.</p>
1
2009-08-05T11:28:34Z
[ "python", "documentation", "substitution", "restructuredtext", "python-sphinx" ]
Substitutions inside links in reST / Sphinx
1,227,037
<p>I am using Sphinx to document a webservice that will be deployed in different servers. The documentation is full of URL examples for the user to click and they should just work. My problem is that the host, port and deployment root will vary and the documentation will have to be re-generated for every deployment.</p> <p>I tried defining substitutions like this:</p> <pre><code>|base_url|/path .. |base_url| replace:: http://localhost:8080 </code></pre> <p>But the generated HTML is not what I want (doesn't include "/path" in the generated link):</p> <pre><code>&lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;/path </code></pre> <p>Does anybody know how to work around this?</p>
16
2009-08-04T11:49:27Z
1,233,122
<p>Ok, here's how I did it. First, <code>apilinks.py</code> (the Sphinx extension):</p> <pre><code>from docutils import nodes, utils def setup(app): def api_link_role(role, rawtext, text, lineno, inliner, options={}, content=[]): ref = app.config.apilinks_base + text node = nodes.reference(rawtext, utils.unescape(ref), refuri=ref, **options) return [node], [] app.add_config_value('apilinks_base', 'http://localhost/', False) app.add_role('apilink', api_link_role) </code></pre> <p>Now, in <code>conf.py</code>, add <code>'apilinks'</code> to the extensions list and set an appropriate value for <code>'apilinks_base'</code> (otherwise, it will default to <code>'<a href="http://localhost/" rel="nofollow">http://localhost/</a>'</code>). My file looks like this:</p> <pre><code>extensions = ['sphinx.ext.autodoc', 'apilinks'] # lots of other stuff apilinks_base = 'http://host:88/base/' </code></pre> <p>Usage:</p> <pre><code>:apilink:`path` </code></pre> <p>Output:</p> <pre><code>&lt;a href="http://host:88/base/path"&gt;http://host:88/base/path&lt;/a&gt; </code></pre>
4
2009-08-05T13:03:10Z
[ "python", "documentation", "substitution", "restructuredtext", "python-sphinx" ]
Substitutions inside links in reST / Sphinx
1,227,037
<p>I am using Sphinx to document a webservice that will be deployed in different servers. The documentation is full of URL examples for the user to click and they should just work. My problem is that the host, port and deployment root will vary and the documentation will have to be re-generated for every deployment.</p> <p>I tried defining substitutions like this:</p> <pre><code>|base_url|/path .. |base_url| replace:: http://localhost:8080 </code></pre> <p>But the generated HTML is not what I want (doesn't include "/path" in the generated link):</p> <pre><code>&lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;/path </code></pre> <p>Does anybody know how to work around this?</p>
16
2009-08-04T11:49:27Z
5,808,741
<p>New in Sphinx v1.0:</p> <p>sphinx.ext.extlinks – Markup to shorten external links</p> <p><a href="http://sphinx.pocoo.org/ext/extlinks.html">http://sphinx.pocoo.org/ext/extlinks.html</a></p> <p>The extension adds one new config value:</p> <p><strong>extlinks</strong></p> <p>This config value must be a dictionary of external sites, mapping unique short alias names to a base URL and a prefix. For example, to create an alias for the above mentioned issues, you would add</p> <pre><code>extlinks = {'issue': ('http://bitbucket.org/birkenfeld/sphinx/issue/%s', 'issue ')} </code></pre> <p>Now, you can use the alias name as a new role, e.g. <code>:issue:`123`</code>. This then inserts a link to <a href="http://bitbucket.org/birkenfeld/sphinx/issue/123">http://bitbucket.org/birkenfeld/sphinx/issue/123</a>. As you can see, the target given in the role is substituted in the base URL in the place of <code>%s</code>.</p> <p>The link caption depends on the second item in the tuple, the prefix:</p> <p>If the prefix is None, the link caption is the full URL. If the prefix is the empty string, the link caption is the partial URL given in the role content (123 in this case.) If the prefix is a non-empty string, the link caption is the partial URL, prepended by the prefix – in the above example, the link caption would be issue 123. You can also use the usual “explicit title” syntax supported by other roles that generate links, i.e. <code>:issue:`this issue &lt;123&gt;`</code>. In this case, the prefix is not relevant.</p>
18
2011-04-27T18:26:10Z
[ "python", "documentation", "substitution", "restructuredtext", "python-sphinx" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
1,227,141
<p>When comparing instances of objects, the <a href="http://docs.python.org/reference/datamodel.html#object.__cmp__" rel="nofollow"><code>__cmp__</code></a> function is called.</p> <p>If the == operator is not working for you by default, you can always redefine the <code>__cmp__</code> function for the object.</p> <p>Edit:</p> <p>As has been pointed out, the <code>__cmp__</code> function is deprecated since 3.0. Instead you should use the <a href="http://docs.python.org/reference/datamodel.html#object.__lt__" rel="nofollow">“rich comparison”</a> methods.</p>
2
2009-08-04T12:13:58Z
[ "python", "object" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
1,227,147
<p>Implement the <code>__eq__</code> method in your class; something like this:</p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Edit: if you want your objects to compare equal if and only if they have equal instance dictionaries:</p> <pre><code>def __eq__(self, other): return self.__dict__ == other.__dict__ </code></pre>
3
2009-08-04T12:15:18Z
[ "python", "object" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
1,227,152
<p>You override the <a href="https://docs.python.org/2.7/reference/datamodel.html#object.__lt__">rich comparison operators</a> in your object.</p> <pre><code>class MyClass: def __lt__(self, other): # return comparison def __le__(self, other) # return comparison def __eq__(self, other) # return comparison def __ne__(self, other) # return comparison def __gt__(self, other) # return comparison def __ge__(self, other) # return comparison </code></pre>
29
2009-08-04T12:15:43Z
[ "python", "object" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
1,227,201
<p>Instance of a class when compared with == comes to non-equal. The best way is to ass the <strong>cmp</strong> function to your class which will do the stuff. </p> <p>If you want to do comparison by the content you can simply use cmp(obj1,obj2)</p> <p>In your case cmp(doc1,doc2) It will return -1 if the content wise they are same.</p>
-4
2009-08-04T12:25:15Z
[ "python", "object" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
1,227,325
<p>As usual with Python, it's <a href="http://en.wikipedia.org/wiki/KISS_principle">kiss</a> :</p> <pre><code>class Test(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def __str__(self): return str(self.__dict__) def __eq__(self, other): return self.__dict__ == other.__dict__ t1 = Test("foo", 42) t2 = Test("foo", 42) t3 = Test("bar", 42) print t1, t2, t3 print t1 == t2 print t2 == t3 </code></pre> <p>It outputs:</p> <pre><code>{'attr2': 42, 'attr1': 'foo'} {'attr2': 42, 'attr1': 'foo'} {'attr2': 42, 'attr1': 'bar'} True False </code></pre> <p>N.B : be aware that before Python 3.0, you are more likely to use <code>__cmp__</code> instead of <code>__eq__</code>, working the same way.</p>
144
2009-08-04T12:47:34Z
[ "python", "object" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
17,043,417
<p>I tried the initial example (see 7 above) and it did not work in ipython. Note that cmp(obj1,obj2) returns a "1" when implemented using two identical object instances. Oddly enough when I modify one of the attribute values and recompare, using cmp(obj1,obj2) the object continues to return a "1". (sigh...)</p> <p>Ok, so what you need to do is iterate two objects and compare each attribute using the == sign.</p>
-1
2013-06-11T11:52:01Z
[ "python", "object" ]
Compare object instances for equality by their attributes in Python
1,227,121
<p>What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like</p> <p>Example:</p> <pre><code>doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something </code></pre> <p><strong>EDIT:</strong></p> <p>To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than </p> <pre><code>def __eq__(self, other): return self.path == other.path and self.title == other.title </code></pre> <p>Should the <code>__eq__()</code> method look something like this?</p> <pre><code>def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other </code></pre>
106
2009-08-04T12:09:38Z
35,652,262
<p>As a summary : </p> <ol> <li>It's advised to implement <code>__eq__</code> rather than <code>__cmp__</code>, except if you run python &lt;= 2.0 (<code>__eq__</code> has been added in 2.1)</li> <li>Don't forget to also implement <code>__ne__</code> (should be something like <code>return not self.__eq__(other)</code> or <code>return not self == other</code> except very special case)</li> <li>Don`t forget that the operator must be implemented in each custom class you want to compare (see example below).</li> <li><p>If you want to compare with object that can be None, you must implement it. The interpreter cannot guess it ... (see example below)</p> <pre><code>class B(object): def __init__(self): self.name = "toto" def __eq__(self, other): if other is None: return False return self.name == other.name class A(object): def __init__(self): self.toto = "titi" self.b_inst = B() def __eq__(self, other): if other is None: return False return (self.toto, self.b_inst) == (other.toto, other.b_inst) </code></pre></li> </ol>
1
2016-02-26T12:53:12Z
[ "python", "object" ]
can someone help me understand this short .py
1,227,448
<p>I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/</a>. Basically what I don't understand is how the variable pickledList ends up available to the threads scope to be shipped out to the client since its never passed to the thread anywhere in the code</p> <pre><code>import pickle import Queue import socket import threading # We'll pickle a list of numbers, yet again: someList = [ 1, 2, 7, 9, 0 ] pickledList = pickle.dumps ( someList ) # A revised version of our thread class: class ClientThread ( threading.Thread ): # Note that we do not override Thread's __init__ method. # The Queue module makes this not necessary. def run ( self ): # Have our thread serve "forever": while True: # Get a client out of the queue client = clientPool.get() # Check if we actually have an actual client in the client variable: if client != None: print 'Received connection:', client [ 1 ] [ 0 ] client [ 0 ].send ( pickledList ) for x in xrange ( 10 ): print client [ 0 ].recv ( 1024 ) client [ 0 ].close() print 'Closed connection:', client [ 1 ] [ 0 ] # Create our Queue: clientPool = Queue.Queue ( 0 ) # Start two threads: for x in xrange ( 2 ): ClientThread().start() # Set up the server: server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) server.bind ( ( '', 2727 ) ) server.listen ( 5 ) # Have the server serve "forever": while True: clientPool.put ( server.accept() ) </code></pre>
2
2009-08-04T13:08:57Z
1,227,472
<p>The <code>pickledList</code> variable is available as a global variable in the <code>ClientThread</code> class. See <a href="http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules">Short Description of Python Scoping Rules</a>.</p>
4
2009-08-04T13:12:28Z
[ "python", "multithreading" ]
can someone help me understand this short .py
1,227,448
<p>I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/</a>. Basically what I don't understand is how the variable pickledList ends up available to the threads scope to be shipped out to the client since its never passed to the thread anywhere in the code</p> <pre><code>import pickle import Queue import socket import threading # We'll pickle a list of numbers, yet again: someList = [ 1, 2, 7, 9, 0 ] pickledList = pickle.dumps ( someList ) # A revised version of our thread class: class ClientThread ( threading.Thread ): # Note that we do not override Thread's __init__ method. # The Queue module makes this not necessary. def run ( self ): # Have our thread serve "forever": while True: # Get a client out of the queue client = clientPool.get() # Check if we actually have an actual client in the client variable: if client != None: print 'Received connection:', client [ 1 ] [ 0 ] client [ 0 ].send ( pickledList ) for x in xrange ( 10 ): print client [ 0 ].recv ( 1024 ) client [ 0 ].close() print 'Closed connection:', client [ 1 ] [ 0 ] # Create our Queue: clientPool = Queue.Queue ( 0 ) # Start two threads: for x in xrange ( 2 ): ClientThread().start() # Set up the server: server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) server.bind ( ( '', 2727 ) ) server.listen ( 5 ) # Have the server serve "forever": while True: clientPool.put ( server.accept() ) </code></pre>
2
2009-08-04T13:08:57Z
1,227,473
<p>Threads don't have their own namespace. <code>pickledList</code> is defined as a global, so it is accessible to the object. Technically it should have had a <code>global pickledList</code> at the top of the function to make that clear, but it's not always needed.</p> <p><strong>EDIT</strong></p> <p>By make it clear, I mean "make it clear to a <strong>human</strong>." </p>
-2
2009-08-04T13:12:42Z
[ "python", "multithreading" ]
Soaplib functions with default arguments
1,227,547
<p>I have to write soaplib method, that has many arguments. The idea is that the user should able able to choose, which arguments he wants to provide. Is that even possible?</p> <p>I know it is possible in python generally, but there is an error, when i try to set it up like normal python method with default arguments.</p>
0
2009-08-04T13:30:17Z
1,331,676
<p>Create complex type</p> <pre><code>class Parameters(ClassSerializer): class types: param1 = primitive.String param2 = primitive.String param3 = primitive.String ... @soapmethod(Parameters, _returns=primitive.String, _outVariableName='return') def soSomething(self, parameters): if parameters.param1 and parameters.param1 != "": # or something like this # ... elif ... </code></pre>
0
2009-08-26T00:10:20Z
[ "python", "soap", "default-value" ]
python ctype recursive structures
1,228,158
<p>I've developped a DLL for a driver in C. I wrote a test program in C++ and the DLL works fine.</p> <p>Now I'd like to interract with this DLL using Python. I've successfully hidden most of the user defined C structures but there is one point where I have to use C structures. I'm rather new to python so I may get things wrong.</p> <p>My approach is to redefine a few structures in python using ctype then pass the variable to my DLL. However in these class I have a custom linked list which contains recursive types as follow</p> <pre><code>class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", c_char_p), ("work_count", c_ushort), ("next_command", EthercatDatagram)] </code></pre> <p>This fails, because inside EthercatDatagram, EthercatDatagram is not already defined so the parser returns an error. </p> <p>How should I represent this linked list in python so that my DLL understands it correctly?</p>
7
2009-08-04T15:25:03Z
1,228,204
<p>You'll have to access <code>_fields_</code> statically after you've created it.</p> <pre><code>class EthercatDatagram(Structure) _fields_ = [...] EthercatDatagram._fields_.append(("next_command", EthercatDatagram)) </code></pre>
-1
2009-08-04T15:33:59Z
[ "python", "dll", "recursion", "structure", "ctypes" ]
python ctype recursive structures
1,228,158
<p>I've developped a DLL for a driver in C. I wrote a test program in C++ and the DLL works fine.</p> <p>Now I'd like to interract with this DLL using Python. I've successfully hidden most of the user defined C structures but there is one point where I have to use C structures. I'm rather new to python so I may get things wrong.</p> <p>My approach is to redefine a few structures in python using ctype then pass the variable to my DLL. However in these class I have a custom linked list which contains recursive types as follow</p> <pre><code>class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", c_char_p), ("work_count", c_ushort), ("next_command", EthercatDatagram)] </code></pre> <p>This fails, because inside EthercatDatagram, EthercatDatagram is not already defined so the parser returns an error. </p> <p>How should I represent this linked list in python so that my DLL understands it correctly?</p>
7
2009-08-04T15:25:03Z
1,228,447
<p>You almost certainly want to declare next_command as a pointer. Having a structure that contains itself isn't possible (in any language).</p> <p>I think this is what you want:</p> <pre><code>class EthercatDatagram(Structure): pass EthercatDatagram._fields_ = [ ("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", c_char_p), ("work_count", c_ushort), ("next_command", POINTER(EthercatDatagram))] </code></pre>
14
2009-08-04T16:12:55Z
[ "python", "dll", "recursion", "structure", "ctypes" ]
python ctype recursive structures
1,228,158
<p>I've developped a DLL for a driver in C. I wrote a test program in C++ and the DLL works fine.</p> <p>Now I'd like to interract with this DLL using Python. I've successfully hidden most of the user defined C structures but there is one point where I have to use C structures. I'm rather new to python so I may get things wrong.</p> <p>My approach is to redefine a few structures in python using ctype then pass the variable to my DLL. However in these class I have a custom linked list which contains recursive types as follow</p> <pre><code>class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", c_char_p), ("work_count", c_ushort), ("next_command", EthercatDatagram)] </code></pre> <p>This fails, because inside EthercatDatagram, EthercatDatagram is not already defined so the parser returns an error. </p> <p>How should I represent this linked list in python so that my DLL understands it correctly?</p>
7
2009-08-04T15:25:03Z
17,833,687
<p>The reason why </p> <pre><code>EthercatDatagram._fields_.append(("next_command", EthercatDatagram)) </code></pre> <p>does not work is that the machinery that creates the descriptor objects (see the source of the <a href="http://hg.python.org/cpython/file/tip/Modules/_ctypes/_ctypes.c" rel="nofollow"><code>PyCStructType_setattro</code></a> function) for accessing the <code>next_command</code> attribute is activated <em>only upon assignment</em> to the <code>_fields_</code> attribute of the class. Merely appending the new field to the list goes completely unnoticed.</p> <p>To avoid this pitfall, use always a tuple (and not a list) as the value of the <code>_fields_</code> attribute: that will make it clear that you have to assign a new value to the attribute and not modify it in place.</p>
0
2013-07-24T12:11:36Z
[ "python", "dll", "recursion", "structure", "ctypes" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
1,228,327
<p>Python strings are immutable, you change them by making a copy.<br /> The easiest way to do what you want is probably.</p> <pre><code>text = "Z" + text[1:] </code></pre> <p>The text[1:] return the string in text from position 1 to the end, positions count from 0 so '1' is the second character.</p> <p>edit: You can use the same string slicing technique for any part of the string</p> <pre><code>text = text[:1] + "Z" + text[2:] </code></pre> <p>Or if the letter only appears once you can use the search and replace technique suggested below</p>
16
2009-08-04T15:52:27Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
1,228,332
<pre><code>new = text[:1] + 'Z' + text[2:] </code></pre>
71
2009-08-04T15:53:00Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
1,228,597
<p>Don't modify strings.</p> <p>Work with them as lists; turn them into strings only when needed.</p> <pre><code>&gt;&gt;&gt; s = list("Hello zorld") &gt;&gt;&gt; s ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd'] &gt;&gt;&gt; s[6] = 'W' &gt;&gt;&gt; s ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] &gt;&gt;&gt; "".join(s) 'Hello World' </code></pre> <p>Python strings are immutable (i.e. they can't be modified). There are <a href="http://effbot.org/pyfaq/why-are-python-strings-immutable.htm">a lot</a> of reasons for this. Use lists until you have no choice, only then turn them into strings.</p>
246
2009-08-04T16:41:07Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
1,229,342
<p>Like other people have said, generally Python strings are supposed to be immutable.</p> <p>However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.</p> <p>Here is an example where I use the technique to clear a string.</p> <p><a href="http://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525">http://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525</a></p> <p>I mention this for the sake of completeness, and this should be your last resort as it is hackish.</p>
3
2009-08-04T19:08:14Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
8,534,982
<p>This code is not mine. I couldn't recall the site form where, I took it. Interestingly, you can use this to replace one character or more with one or more charectors. Though this reply is very late, novices like me (anytime) might find it useful.</p> <h1>Change Text function.</h1> <pre><code>mytext = 'Hello Zorld' mytext = mytext.replace('Z', 'W') print mytext, </code></pre>
-4
2011-12-16T13:39:14Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
21,459,305
<p>Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings):</p> <pre><code>s = "abcdefg" b_s = bytearray(s) b_s[1] = "Z" s = str(b_s) print s aZcdefg </code></pre> <p>edit: Changed str to s</p> <p>edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with unicode.</p>
7
2014-01-30T14:34:49Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
22,149,018
<h2>Fastest method?</h2> <p>There are two ways. For the speed seekers I recommend 'Method 2' </p> <p><strong>Method 1</strong></p> <p>Given by this <a href="http://stackoverflow.com/a/1228597/2571620">answer</a></p> <pre><code>text = 'abcdefg' new = list(text) new[6] = 'W' ''.join(new) </code></pre> <p>Which is pretty slow compared to 'Method 2'</p> <pre><code>timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000) 1.7008259296417236 </code></pre> <p><strong>Method 2 (FAST METHOD)</strong></p> <p>Given by this <a href="http://stackoverflow.com/a/1228332/2571620">answer</a></p> <pre><code>text = 'abcdefg' text = text[:1] + 'Z' + text[2:] </code></pre> <p>Which is much faster:</p> <pre><code>timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000) 0.27298116683959961 </code></pre>
52
2014-03-03T14:15:24Z
[ "python" ]
Change one character in a string in Python?
1,228,299
<p>What is the easiest way in Python to replace a character in a string like: </p> <pre><code>text = "abcdefg"; text[1] = "Z"; ^ </code></pre>
172
2009-08-04T15:48:39Z
33,836,145
<p>Actually, with strings, you can do something like this:</p> <pre><code>oldStr = 'Hello World!' newStr = '' for i in oldStr: if 'a' &lt; i &lt; 'z': newStr += chr(ord(i)-32) else: newStr += i print(newStr) 'HELLO WORLD!' </code></pre> <p>Basically, I'm "adding"+"strings" together into a new string :).</p>
0
2015-11-20T21:12:00Z
[ "python" ]
How to scale matplotlib subplot heights individually
1,228,315
<p>Using matplotlib/pylab....</p> <p>How do I plot 5 heatmaps as subplots which have the same number of columns but different row counts? In other words, I need each subplot's height to be scaled differently.</p> <p>Perhaps an image better illustrates the problem...</p> <p><img src="http://img98.imageshack.us/img98/5853/heatmap.png" alt="alt text" /></p> <p>I need the data points to all be square, AND the columns to be lined up, so the heights have to change according to how many rows each subplot has.</p> <p>I've tried:</p> <ol> <li>The scaling options mentioned <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.axis">here</a>. The above plot is with <code>axis('tight')</code>.</li> <li>The y-axis scaling solutions mentioned <a href="http://stackoverflow.com/questions/401787">here</a>.</li> </ol> <p>... but no luck so far. </p>
5
2009-08-04T15:50:47Z
1,228,346
<p>I haven't tried this for any of my own work, but perhaps the <a href="http://matplotlib.sourceforge.net/mpl%5Ftoolkits/axes%5Fgrid/users/overview.html#axesgrid" rel="nofollow">matplotlib AxesGrid toolkit</a> might be what you are looking for.</p>
4
2009-08-04T15:54:50Z
[ "python", "matplotlib" ]
How to scale matplotlib subplot heights individually
1,228,315
<p>Using matplotlib/pylab....</p> <p>How do I plot 5 heatmaps as subplots which have the same number of columns but different row counts? In other words, I need each subplot's height to be scaled differently.</p> <p>Perhaps an image better illustrates the problem...</p> <p><img src="http://img98.imageshack.us/img98/5853/heatmap.png" alt="alt text" /></p> <p>I need the data points to all be square, AND the columns to be lined up, so the heights have to change according to how many rows each subplot has.</p> <p>I've tried:</p> <ol> <li>The scaling options mentioned <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.axis">here</a>. The above plot is with <code>axis('tight')</code>.</li> <li>The y-axis scaling solutions mentioned <a href="http://stackoverflow.com/questions/401787">here</a>.</li> </ol> <p>... but no luck so far. </p>
5
2009-08-04T15:50:47Z
1,241,093
<p>Don't use <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.subplot" rel="nofollow">subplot</a> but <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.axes" rel="nofollow">axes</a> to create your subplots - the latter allows arbitrary positioning of the subplot.</p>
2
2009-08-06T20:06:59Z
[ "python", "matplotlib" ]
Problem with hash function: hash(1) == hash(1.0)
1,228,475
<p>I have an instance of <code>dict</code> with <code>int</code>s, <code>float</code>s, <code>string</code>s as keys, but the problem is when there are <code>a</code> as <code>int</code> and <code>b</code> as <code>float</code>, and <code>float(a) == b</code>, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values.</p> <p>Example:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1.0' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre> <p>What I need is:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre>
1
2009-08-04T16:17:40Z
1,228,508
<p>This doesn't solve your problem, but from <a href="http://docs.python.org/library/numbers.html#notes-for-type-implementors" rel="nofollow">Python 2.6's number documentation</a>:</p> <blockquote> <p>Implementors should be careful to make equal numbers equal and hash them to the same values. </p> </blockquote> <p>Can you get by with making the float 1.00001, or something like that?</p>
1
2009-08-04T16:22:45Z
[ "python", "hash", "dictionary" ]
Problem with hash function: hash(1) == hash(1.0)
1,228,475
<p>I have an instance of <code>dict</code> with <code>int</code>s, <code>float</code>s, <code>string</code>s as keys, but the problem is when there are <code>a</code> as <code>int</code> and <code>b</code> as <code>float</code>, and <code>float(a) == b</code>, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values.</p> <p>Example:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1.0' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre> <p>What I need is:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre>
1
2009-08-04T16:17:40Z
1,228,517
<p>Using a float as a dictionary key is 'unwise' it's impossible to guarantee that two floats will evaluate to the same value.</p> <p>The best thing is to multiply the keys to a predetermined number of decimal places and use that integer as the key.</p> <p>edit: Sorry it seems you don't want a dict with real number keys, you simply want to format an output based on the type of input?</p>
6
2009-08-04T16:23:36Z
[ "python", "hash", "dictionary" ]
Problem with hash function: hash(1) == hash(1.0)
1,228,475
<p>I have an instance of <code>dict</code> with <code>int</code>s, <code>float</code>s, <code>string</code>s as keys, but the problem is when there are <code>a</code> as <code>int</code> and <code>b</code> as <code>float</code>, and <code>float(a) == b</code>, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values.</p> <p>Example:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1.0' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre> <p>What I need is:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre>
1
2009-08-04T16:17:40Z
1,228,643
<p>Since <code>1 == 1.0</code>, it would horribly break the semantics of hashing (and therefore dicts and sets) if it were the case that <code>hash(1) != hash(1.0)</code>. More generally, it must ALWAYS be the case that <code>x == y</code> implies <code>hash(x) == hash(y)</code>, for ALL <code>x</code> and <code>y</code> (there is of course no condition requiring the reverse implication to hold).</p> <p>So your dict <code>d</code> has just three entries, as the second one you've written in the dict display overrides the first one. If you need to force equality to hold only between identical types (as opposed to numbers more generally), you need a wrapper such as:</p> <pre><code>class W(object): def __init__(self, x): self.x = x self.t = type(x) def __eq__(self, other): t = type(other) if t != type(self): return False return self.x == other.x and self.t == other.t def __hash__(self): return hash(self.x) ^ hash(self.t) def __getattr__(self, name): return getattr(self.x, name) </code></pre> <p>Depending on your exact needs you may also want to override other methods (other comparison methods such as <code>__cmp__</code> or <code>__le__</code>, arithmetic ones, <code>__repr__</code>, etc etc). At any rate, this will allow you to build a dict similar to what you require, just use as keys <code>W(1)</code> instead of bare <code>1</code> and <code>W(1.0)</code> instead of bare <code>1.0</code> (you may not need to wrap non-numbers, although there's no harm if you choose to do so, and it may ease retrieval from your dict if all keys are equally wrapped).</p>
7
2009-08-04T16:47:55Z
[ "python", "hash", "dictionary" ]
Problem with hash function: hash(1) == hash(1.0)
1,228,475
<p>I have an instance of <code>dict</code> with <code>int</code>s, <code>float</code>s, <code>string</code>s as keys, but the problem is when there are <code>a</code> as <code>int</code> and <code>b</code> as <code>float</code>, and <code>float(a) == b</code>, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values.</p> <p>Example:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1.0' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre> <p>What I need is:</p> <pre><code>d = {1:'1', 1.0:'1.0', '1':1, '1.0':1.0} d[1] == '1' d[1.0] == '1.0' d['1'] == 1 d['1.0'] == 1.0 </code></pre>
1
2009-08-04T16:17:40Z
1,228,957
<p>If you really just need to know the difference, perhaps do something hackish like:</p> <pre><code>x = '1' y = 1 hash(type(x) + x) != hash(type(y) + y) </code></pre>
2
2009-08-04T17:47:43Z
[ "python", "hash", "dictionary" ]
Retrieving the return value of a Python script
1,228,550
<p>I have an external C# program which executes a Python script using the <code>Process</code> class.</p> <p>My script returns a numerical code and I want to retrieve it from my C# program. Is this possible?</p> <p>The problem is, I'm getting the return code of <code>python.exe</code> instead of the code returned from my script. (For example, <code>3</code>.)</p>
2
2009-08-04T16:31:22Z
1,228,569
<p>The interpreter does not return the value at the top of Python's stack, unless you do this:</p> <pre><code>if __name__ == "__main__": sys.exit(main()) </code></pre> <p>or if you make a call to <code>sys.exit</code> elsewhere.</p> <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=4829">Here's a lot more documentation on this issue.</a></p>
7
2009-08-04T16:35:14Z
[ "c#", "python" ]
Globally-scoped variable: can its value change before it is picked up by the thread?
1,228,655
<p>In the following code, you see that <code>pickledList</code> is being used by the thread and is set in the global scope. </p> <p>If the variable that the thread was using was set dynamically somewhere down below in that final while loop, is it possible that its value could change before the thread got to use it? How can I set a value dynamically in the loop, send it off to the thread and <strong>make sure</strong> that its value doesn't change before the thread gets to use it?</p> <pre><code>import pickle import Queue import socket import threading someList = [ 1, 2, 7, 9, 0 ] pickledList = pickle.dumps ( someList ) class ClientThread ( threading.Thread ): def run ( self ): while True: client = clientPool.get() if client != None: print 'Received connection:', client [ 1 ] [ 0 ] client [ 0 ].send ( pickledList ) for x in xrange ( 10 ): print client [ 0 ].recv ( 1024 ) client [ 0 ].close() print 'Closed connection:', client [ 1 ] [ 0 ] clientPool = Queue.Queue ( 0 ) for x in xrange ( 2 ): ClientThread().start() server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) server.bind ( ( '', 2727 ) ) server.listen ( 5 ) while True: clientPool.put ( server.accept() ) </code></pre> <p>EDIT: </p> <p>Here is a better example of my problem. If you run this, sometimes the values change before the thread can output them, causing some to be skipped:</p> <pre><code>from threading import Thread class t ( Thread ): def run(self): print "(from thread) ", print i for i in range(1, 50): print i t().start() </code></pre> <p>How can I pass the value in <code>i</code> to the thread in such a way that its no longer bound to the variable, so that if the value stored in <code>i</code> changes, the value the thread is working with is not affected.</p>
3
2009-08-04T16:49:40Z
1,228,963
<p>Option 1: you can pass arguments into each Thread when it is instantiated:</p> <pre><code>ClientThread(arg1, arg2, kwarg1="three times!").start() </code></pre> <p>in which case your <code>run</code> method will be called:</p> <pre><code>run(arg1, arg2, kwarg1="three times!") </code></pre> <p>by the Thread instance when you call <code>start()</code>. If you need to pass mutable objects (dicts, lists, instances) to the function, you must be sure to re-assign the global variable, <strong>not</strong> edit it in place.</p> <p>Option 2: you can set an instance variable on your <code>ClientThread</code> objects:</p> <pre><code>myThread.setMyAttribute('new value') </code></pre> <p>With option 2 you need to be wary of race conditions etc. depending on what the method does. Using <code>Lock</code>s whenever you're writing or reading data from/to a thread is a good idea.</p> <p>Option 3: grab the global when <code>run</code> is first called and store a copy locally</p> <pre><code>run(self): localVar = globalVar # only for immutable types localList = globalList[:] # copy of a list localDict = globalDict.copy() # Warning! Shallow copy only! </code></pre> <p>Option 1 is the right way to go if the value a thread is given never needs to change during its lifetime, Option 2 if the value does need to change. Option 3 is a hack.</p> <p>With regard to generally passing variables/values around, you must remember with Python that immutable objects (strings, numbers, tuples) are passed <strong>by value</strong> and mutable objects (dicts, lists, class instances) are passed <strong>by reference</strong>.</p> <p>Consequently, altering a string, number or tuple will not affect any instances previously passed that variable, however altering a dict, list or instance will do. Re-assigning a variable to a different object will not affect anything previously given the old value.</p> <p>Globals certainly shouldn't be used for values that may change (if at all). Basically your example is doing it the wrong way.</p>
3
2009-08-04T17:49:05Z
[ "python", "multithreading", "scope" ]
Problem with Twisted python - sending binary data
1,228,722
<p>What I'm trying to do is fairly simple: send a file from client to server. First, the client sends information about the file - the size of it that is. Then it sends the actual file.</p> <p>This is what I've done so far:</p> <p>Server.py</p> <pre><code>from twisted.internet import reactor, protocol from twisted.protocols.basic import LineReceiver import pickle import sys class Echo(LineReceiver): def connectionMade(self): self.factory.clients.append(self) self.setRawMode() def connectionLost(self, reason): self.factory.clients.remove(self) def lineReceived(self, data): print "line", data def rawDataReceived(self, data): try: obj = pickle.loads(data) print obj except: print data #self.transport.write("wa2") def main(): """This runs the protocol on port 8000""" factory = protocol.ServerFactory() factory.protocol = Echo factory.clients = [] reactor.listenTCP(8000,factory) reactor.run() # this only runs if the module was *not* imported if __name__ == '__main__': main() </code></pre> <p>Client.py</p> <pre><code>import pickle from twisted.internet import reactor, protocol import time import os.path from twisted.protocols.basic import LineReceiver class EchoClient(LineReceiver): def connectionMade(self): file = "some file that is a couple of megs" filesize = os.path.getsize(file) self.sendLine(pickle.dumps({"size":filesize})) f = open(file, "rb") contents = f.read() print contents[:20] self.sendLine(contents[:20]) f.close() # self.sendLine("hej") # self.sendLine("wa") def connectionLost(self, reason): print "connection lost" class EchoFactory(protocol.ClientFactory): protocol = EchoClient def clientConnectionFailed(self, connector, reason): print "Connection failed - goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "Connection lost - goodbye!" reactor.stop() # this connects the protocol to a server runing on port 8000 def main(): f = EchoFactory() reactor.connectTCP("localhost", 8000, f) reactor.run() # this only runs if the module was *not* imported if __name__ == '__main__': main() </code></pre> <p>The server will only output the deserialized object:</p> <p>{'size': 183574528L}</p> <p>How come? What happend to the 20 chars from the file I wanted to send?</p> <p>If use the "hej" and "wa" sends instead, I will get them both (in the same message, not twice).</p> <p>Somebody?</p>
5
2009-08-04T17:02:17Z
1,228,952
<p>You've set your server to raw mode with setRawMode(), so the callback rawDataReceived is being called with the incoming data (not lineReceived). If you print the data you receive in rawDataReceived, you see everything including the file content, but as you call pickle to deserialize the data, it's being ignored.</p> <p>Either you change the way you send data to the server (I would suggest the netstring format) or you pass the content inside the pickle serialized object, and do this in one call.</p> <pre><code>self.sendLine(pickle.dumps({"size":filesize, 'content': contents[:20]})) </code></pre>
8
2009-08-04T17:46:56Z
[ "python", "file", "twisted", "send" ]
Python weakref callbacks and __del__ execution order
1,228,791
<p>In Python, is there a way to call a function after an object is finalized?</p> <p>I thought the callback in a weakref would do it, but it appears a weakref's callback is called once the object is garbage collected, but before the objects <code>__del__</code> method is called. This seems contrary to <a href="http://svn.python.org/projects/python/trunk/Modules/gc_weakref.txt" rel="nofollow">the notes on weakrefs and garbage collection in the Python trunk</a>. Here's an example.</p> <pre><code>import sys import weakref class Spam(object) : def __init__(self, name) : self.name = name def __del__(self) : sys.stdout.write("Deleting Spam:%s\n" % self.name) sys.stdout.flush() def cleaner(reference) : sys.stdout.write("In callback with reference %s\n" % reference) sys.stdout.flush() spam = Spam("first") wk_spam = weakref.ref(spam, cleaner) del spam </code></pre> <p>The output I get is</p> <pre><code>$ python weakref_test.py In callback with reference &lt;weakref at 0xc760a8; dead&gt; Deleting Spam:first </code></pre> <p>Is there some other conventional way to do what I want? Can I somehow force the finalization in my callback?</p>
2
2009-08-04T17:18:12Z
1,228,916
<p>If "do what you want" means "run code when a resource leaves the context" ( instead of, for example, "abuse the garbage collector to do stuff" ), you're looking in the wrong direction. Python abtracted that whole idea as <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">context-managers</a>, used with the <code>with</code> statement.</p> <pre><code>from __future__ import with_statement import sys class Spam(object): def __init__(self, name): self.name = name def __enter__(self): sys.stdout.write("Entering Spam:%s\n" % self.name) sys.stdout.flush() def __exit__(self, type, value, traceback): sys.stdout.write("Lets clean up Spam:%s\n" % self.name) if type is None: sys.stdout.write("Leaving Spam:%s in peace\n" % self.name) return else: sys.stdout.write("Leaving Spam:%s with Exception:%r\n" % (self.name, value)) with Spam("first") as spam: pass with Spam("2nd") as spam: raise Exception("Oh No!") </code></pre> <p>gives:</p> <pre><code>Entering Spam:first Lets clean up Spam:first Leaving Spam:first in peace Entering Spam:2nd Lets clean up Spam:2nd Leaving Spam:2nd with Exception:Exception('Oh No!',) Traceback (most recent call last): File "asd.py", line 24, in &lt;module&gt; raise Exception("Oh No!") Exception: Oh No! </code></pre>
2
2009-08-04T17:40:40Z
[ "python", "weak-references" ]
Python weakref callbacks and __del__ execution order
1,228,791
<p>In Python, is there a way to call a function after an object is finalized?</p> <p>I thought the callback in a weakref would do it, but it appears a weakref's callback is called once the object is garbage collected, but before the objects <code>__del__</code> method is called. This seems contrary to <a href="http://svn.python.org/projects/python/trunk/Modules/gc_weakref.txt" rel="nofollow">the notes on weakrefs and garbage collection in the Python trunk</a>. Here's an example.</p> <pre><code>import sys import weakref class Spam(object) : def __init__(self, name) : self.name = name def __del__(self) : sys.stdout.write("Deleting Spam:%s\n" % self.name) sys.stdout.flush() def cleaner(reference) : sys.stdout.write("In callback with reference %s\n" % reference) sys.stdout.flush() spam = Spam("first") wk_spam = weakref.ref(spam, cleaner) del spam </code></pre> <p>The output I get is</p> <pre><code>$ python weakref_test.py In callback with reference &lt;weakref at 0xc760a8; dead&gt; Deleting Spam:first </code></pre> <p>Is there some other conventional way to do what I want? Can I somehow force the finalization in my callback?</p>
2
2009-08-04T17:18:12Z
1,229,565
<p>Here is a solution that uses a serialized garbage loop on another thread. Its probably the closest solution you'll get.</p> <pre><code>import sys from threading import Thread from Queue import Queue import weakref alive = weakref.WeakValueDictionary() dump = Queue() def garbageloop(): while True: f = dump.get() f() garbage_thread = Thread(target=garbageloop) garbage_thread.daemon = True garbage_thread.start() class Spam(object) : def __init__(self, name) : self.name = name alive[id(self)] = self def __del__(self) : sys.stdout.write("Deleting Spam:%s\n" % self.name) sys.stdout.flush() dump.put(lambda:cleaner(id(self))) def cleaner(address): if address in alive: sys.stdout.write("Object was still alive\n") else: sys.stdout.write("Object is dead\n") sys.stdout.flush() spam = Spam("first") del spam </code></pre>
0
2009-08-04T19:52:40Z
[ "python", "weak-references" ]
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
1,229,084
<p>Unpickle from file when program loads, modify as a normal dictionary in memory while program is running, pickle to file when program exits? Not sure exactly what more you're asking for here.</p>
4
2009-08-04T18:13:07Z
[ "python", "dictionary", "persistence", "object-persistence" ]
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
1,229,099
<p>If your keys (not necessarily the values) are strings, the <a href="http://docs.python.org/library/shelve.html">shelve</a> standard library module does what you want pretty seamlessly.</p>
15
2009-08-04T18:17:27Z
[ "python", "dictionary", "persistence", "object-persistence" ]
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
1,229,114
<p>Assuming the keys and values have working implementations of <code>repr</code>, one solution is that you save the string representation of the dictionary (<code>repr(dict)</code>) to file. YOu can load it using the <code>eval</code> function (<code>eval(inputstring)</code>). There are two main disadvantages of this technique:</p> <p>1) Is will not work with types that have an unuseable implementation of repr (or may even seem to work, but fail). You'll need to pay at least some attention to what is going on.</p> <p>2) Your file-load mechanism is basically straight-out executing Python code. Not great for security unless you fully control the input.</p> <p>It has 1 advantage: Absurdly easy to do.</p>
1
2009-08-04T18:24:22Z
[ "python", "dictionary", "persistence", "object-persistence" ]
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
1,229,320
<p>pickling has one disadvantage. it can be expensive if your dictionary has to be read and written frequently from disk and it's large. pickle dumps the stuff down (whole). unpickle gets the stuff up (as a whole). </p> <p>if you have to handle small dicts, pickle is ok. If you are going to work with something more complex, go for berkelydb. It is basically made to store key:value pairs.</p>
0
2009-08-04T19:03:14Z
[ "python", "dictionary", "persistence", "object-persistence" ]
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
1,229,346
<p>My favorite method (which does not use standard python dictionary functions): Read/write YAML files using <a href="http://pyyaml.org/" rel="nofollow">PyYaml</a>. <a href="http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python/636138#636138">See this answer for details</a>, summarized here:</p> <p>Create a YAML file, "employment.yml":</p> <pre><code>new jersey: mercer county: pumbers: 3 programmers: 81 middlesex county: salesmen: 62 programmers: 81 new york: queens county: plumbers: 9 salesmen: 36 </code></pre> <p>Step 3: Read it in Python</p> <pre><code>import yaml file_handle = open("employment.yml") my__dictionary = yaml.safe_load(file_handle) file_handle.close() </code></pre> <p>and now my__dictionary has all the values. If you needed to do this on the fly, create a string containing YAML and parse it wth yaml.safe_load.</p>
1
2009-08-04T19:09:22Z
[ "python", "dictionary", "persistence", "object-persistence" ]
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
12,058,834
<p>If using only strings as keys (as allowed by the <a href="http://docs.python.org/library/shelve.html" rel="nofollow"><code>shelve</code></a> module) is not enough, the <a href="http://stackoverflow.com/questions/1229068/with-python-can-i-keep-a-persistent-dictionary-and-modify-it">FileDict</a> might be a good way to solve this problem.</p>
0
2012-08-21T16:02:21Z
[ "python", "dictionary", "persistence", "object-persistence" ]