title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Is there a cross-platform python low-level API to capture or generate keyboard events?
676,713
<p>I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program asks me for my email address I just need to type Ctrl-@.</p> <p>I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.</p> <p>Thanks for your help.</p> <p>Note: there is <a href="http://stackoverflow.com/questions/310576/low-level-keyboard-input-on-windows">a similar question</a> but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.</p> <p>Edit: I should probably add a disclaimer here: I do <em>not</em> want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)</p>
11
2009-03-24T09:48:25Z
681,571
<p>On linux, you might want to have a look at <a href="http://pykeylogger.wiki.sourceforge.net/" rel="nofollow">pykeylogger</a>. For some strange reason, reading from /dev/input/.... doesn't always work when X is running. For example it doesn't work on ubuntu 8.10. Pykeylogger uses xlib, which works exactly when the other way doesn't. I'm still looking into this, so if you find a simpler way of doing this, please tell me.</p>
0
2009-03-25T13:23:18Z
[ "python", "cross-platform", "keyboard-events", "low-level-api" ]
Is there a cross-platform python low-level API to capture or generate keyboard events?
676,713
<p>I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program asks me for my email address I just need to type Ctrl-@.</p> <p>I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.</p> <p>Thanks for your help.</p> <p>Note: there is <a href="http://stackoverflow.com/questions/310576/low-level-keyboard-input-on-windows">a similar question</a> but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.</p> <p>Edit: I should probably add a disclaimer here: I do <em>not</em> want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)</p>
11
2009-03-24T09:48:25Z
1,189,608
<p>As the guy that wrote the original pykeylogger linux port, I can say there isn't really a cross platform one. Essentially I rewrote the pyhook API for keyboard events to capture from the xserver itself, using the record extension. Of course, this assumes the record extension is there, loaded into the x server.</p> <p>From there, it's essentially just detecting if you're on windows, or linux, and then loading the correct module for the OS. Everything else should be identical.</p> <p>Take a look at the pykeylogger source, in pyxhook.py for the class and implimentation. Otherwise, just load that module, or pyhook instead, depending on OS.</p>
5
2009-07-27T17:44:51Z
[ "python", "cross-platform", "keyboard-events", "low-level-api" ]
Is there a cross-platform python low-level API to capture or generate keyboard events?
676,713
<p>I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program asks me for my email address I just need to type Ctrl-@.</p> <p>I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.</p> <p>Thanks for your help.</p> <p>Note: there is <a href="http://stackoverflow.com/questions/310576/low-level-keyboard-input-on-windows">a similar question</a> but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.</p> <p>Edit: I should probably add a disclaimer here: I do <em>not</em> want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)</p>
11
2009-03-24T09:48:25Z
1,666,022
<p>I've made a few tests on Ubuntu 9.10. pykeylogger doesn't seems to be working. I've tryied to change the /etc/X11/xorg.conf in order to allow module to be loaded but in that specific version of ubuntu there is no xorg.conf. So, in my opiniion pykelogger is NOT working on ubuntu 9.10 !!</p>
1
2009-11-03T08:44:38Z
[ "python", "cross-platform", "keyboard-events", "low-level-api" ]
Is there a cross-platform python low-level API to capture or generate keyboard events?
676,713
<p>I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program asks me for my email address I just need to type Ctrl-@.</p> <p>I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.</p> <p>Thanks for your help.</p> <p>Note: there is <a href="http://stackoverflow.com/questions/310576/low-level-keyboard-input-on-windows">a similar question</a> but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.</p> <p>Edit: I should probably add a disclaimer here: I do <em>not</em> want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)</p>
11
2009-03-24T09:48:25Z
1,802,717
<p>Under Linux it's possible to do this quite easily with Xlib. See this page for details:</p> <p><a href="http://www.larsen-b.com/Article/184.html" rel="nofollow">http://www.larsen-b.com/Article/184.html</a></p>
0
2009-11-26T09:59:02Z
[ "python", "cross-platform", "keyboard-events", "low-level-api" ]
Intercepting changes of attributes in classes within a class - Python
676,826
<p>I have been messing around with pygame and python and I want to be able to call a function when an attribute of my class has changed. My current solution being:</p> <pre><code>class ExampleClass(parentClass): def __init__(self): self.rect = pygame.rect.Rect(0,0,100,100) def __setattr__(self, name, value): parentClass.__setattr__(self,name,value) dofancystuff() Firstclass = ExampleClass() </code></pre> <p>This works fine and dofancystuff is called when I change the rect value with <code>Firsclass.rect = pygame.rect.Rect(0,0,100,100)</code>. However if I say <code>Firstclass.rect.bottom = 3</code>. <code>__setattr__</code> and there for dofancystuff is not called.</p> <p>So my question I guess is how can I intercept any change to an attribute of a subclass?</p> <p>edit: Also If I am going about this the wrong way please do tell I'm not very knowledgable when it comes to python.</p>
2
2009-03-24T10:34:25Z
676,843
<p>You could try <code>__getattr__</code>, which should be called on <code>Firstclass.rect</code>.</p> <p>But do this instead: Create a separate class (subclass of <code>pygame.rect</code>?) for <code>ExampleClass.rect</code>. Implement <code>__setattr__</code> in that class. Now you will be told about anything that gets set in your <code>rect</code> member for <code>ExampleClass</code>. You can still implement <code>__setattr__</code> in <code>ExampleClass</code> (and <em>should</em>), only now make sure you instantiate a version of your own <code>rect</code> class...</p> <p>BTW: Don't call your objects <code>Firstclass</code>, as then it looks like a class as opposed to an object...</p>
1
2009-03-24T10:39:20Z
[ "python", "class", "attributes", "subclass", "pygame" ]
Intercepting changes of attributes in classes within a class - Python
676,826
<p>I have been messing around with pygame and python and I want to be able to call a function when an attribute of my class has changed. My current solution being:</p> <pre><code>class ExampleClass(parentClass): def __init__(self): self.rect = pygame.rect.Rect(0,0,100,100) def __setattr__(self, name, value): parentClass.__setattr__(self,name,value) dofancystuff() Firstclass = ExampleClass() </code></pre> <p>This works fine and dofancystuff is called when I change the rect value with <code>Firsclass.rect = pygame.rect.Rect(0,0,100,100)</code>. However if I say <code>Firstclass.rect.bottom = 3</code>. <code>__setattr__</code> and there for dofancystuff is not called.</p> <p>So my question I guess is how can I intercept any change to an attribute of a subclass?</p> <p>edit: Also If I am going about this the wrong way please do tell I'm not very knowledgable when it comes to python.</p>
2
2009-03-24T10:34:25Z
676,872
<p>Well, the simple answer is you can't. In the case of <code>Firstclass.rect = &lt;...&gt;</code> your <code>__setattr__</code> is called. But in the case of <code>Firstclass.rect.bottom = 3</code> the <code>__setattr__</code> method of the Rect instance is called. The only solution I see, is to create a derived class of pygame.rect.Rect where you overwrite the <code>__setattr__</code> method. You can also monkey patch the Rect class, but this is discouraged for good reasons.</p>
4
2009-03-24T10:46:29Z
[ "python", "class", "attributes", "subclass", "pygame" ]
Intercepting changes of attributes in classes within a class - Python
676,826
<p>I have been messing around with pygame and python and I want to be able to call a function when an attribute of my class has changed. My current solution being:</p> <pre><code>class ExampleClass(parentClass): def __init__(self): self.rect = pygame.rect.Rect(0,0,100,100) def __setattr__(self, name, value): parentClass.__setattr__(self,name,value) dofancystuff() Firstclass = ExampleClass() </code></pre> <p>This works fine and dofancystuff is called when I change the rect value with <code>Firsclass.rect = pygame.rect.Rect(0,0,100,100)</code>. However if I say <code>Firstclass.rect.bottom = 3</code>. <code>__setattr__</code> and there for dofancystuff is not called.</p> <p>So my question I guess is how can I intercept any change to an attribute of a subclass?</p> <p>edit: Also If I am going about this the wrong way please do tell I'm not very knowledgable when it comes to python.</p>
2
2009-03-24T10:34:25Z
1,112,632
<p>I think the reason why you have this difficulty deserves a little more information than is provided by the other answers.</p> <p>The problem is, when you do:</p> <pre><code>myObject.attribute.thing = value </code></pre> <p>You're not assigning a value to attribute. The code is equivalent to this:</p> <pre><code>anAttribute = myObject.attribute anAttribute.thing = value </code></pre> <p>As it's seen by myObject, all you're doing it getting the attribute; you're not setting the attribute.</p> <p>Making subclasses of your attributes that you control, and can define __setattr__ for is one solution.</p> <p>An alternative solution, that may make sense if you have lots of attributes of different types and don't want to make lots of individual subclasses for all of them, is to override __getattribute__ or __getattr__ to return a facade to the attribute that performs the relevant operations in its __setattr__ method. I've not attempted to do this myself, but I imagine that you should be able to make a simple facade class that will act as a facade for any object.</p> <p>Care would need to be taken in the choice of <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetattribute%5F%5F" rel="nofollow">__getattribute__</a> and <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetattr%5F%5F" rel="nofollow">__getattr__</a>. See the documentation linked in the previous sentence for information, but basically if __getattr__ is used, the actual attributes will have top be encapsulated/obfuscated somehow so that __getattr__ handles requests for them, and if __getattribute__ is used, it'll have to retrieve attributes via calls to a base class.</p> <p>If all you're trying to do is determine if some rects have been updated, then this is overkill.</p>
0
2009-07-11T01:07:07Z
[ "python", "class", "attributes", "subclass", "pygame" ]
Intercepting changes of attributes in classes within a class - Python
676,826
<p>I have been messing around with pygame and python and I want to be able to call a function when an attribute of my class has changed. My current solution being:</p> <pre><code>class ExampleClass(parentClass): def __init__(self): self.rect = pygame.rect.Rect(0,0,100,100) def __setattr__(self, name, value): parentClass.__setattr__(self,name,value) dofancystuff() Firstclass = ExampleClass() </code></pre> <p>This works fine and dofancystuff is called when I change the rect value with <code>Firsclass.rect = pygame.rect.Rect(0,0,100,100)</code>. However if I say <code>Firstclass.rect.bottom = 3</code>. <code>__setattr__</code> and there for dofancystuff is not called.</p> <p>So my question I guess is how can I intercept any change to an attribute of a subclass?</p> <p>edit: Also If I am going about this the wrong way please do tell I'm not very knowledgable when it comes to python.</p>
2
2009-03-24T10:34:25Z
15,865,081
<p>This isn't answering the question but it is relevant:</p> <pre><code>self.__dict__[name] = value </code></pre> <p>is probably better than </p> <pre><code>parentClass.__setattr__(self, name, value) </code></pre> <p>This is recommended by the Python documentation (setattr">http://docs.python.org/2/reference/datamodel.html?highlight=setattr#object.<strong>setattr</strong>) and makes more sense anyway in the general case since it does not assume anything about the behaviour of parentClass <strong>setattr</strong>.</p> <p>Yay for unsolicited advice four years too late!</p>
1
2013-04-07T16:56:26Z
[ "python", "class", "attributes", "subclass", "pygame" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
677,042
<p>Just open a socket between the two processes and have the editor tell all the players about the update.</p>
2
2009-03-24T11:40:26Z
[ "python", "sqlite", "notifications" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
677,066
<p><strong>Edit:</strong> I am asuming processes on the same machine.</p> <p>In my opinion there are two ways:</p> <ul> <li><p>Polling (as you mentioned), but keep it to a single value (like a table that just keeps the LastUpdateTime of other tables)</p></li> <li><p>Use whichever interprocess-communication there is available on the target platform. This could be events in Windows (e.g. in C# (I don't know in Python) the ManualResetEvent, AutoResetEvent, or a Mutex if you want to sacrifice a waiter-thread in each process), or <a href="http://www.comptechdoc.org/os/linux/programming/linux%5Fpgsignals.html" rel="nofollow">Signals</a> in Linux.</p></li> </ul>
1
2009-03-24T11:49:30Z
[ "python", "sqlite", "notifications" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
677,085
<p>A relational database is not your best first choice for this.</p> <p>Why?</p> <p>You want all of your editors to pass changes to your player. </p> <p>Your player is -- effectively -- a server for all those editors. Your player needs multiple open connections. It must listen to all those connections for changes. It must display those changes.</p> <p>If the changes are really large, you can move to a hybrid solution where the editors persist the changes <em>and</em> notify the player. </p> <p>Either way, the editors must notify they player that they have a change. It's much, much simpler than the player trying to discover changes in a database.</p> <p><hr /></p> <p>A better design is a server which accepts messages from the editors, persists them, and notifies the player. This server is neither editor nor player, but merely a broker that assures that all the messages are handled. It accepts connections from editors and players. It manages the database.</p> <p>There are two implementations. Server IS the player. Server is separate from the player. The design of server doesn't change -- only the protocol. When server is the player, then server calls the player objects directly. When server is separate from the player, then the server writes to the player's socket.</p> <p>When the player is part of the server, player objects are invoked directly when a message is received from an editor. When the player is separate, a small reader collects the messages from a socket and calls the player objects.</p> <p>The player connects to the server and then waits for a stream of information. This can either be input from the editors or references to data that the server persisted in the database.</p> <p>If your message traffic is small enough so that network latency is not a problem, editor sends all the data to the server/player. If message traffic is too large, then the editor writes to a database and sends a message with just a database FK to the server/player. </p> <p><hr /></p> <p>Please clarify "If the editor crashes while notifying, the player is permanently messed up" in your question.</p> <p>This sounds like a poor design for the player service. It can't be "permanently messed up" unless it's not getting state from the various editors. If it's getting state from the editors (but attempting to mirror that state, for example) then you should consider a design where the player simply gets state from the editor and cannot get "permanently messed up".</p>
5
2009-03-24T11:55:22Z
[ "python", "sqlite", "notifications" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
677,087
<p>If it's on the same machine, the simplest way would be to have named pipe, "player" with blocking read() and "editors" putting a token in pipe whenever they modify DB.</p>
1
2009-03-24T11:56:09Z
[ "python", "sqlite", "notifications" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
677,169
<p>How many editor processes (why processes?), and how often do you expect updates? This doesn't sound like a good design, especially not considering sqlite really isn't <b>too</b> happy about multiple concurrent accesses to the database.</p> <p><i>If</i> multiple processes makes sense <b>and</b> you want persistence, it would probably be smarter to have the editors notify your player via sockets, pipes, shared memory or the like and then have the player (aka server process) do the persisting.</p>
1
2009-03-24T12:30:20Z
[ "python", "sqlite", "notifications" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
677,215
<p>I think in that case, I would make a process to manage the database read/writes.</p> <p>Each editor that want to make some modifications to the database makes a call to this proccess, be it through IPC or network, or whatever method.</p> <p>This process can then notify the player of a change in the database. The player, when he wants to retrieve some data should make a request of the data it wants to the process managing the database. (Or the db process tells it what it needs, when it notifies of a change, so no request from the player needed)</p> <p>Doing this will have the advantage of having only one process accessing the SQLite DB, so no locking or concurrency issues on the database.</p>
2
2009-03-24T12:45:44Z
[ "python", "sqlite", "notifications" ]
How do I notify a process of an SQLite database change done in a different process?
677,028
<p>Let's say I have two or more processes dealing with an SQLite database - a "player" process and many "editor" processes. </p> <p>The "player" process reads the database and updates a view - in my case it would be a waveform being mixed to the soundcard depending on events stored in the database.</p> <p>An "editor" process is any editor for that database: it changes the database constantly.</p> <p>Now I want the player to reflect the editing changes quickly.</p> <p>I know that SQLite supplies hooks to trace database changes within the same process, but there seems to be little info on how to do this with multiple processes.</p> <p>I could poll the database constantly, compare records and trigger events, but that seems to be quite inefficient, especially when the database grows to a large size.</p> <p>I am thinking about using a log table and triggers, but I wonder if there is a simpler method.</p>
8
2009-03-24T11:34:34Z
22,390,871
<p>SQLite has an <a href="https://www.sqlite.org/c3ref/update_hook.html" rel="nofollow"><code>update_hook</code></a> function which does what you want. Unfortunately it isn't exposed by the Python sqlite module...</p> <p>Here is a slightly hacky workaround that digs into the C api (from Python code) to make use of it: <a href="http://stackoverflow.com/a/16920926">http://stackoverflow.com/a/16920926</a></p>
2
2014-03-13T21:03:29Z
[ "python", "sqlite", "notifications" ]
verbose_name_plural unexpected in a model?
677,172
<p>I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says:</p> <pre><code> File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 4, in &lt;module&gt; class Concursante(models.Model): File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 7, in Concursante nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) TypeError: __init__() got an unexpected keyword argument 'verbose_name_plural' </code></pre> <p>My model begins like this:</p> <pre><code># -*- encoding: utf-8 -*- from django.db import models class Concursante(models.Model): nombre = models.CharField(verbose_name='Nombre', max_length=30) apellidos = models.CharField(verbose_name='Apellidos', max_length=50) nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) </code></pre> <p>Why 'he' didn't expects a plural verbose name there? Cannot live together with verbose_name?</p> <p>FYI, this are my software versions:</p> <ul> <li>Ubuntu 8.04</li> <li>Python 2.5.2</li> <li>Django "1" "0" "final"</li> <li>Django ubuntu package version "1.0-1ubuntu1"</li> </ul>
2
2009-03-24T12:31:09Z
677,198
<p>There is no <code>verbose_name_plural</code>. It does not make sense to have both singular and plural for one field. They are mutually exclusive. In Django, they share the same name: <code>verbose_name</code>.</p> <p>If your data represents multiple items (e.g. in a one-to-many relationship) use a plural form in <code>verbose_name</code>. Otherwise, if your data represents a single item, use a singular form.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/db/models/#verbose-field-names">Verbose name fields in the Django documentation</a> provides some examples.</p>
5
2009-03-24T12:39:49Z
[ "python", "django", "django-models" ]
verbose_name_plural unexpected in a model?
677,172
<p>I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says:</p> <pre><code> File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 4, in &lt;module&gt; class Concursante(models.Model): File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 7, in Concursante nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) TypeError: __init__() got an unexpected keyword argument 'verbose_name_plural' </code></pre> <p>My model begins like this:</p> <pre><code># -*- encoding: utf-8 -*- from django.db import models class Concursante(models.Model): nombre = models.CharField(verbose_name='Nombre', max_length=30) apellidos = models.CharField(verbose_name='Apellidos', max_length=50) nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) </code></pre> <p>Why 'he' didn't expects a plural verbose name there? Cannot live together with verbose_name?</p> <p>FYI, this are my software versions:</p> <ul> <li>Ubuntu 8.04</li> <li>Python 2.5.2</li> <li>Django "1" "0" "final"</li> <li>Django ubuntu package version "1.0-1ubuntu1"</li> </ul>
2
2009-03-24T12:31:09Z
677,199
<p>Unfortunately, <code>verbose_name_plural</code> is not an option on the field. It's a meta option for the model itself. A field has no plural name since, unless it's a many-to-many relationship (in which case Django will use the plural for the model pointed to by the relationship), there's only one entity in that field.</p> <p>Here's the doc section: <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id3" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/models/#id3</a></p>
4
2009-03-24T12:39:52Z
[ "python", "django", "django-models" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
677,407
<p>Are you looking for <a href="http://en.wikipedia.org/wiki/Cyclomatic%5Fcomplexity" rel="nofollow">cyclomatic complexity (Wikipedia)</a>? It basically computes the number of paths through a piece of code. There are some projects to compute that for Python code, for example <a href="http://sourceforge.net/projects/pymetrics/" rel="nofollow">PyMetrics</a> or <a href="http://www.traceback.org/2008/03/31/measuring-cyclomatic-complexity-of-python-code/" rel="nofollow">this one</a>. Google will certainly bring up more.</p> <p>But I don't know of any further integration with unit tests that will show you the coverage.</p>
2
2009-03-24T13:31:46Z
[ "python", "unit-testing", "code-coverage" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
679,530
<p>I don't know of any branch coverage tools for Python, though I've contemplated writing one. My thought was to start with the AST and insert additional instrumentation for each branch point. It's doable, but there are some tricky cases.</p> <p>For example,</p> <pre><code>raise SomeException(x) </code></pre> <p>Branch coverage for this needs to check that SomeException(x) was fully instantiated and didn't raise its own exception.</p> <pre><code>assert x, "Oh No!: %r" % (x, y) </code></pre> <p>This needs to check that the text on the right side of the assertion statement is fully evaluated.</p> <pre><code>return args.name or os.getenv("NAME") or die("no name present") </code></pre> <p>Each of the first two terms has to be checked for the true/false path, but not the last. In fact, the last might not even return.</p> <p>There were a lot of cases to worry about and I had no pressing need for it other than curiosity so I didn't go anywhere with it. I was also wondering if I would get a lot of false positives where I would need some way to repress specific warnings.</p> <p>If you want to try this route, start with Python 2.6 or 3.0. In those releases the AST module is documented and you can create your own AST nodes before generating the code or .pyc file.</p>
2
2009-03-24T22:37:42Z
[ "python", "unit-testing", "code-coverage" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
680,042
<p>The very same maintainer of coverage.py has an article discussing a way to <a href="http://nedbatchelder.com/blog/200804/wicked%5Fhack%5Fpython%5Fbytecode%5Ftracing.html" rel="nofollow">get coverage information at the bytecode level</a>. The method is a bit kludgey: it involves re-assembling .pyc files with tweaked line numbers. However, it provides about as much granularity in coverage measurement as you could ask for.</p>
1
2009-03-25T02:44:51Z
[ "python", "unit-testing", "code-coverage" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
683,736
<p>I haven't used it myself, but if you are willing to replace coverage analysis with <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting" rel="nofollow" title="mutation testing">mutation testing</a>, I've heard of a mutation tester called "pester".</p> <p>While I was doing googling, I also came across <a href="http://www.pycheesecake.org/wiki/PythonTestingToolsTaxonomy" rel="nofollow">a list of python testing tools</a> which mentions some possible code coverage tools.</p>
1
2009-03-25T22:18:15Z
[ "python", "unit-testing", "code-coverage" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
1,114,731
<p>Parse and modify the AST is the right answer, IMHO. See this paper for a complete description of what you need to do: "Branch Coverage Made Easy for Arbitrary Languages"</p> <p><a href="http://www.semanticdesigns.com/Company/Publications/TestCoverage.pdf" rel="nofollow">http://www.semanticdesigns.com/Company/Publications/TestCoverage.pdf</a></p>
0
2009-07-11T21:52:08Z
[ "python", "unit-testing", "code-coverage" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
1,714,970
<p><a href="http://nedbatchelder.com/code/coverage/branch.html" rel="nofollow">Coverage.py now includes branch coverage</a>. </p> <p>For the curious: the code is not modified before running. The trace function tracks which lines follow which in the execution, and compare that information with static analysis of the compiled byte code to find path possibilities not executed.</p>
7
2009-11-11T12:44:20Z
[ "python", "unit-testing", "code-coverage" ]
condition coverage in python
677,219
<p>Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".</p>
17
2009-03-24T12:47:09Z
37,492,466
<p>It looks like "instrumental" implements condition coverage:</p> <p><a href="https://pypi.python.org/pypi/instrumental" rel="nofollow">Instrumental on Pypi</a></p> <p><a href="https://lautaportti.wordpress.com/2011/05/07/test-coverage-analysis/" rel="nofollow">Link about coverage.py and instrumental</a></p> <p>Has anyone tried it? It has a tiny version number. I need something I can trust.</p>
0
2016-05-27T21:26:29Z
[ "python", "unit-testing", "code-coverage" ]
Python SVN bindings for Windows
677,252
<p>Where can I find precompiled Python SWIG SVN bindings for Windows?</p>
18
2009-03-24T12:58:01Z
677,345
<p>The (old) <a href="http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=8100" rel="nofollow">Windows binaries</a> page at tigris.org contains an installer for <em>python bindings for SVN</em>. View the source for the SWIG bindings at <a href="http://svn.apache.org/viewvc/subversion/trunk/subversion/bindings/swig/python/" rel="nofollow">/trunk/subversion/bindings/swig/python</a>.</p> <p>(May 2010 - The <em>Subversion project</em> is transitioning into its new role as an Apache Software Foundation, many resources are changing address. Updated source link. )</p> <p>(November 2010 - more Windows binaries)</p> <p>The <a href="http://alagazam.net/" rel="nofollow">win32svn</a> project, <em>Subversion for Windows, by alagazam</em>, is a win32 build of subversion. As of November 2010, it contains a 1.6.13 build dated 2010-10-05, <em>including <code>python 2.6</code> bindings</em>.</p> <p>(January 2011 - keeping up: 2010-12-17, <a href="http://sourceforge.net/projects/win32svn/files/1.6.15/" rel="nofollow">1.6.15</a>, Python 2.6.6.)</p> <p>(May 2011 - 2011-03-14, <a href="http://sourceforge.net/projects/win32svn/files/1.6.16/" rel="nofollow">1.6.16</a>, Python 2.6.6)</p> <p>(June 2011 - 2011-06-03, <a href="http://sourceforge.net/projects/win32svn/files/1.6.17/" rel="nofollow">1.6.17</a>, Python 2.6.6)</p> <p>(October 2011 - 2011-10-15, <a href="http://sourceforge.net/projects/win32svn/files/1.7.0/" rel="nofollow">1.7.0</a>), Python 2.6.6 and 2.7.2)</p> <p>(December 2011 - 2011-12-12, <a href="http://sourceforge.net/projects/win32svn/files/1.7.2/" rel="nofollow">[1.7.2]</a>, Python 2.7.2 and 2.6.6)</p> <p>(February 2012 - 2012-02-18, <a href="http://sourceforge.net/projects/win32svn/files/1.7.3/" rel="nofollow">[1.7.3]</a>, Python 2.5.4 , 2.6.6 and 2.7.2 )</p> <p>(March 2012 - 2012-03-08 <a href="http://sourceforge.net/projects/win32svn/files/1.7.4/" rel="nofollow">1.7.4</a>, Python 2.5.4 , 2.6.6 and 2.7.2)</p> <p>(May 2012 - 2012-05-17 <a href="http://sourceforge.net/projects/win32svn/files/1.7.5/" rel="nofollow">1.7.5</a>, Python 2.5.4 , 2.6.6 and 2.7.3)</p> <p>(August 2012 - 2012-08-15 <a href="http://sourceforge.net/projects/win32svn/files/1.7.6/" rel="nofollow">1.7.6</a>, Python 2.5.4, 2.6.6 and 2.7.3. No Python 3 version) </p> <p>(December 2012 - 2012-12-20 <a href="http://sourceforge.net/projects/win32svn/files/1.7.8/" rel="nofollow">1.7.8</a>, Python 2.5.4, 2.6.6 and 2.7.3.)</p> <p>(November 2013 - 2013-11-25 <a href="http://sourceforge.net/projects/win32svn/files/1.8.5/" rel="nofollow">1.8.5</a>, Python 2.6.6 and 2.7.6)</p> <p>(May 2016 - 2016-05-04 <a href="https://sourceforge.net/projects/win32svn/files/1.8.16/" rel="nofollow">1.8.16</a>, Python 2.6.6 and 2.7.9)</p>
45
2009-03-24T13:18:35Z
[ "python", "windows", "svn", "swig", "precompiled" ]
Python SVN bindings for Windows
677,252
<p>Where can I find precompiled Python SWIG SVN bindings for Windows?</p>
18
2009-03-24T12:58:01Z
4,848,786
<p>You can find working bindings in the Trac project:</p> <p><a href="http://trac.edgewall.org/wiki/TracSubversion" rel="nofollow">http://trac.edgewall.org/wiki/TracSubversion</a></p> <p>See the attachment:</p> <p>svn-win32-1.6.15_py_2.7.zip</p>
1
2011-01-31T08:10:41Z
[ "python", "windows", "svn", "swig", "precompiled" ]
What's the best online tutorial for starting with Spring Python
677,255
<p>Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs. </p> <p>My manager has complained (with good reason) that our APIs are in a mess - we need to impose some order on them. Since we will be re-factoring it makes sense to take advantage of what is considered best practice - so we would like to consider Spring.</p> <p>Could somebody point me to the best learning resources for getting started with Spring? I've googled for a while and not found anything which seems to start from first principles. I'm looking for something which assumes good knowledge of Python but zero knowledge of Spring on other platforms or it's principles.</p> <p>Thanks</p>
5
2009-03-24T12:58:23Z
677,357
<p>How did you come to decide on Spring Python as your API of choice? Spring works well on Java where there's a tradition of declarative programming; defining your application primarily using XML to control a core engine is a standard pattern in Java. </p> <p>In Python, while the underlying patterns like Inversion of Control are still apposite (depending on your use case), the implementation chosen by Spring looks like a classic case of something produced by a Java programmer who doesn't want to learn Python. See the oft-referenced article <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is Not Java</a>.</p> <p>I applaud your decision to introduce order and thoughtfulness to your codebase, but you may wish to evaluate a number of options before making your decision. In particular, you may find that using Spring Python will make it difficult to hire good Python programmers, many of whom will run the other way when faced with 1000-line XML files describing object interactions.</p> <p>Perhaps start by re-examining what you really want to accomplish. The problem cannot simply be that "you need a framework". There are lots of frameworks out there, and it's hard to evaluate a) if you truly need one and b) which one will work if you haven't identified what underlying software problems you need to solve.</p> <p>If the real problem is that your code is an unmaintainable mess, introducing a framework probably won't fix the issue. Instead of just messy code, you'll have code that is messy in someone else's style :-) Perhaps rigour in the dev team is where you should recommend starting first: good planning, code reviews, stringent hiring practices, a "cleanup" release, etc...</p> <p>Good luck with the research.</p>
10
2009-03-24T13:19:51Z
[ "python", "spring" ]
What's the best online tutorial for starting with Spring Python
677,255
<p>Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs. </p> <p>My manager has complained (with good reason) that our APIs are in a mess - we need to impose some order on them. Since we will be re-factoring it makes sense to take advantage of what is considered best practice - so we would like to consider Spring.</p> <p>Could somebody point me to the best learning resources for getting started with Spring? I've googled for a while and not found anything which seems to start from first principles. I'm looking for something which assumes good knowledge of Python but zero knowledge of Spring on other platforms or it's principles.</p> <p>Thanks</p>
5
2009-03-24T12:58:23Z
677,511
<p>I won't go so far as to suggest that Spring Python is bad (because I don't know enough about it). But, to call Spring Python the "gold standard for Python APIs" is a stretch. To me, it seems that Spring Python is more of a way to allow Python apps to interact with Java Apps using Spring.</p> <p>At any rate, after taking a precursory glance at the <a href="http://springpython.webfactional.com/reference/html/index.html" rel="nofollow">official documentation</a>, it seems fairly easy to understand for me having decent knowledge of Python but no knowledge of spring. Aside from the fact that it almost looks like Java code where the author forgot the typenames, semicolons, and curly braces. :-)</p>
1
2009-03-24T13:55:00Z
[ "python", "spring" ]
How to check if an RGB image contains only one color?
677,395
<p>I'm using Python and PIL.</p> <p>I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001).</p> <p>I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clever algorithm.</p> <p>Any ideas?</p> <blockquote> <p>ImageStat module is THE answer! Thanks Aaron. I use ImageStat.var to get the variance and it works perfectly.</p> </blockquote> <p>Here is my piece of code:</p> <pre><code>from PIL import Image, ImageStat MONOCHROMATIC_MAX_VARIANCE = 0.005 def is_monochromatic_image(src): v = ImageStat.Stat(Image.open(src)).var return reduce(lambda x, y: x and y &lt; MONOCHROMATIC_MAX_VARIANCE, v, True) </code></pre>
2
2009-03-24T13:28:34Z
677,454
<p>First, you should define a distance between two colors. Then you just have to verify for each pixel that it's distance to your color is small enough.</p>
0
2009-03-24T13:41:58Z
[ "python", "image", "colors", "python-imaging-library" ]
How to check if an RGB image contains only one color?
677,395
<p>I'm using Python and PIL.</p> <p>I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001).</p> <p>I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clever algorithm.</p> <p>Any ideas?</p> <blockquote> <p>ImageStat module is THE answer! Thanks Aaron. I use ImageStat.var to get the variance and it works perfectly.</p> </blockquote> <p>Here is my piece of code:</p> <pre><code>from PIL import Image, ImageStat MONOCHROMATIC_MAX_VARIANCE = 0.005 def is_monochromatic_image(src): v = ImageStat.Stat(Image.open(src)).var return reduce(lambda x, y: x and y &lt; MONOCHROMATIC_MAX_VARIANCE, v, True) </code></pre>
2
2009-03-24T13:28:34Z
677,545
<p>Try the <a href="http://www.pythonware.com/library/pil/handbook/imagestat.htm" rel="nofollow">ImageStat module</a>. If the values returned by <code>extrema</code> are the same, you have only a single color in the image.</p>
3
2009-03-24T14:03:28Z
[ "python", "image", "colors", "python-imaging-library" ]
How to check if an RGB image contains only one color?
677,395
<p>I'm using Python and PIL.</p> <p>I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001).</p> <p>I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clever algorithm.</p> <p>Any ideas?</p> <blockquote> <p>ImageStat module is THE answer! Thanks Aaron. I use ImageStat.var to get the variance and it works perfectly.</p> </blockquote> <p>Here is my piece of code:</p> <pre><code>from PIL import Image, ImageStat MONOCHROMATIC_MAX_VARIANCE = 0.005 def is_monochromatic_image(src): v = ImageStat.Stat(Image.open(src)).var return reduce(lambda x, y: x and y &lt; MONOCHROMATIC_MAX_VARIANCE, v, True) </code></pre>
2
2009-03-24T13:28:34Z
677,567
<p>Here's a little snippet you could make use of :</p> <pre><code> import Image im = Image.open("path_to_image") width,height = im.size for w in range(0,width): for h in range(0,height): # this will hold the value of all the channels color_tuple = im.getpixel((w,h)) # do something with the colors here </code></pre> <p>Maybe use a hash and store the tuples as the key and it's number of appearances as value?</p>
0
2009-03-24T14:09:00Z
[ "python", "image", "colors", "python-imaging-library" ]
Using 'old' database with django
677,476
<p>I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django. </p> <p>What's the best way to access these tables?</p>
6
2009-03-24T13:48:33Z
677,549
<p>There is no way to use composite primary keys in Django's ORM as of now (up to v1.0.2).</p> <p>I can only think of three solutions/workarounds:</p> <ol> <li>There is a <a href="http://github.com/dcramer/django-compositepks/tree/master" rel="nofollow">fork</a> of django with a composite pk patch at github that you might want to try.</li> <li>You could use <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> together with Django.</li> <li>You have to add a single field primary key field to those tables.</li> </ol>
4
2009-03-24T14:05:13Z
[ "python", "django" ]
Using 'old' database with django
677,476
<p>I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django. </p> <p>What's the best way to access these tables?</p>
6
2009-03-24T13:48:33Z
677,798
<p>Django does have support for <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships" rel="nofollow">many-to-many relationships</a>. If you want to use a helper table to manage this relationships, the ManyToManyField takes a through argument which specifies the table to use. You can't model anything terribly complex this way, but it is good for most simple applications.</p>
0
2009-03-24T15:01:35Z
[ "python", "django" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
680,473
<p>You can't really pass custom parameters to the script. However the following things are possible and could solve your problem:</p> <ul> <li>optional features can be enabled using <code>--with-featurename</code>, standard features can be disabled using <code>--without-featurename</code>. [AFAIR this requires setuptools]</li> <li>you can use environment variables, these however require to be <code>set</code> on windows whereas prefixing them works on linux/ OS X (<code>FOO=bar python setup.py</code>).</li> <li>you can extend distutils with your own <code>cmd_class</code>es which can implement new features. They are also chainable, so you can use that to change variables in your script. (<code>python setup.py foo install</code>) will execute the <code>foo</code> command before it executes <code>install</code>.</li> </ul> <p>Hope that helps somehow. Generally speaking I would suggest providing a bit more information what exactly your extra parameter should do, maybe there is a better solution available.</p>
8
2009-03-25T06:48:40Z
[ "python", "distutils" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
4,792,601
<p>Here is a very simple solution, all you have to do is filter out <code>sys.argv</code> and handle it yourself before you call to distutils <code>setup(..)</code>. Something like this:</p> <pre><code>if "--foo" in sys.argv: do_foo_stuff() sys.argv.remove("--foo") ... setup(..) </code></pre> <p>The documentation on how to do this with distutils is terrible, eventually I came across this one: <a href="http://readthedocs.org/docs/the-hitchhikers-guide-to-packaging/en/latest/specification.html">the hitchhikers guide to packaging</a>, which uses <code>sdist</code> and its <code>user_options</code>. I find the <a href="http://docs.python.org/2/distutils/extending">extending distutils</a> reference not particularly helpful.</p> <p>Although this looks like the "proper" way of doing it with distutils (at least the only one that I could find that is vaguely documented). I could not find anything on <code>--with</code> and <code>--without</code> switches mentioned in the other answer.</p> <p>The problem with this distutils solution is that it is just way too involved for what I am looking for (which may also be the case for you). Adding dozens of lines and subclassing <code>sdist</code> is just wrong for me.</p>
14
2011-01-25T10:54:17Z
[ "python", "distutils" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
18,940,379
<p>A quick and easy way similar to that given by totaam would be to use argparse to grab the -foo argument and leave the remaining arguments for the call to distutils.setup(). Using argparse for this would be better than iterating through sys.argv manually imho. For instance, add this at the beginning of your setup.py:</p> <pre><code>argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument('--foo', help='required foo argument', required=True) args, unknown = argparser.parse_known_args() sys.argv = [sys.argv[0]] + unknown </code></pre> <p>The <code>add_help=False</code> argument means that you can still get the regular setup.py help using <code>-h</code> (provided <code>--foo</code> is given).</p>
-2
2013-09-22T04:39:08Z
[ "python", "distutils" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
20,248,942
<p>As Setuptools/Distuils are horribly documented, I had problems finding the answer to this myself. But eventually I stumbled across <a href="http://marc.merlins.org/linux/talks/SvnScalingGvn/svn-tree/gvn-release/setup.py">this</a> example. Also, <a href="http://stackoverflow.com/questions/1710839/custom-distutils-commands">this</a> similar question was helpful. Basically, a custom command with an option would look like:</p> <pre><code>from distutils.core import setup, Command class InstallCommand(Command): description = "Installs the foo." user_options = [ ('foo=', None, 'Specify the foo to bar.'), ] def initialize_options(self): self.foo = None def finalize_options(self): assert self.foo in (None, 'myFoo', 'myFoo2'), 'Invalid foo!' def run(self): install_all_the_things() setup( ..., cmdclass={ 'install': InstallCommand, } ) </code></pre>
29
2013-11-27T17:17:29Z
[ "python", "distutils" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
28,329,763
<p>I successfully used a workaround to use a solution similar to totaam's suggestion. I ended up popping my extra arguments from the sys.argv list:</p> <pre><code>import sys from distutils.core import setup foo = 0 if '--foo' in sys.argv: index = sys.argv.index('--foo') sys.argv.pop(index) # Removes the '--foo' foo = sys.argv.pop(index) # Returns the element after the '--foo' # The foo is now ready to use for the setup setup(...) </code></pre> <p>Some extra validation could be added to ensure the inputs are good, but this is how I did it</p>
2
2015-02-04T19:29:01Z
[ "python", "distutils" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
33,181,352
<p>Yes, it's 2015 and the documentation for adding commands and options in both <code>setuptools</code> and <code>distutils</code> is still largely missing.</p> <p>After a few frustrating hours I figured out the following code for adding a custom option to the <code>install</code> command of <code>setup.py</code>:</p> <pre><code>from setuptools.command.install import install class InstallCommand(install): user_options = install.user_options + [ ('custom_option=', None, 'Path to something') ] def initialize_options(self): install.initialize_options(self) self.custom_option = None def finalize_options(self): #print('The custom option for install is ', self.custom_option) install.finalize_options(self) def run(self): global my_custom_option my_custom_option = self.custom_option install.run(self) </code></pre> <p>At this point you register your command with <code>setup</code>:</p> <pre><code>setup( cmdclass={ 'install': InstallCommand, }, : </code></pre>
2
2015-10-17T00:21:10Z
[ "python", "distutils" ]
distutils: How to pass a user defined parameter to setup.py?
677,577
<p>Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:</p> <pre><code>python setup.py install -foo myfoo </code></pre> <p>Thank you,<br/> Mher</p>
34
2009-03-24T14:12:04Z
36,489,371
<p>Perhaps you are an unseasoned programmer like me that still struggled after reading all the answers above. Thus, you might find another example potentially helpful (<strong>and to address the comments in previous answers about entering the command line arguments</strong>):</p> <pre><code>class RunClientCommand(Command): """ A command class to runs the client GUI. """ description = "runs client gui" # The format is (long option, short option, description). user_options = [ ('socket=', None, 'The socket of the server to connect (e.g. '127.0.0.1:8000')', ] def initialize_options(self): """ Sets the default value for the server socket. The method is responsible for setting default values for all the options that the command supports. Option dependencies should not be set here. """ self.socket = '127.0.0.1:8000' def finalize_options(self): """ Overriding a required abstract method. The method is responsible for setting and checking the final values and option dependencies for all the options just before the method run is executed. In practice, this is where the values are assigned and verified. """ pass def run(self): """ Semantically, runs 'python src/client/view.py SERVER_SOCKET' on the command line. """ print(self.socket) errno = subprocess.call([sys.executable, 'src/client/view.py ' + self.socket]) if errno != 0: raise SystemExit("Unable to run client GUI!") </code></pre> <hr> <pre><code>setup( # Some other omitted details cmdclass={ 'runClient': RunClientCommand, }, </code></pre> <p>The above is tested and from some code I wrote. I have also included slightly more detailed docstrings to make things easier to understand.</p> <p>As for the command line: <code>python setup.py runClient --socket=127.0.0.1:7777</code>. A quick double check using print statements shows that indeed the correct argument is picked up by the run method.</p> <p>Other resources I found useful (<strong><em>more</em> and <em>more</em></strong> examples):</p> <p><a href="http://stackoverflow.com/questions/1710839/custom-distutils-commands">Custom distutils commands</a></p> <p><a href="https://seasonofcode.com/posts/how-to-add-custom-build-steps-and-commands-to-setuppy.html" rel="nofollow">https://seasonofcode.com/posts/how-to-add-custom-build-steps-and-commands-to-setuppy.html</a></p>
2
2016-04-08T00:11:34Z
[ "python", "distutils" ]
wxPython: Making a scrollable DC
677,590
<p>I am drawing inside a wx.Window using a PaintDC. I am drawing circles and stuff like that into that window. Problem is, sometimes the circles go outside the scope of the window. I want a scrollbar to automatically appear whenever the drawing gets too big. What do I do?</p>
1
2009-03-24T14:15:29Z
680,574
<p>Use a <code>wx.ScrolledWindow</code> and set the size of the window as soon as your 'drawing go outside' the window with</p> <pre><code>SetVirtualSize(width,height) </code></pre> <p>If this size is bigger than the client size, then wx will show scrollbars. When drawing in the window make sure to use <code>CalcUnscrolledPosition</code> and <code>CalcScrolledPosition</code></p> <p><a href="http://docs.wxwidgets.org/stable/wx%5Fwxscrolledwindow.html" rel="nofollow">Here</a> you can find some more information.</p>
1
2009-03-25T07:36:46Z
[ "python", "wxpython", "scroll", "scrollbar" ]
How can I record live video with gstreamer without dropping frames?
677,641
<p>I'm trying to use gstreamer 0.10 from Python to simultaneously display a v4l2 video source and record it to xvid-in-avi. Over a long period of time the computer would be fast enough to do this but if another program uses the disk it drops frames. That's bad enough, but on playback there are bursts of movement in the video where frames were dropped instead of displaying the frames we were able to encode at a lower framerate.</p> <p>The pipeline is <code>v4l2src ! capsfilter ! tee ! queue ! xvidenc ! avimux ! filesink</code> and the tee also sinks to a <code>queue ! xvimagesink sync=false</code>. I've tried adding <code>videorate</code> in front of <code>xvidenc</code> but that seems to make things worse.</p> <p>I've considered spooling the uncompressed video to disk in this pipeline and encoding it in a background thread. What else could I do to solve this problem? Is <code>xvidenc</code> or <code>avimux</code> doing the wrong thing with dropped frames? Could I dramatically increase the size of the queue preceding my encoder?</p>
4
2009-03-24T14:28:02Z
677,681
<p><code>tee</code> will block if either output blocks, so it's probably your bottleneck. I suggest to write the stream that takes longer to encode to disk and encode from there.</p>
5
2009-03-24T14:35:41Z
[ "python", "linux", "gstreamer" ]
How can I record live video with gstreamer without dropping frames?
677,641
<p>I'm trying to use gstreamer 0.10 from Python to simultaneously display a v4l2 video source and record it to xvid-in-avi. Over a long period of time the computer would be fast enough to do this but if another program uses the disk it drops frames. That's bad enough, but on playback there are bursts of movement in the video where frames were dropped instead of displaying the frames we were able to encode at a lower framerate.</p> <p>The pipeline is <code>v4l2src ! capsfilter ! tee ! queue ! xvidenc ! avimux ! filesink</code> and the tee also sinks to a <code>queue ! xvimagesink sync=false</code>. I've tried adding <code>videorate</code> in front of <code>xvidenc</code> but that seems to make things worse.</p> <p>I've considered spooling the uncompressed video to disk in this pipeline and encoding it in a background thread. What else could I do to solve this problem? Is <code>xvidenc</code> or <code>avimux</code> doing the wrong thing with dropped frames? Could I dramatically increase the size of the queue preceding my encoder?</p>
4
2009-03-24T14:28:02Z
2,237,878
<p>and you need to write xvimagesink, not xvimagesync</p>
1
2010-02-10T15:20:28Z
[ "python", "linux", "gstreamer" ]
How to extract from a list of objects a list of specific attribute?
677,656
<p>I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.</p> <p>Is there any built-in functions to do that?</p>
7
2009-03-24T14:31:43Z
677,663
<p>Assuming you want field <code>b</code> for the objects in a list named <code>objects</code> do this: </p> <pre><code>[o.b for o in objects] </code></pre>
0
2009-03-24T14:33:14Z
[ "python" ]
How to extract from a list of objects a list of specific attribute?
677,656
<p>I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.</p> <p>Is there any built-in functions to do that?</p>
7
2009-03-24T14:31:43Z
677,669
<p>The first thing that came to my mind:</p> <pre><code>attrList = map(lambda x: x.attr, objectList) </code></pre>
2
2009-03-24T14:34:06Z
[ "python" ]
How to extract from a list of objects a list of specific attribute?
677,656
<p>I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.</p> <p>Is there any built-in functions to do that?</p>
7
2009-03-24T14:31:43Z
677,679
<p>are you looking for something like this?</p> <pre><code>[o.specific_attr for o in objects] </code></pre>
5
2009-03-24T14:35:30Z
[ "python" ]
How to extract from a list of objects a list of specific attribute?
677,656
<p>I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.</p> <p>Is there any built-in functions to do that?</p>
7
2009-03-24T14:31:43Z
677,685
<p>A list comprehension would work just fine:</p> <pre><code>[o.my_attr for o in my_list] </code></pre> <p>But there is a combination of built-in functions, since you ask :-)</p> <pre><code>from operator import attrgetter map(attrgetter('my_attr'), my_list) </code></pre>
14
2009-03-24T14:36:50Z
[ "python" ]
Specifying different template names in Django generic views
677,793
<p>I have the code in my urls.py for my generic views;</p> <pre><code>infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) </code></pre> <p>So going to the address /gindex/ will use a generic view with the template of 'index.html'.</p> <p>But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name.</p> <p>Please note this also applies to template object name within infodict.</p> <p>Thanks for your help!</p> <p><strong>Edit</strong>: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually!</p> <p>Thanks again for all the answers and different approaches.</p>
2
2009-03-24T15:00:49Z
677,853
<p>If you want to supply different template names to different views, the common practice is indeed to pass in a unique dictionary to each URL pattern. For example:</p> <pre><code>urlpatterns = patterns('', url(r'^home/$', 'my.views.home', {'template_name': 'home.html'}, name='home'), url(r'^about/$', 'my.views.about', {'template_name': 'about.html'}, name='about'), ) </code></pre> <p>This kind of pattern is common and acceptable.</p>
1
2009-03-24T15:15:01Z
[ "python", "django", "django-urls" ]
Specifying different template names in Django generic views
677,793
<p>I have the code in my urls.py for my generic views;</p> <pre><code>infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) </code></pre> <p>So going to the address /gindex/ will use a generic view with the template of 'index.html'.</p> <p>But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name.</p> <p>Please note this also applies to template object name within infodict.</p> <p>Thanks for your help!</p> <p><strong>Edit</strong>: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually!</p> <p>Thanks again for all the answers and different approaches.</p>
2
2009-03-24T15:00:49Z
677,941
<p>Not as simple, but possibly useful if you have a whole lot of different patterns matching the same view:</p> <pre><code>base_dict={ ... #defaults go here } def make_dict(template_name,template_object_name): base_dict.update({ 'template_name':template_name, 'template_object_name':template_object_name, }) return base_dict urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', make_dict('index1.html','latest_poll_list')), (r'^hindex/$', 'archive_index', make_dict('index2.html','oldest_poll_list')), ) </code></pre> <p>For a lot of similar generic views, this will condense your code calls a wee bit, at the expense of a little bit of transparency. If you've got many lines customizing the same few parameters, this might be easiest to read.</p> <p>Finally, if all or most of your views require some, but not all, of the same information, never forget how useful a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#writing-your-own-context-processors" rel="nofollow">context processor</a> is. It takes only a little more work to set up than the above solutions, but it extends much better, because it will guarantee that (unless you use the render_to_response shortcut without the RequestContext keyword) the defaults will always be available to your template no matter how your view or url conf changes.</p>
0
2009-03-24T15:31:53Z
[ "python", "django", "django-urls" ]
Specifying different template names in Django generic views
677,793
<p>I have the code in my urls.py for my generic views;</p> <pre><code>infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) </code></pre> <p>So going to the address /gindex/ will use a generic view with the template of 'index.html'.</p> <p>But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name.</p> <p>Please note this also applies to template object name within infodict.</p> <p>Thanks for your help!</p> <p><strong>Edit</strong>: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually!</p> <p>Thanks again for all the answers and different approaches.</p>
2
2009-03-24T15:00:49Z
678,027
<p>you can define wrapper view functions to parametrize generic views. In your urls.py add pattern</p> <pre><code>url(r'^/(?P&lt;tmpl_name&gt;\w+)/$', 'my.views.datebasedproxy') </code></pre> <p>in your views.py add view function</p> <pre><code>def datebasedproxy(request, tmpl_name): return django.views.generic.date_based(request,otherparameters, template_name=tmpl_matrix[tmpl_name]) </code></pre> <p>where tmpl_matrix is hypothetic list that matches template file name with parameter and otherparameters stands for other dictionary items required for date_based function</p>
0
2009-03-24T15:48:03Z
[ "python", "django", "django-urls" ]
Specifying different template names in Django generic views
677,793
<p>I have the code in my urls.py for my generic views;</p> <pre><code>infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) </code></pre> <p>So going to the address /gindex/ will use a generic view with the template of 'index.html'.</p> <p>But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name.</p> <p>Please note this also applies to template object name within infodict.</p> <p>Thanks for your help!</p> <p><strong>Edit</strong>: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually!</p> <p>Thanks again for all the answers and different approaches.</p>
2
2009-03-24T15:00:49Z
678,441
<p>Use the dict() constructor:</p> <pre><code>infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns = patterns('django.views.generic.date_based', url(r'^gindex/$', 'archive_index', dict(infodict, template_name='gindex.html')), url(r'^hindex/$', 'archive_index', dict(infodict, template_name='hindex.html')), ) </code></pre>
8
2009-03-24T17:35:51Z
[ "python", "django", "django-urls" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
677,841
<p>Without a doubt MySQLdb is the best solution, but if you can't use it…</p> <p>If you have <code>libmysqlclient</code>.[<code>so</code>|<code>dll</code>], you could access it directly using <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> module. </p>
1
2009-03-24T15:11:47Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
677,844
<p>As far as I know there is no direct alternative. The only thing I can think of is to use ODBC instead, via <a href="http://pyodbc.sourceforge.net/" rel="nofollow">pyodbc</a>. The MySQL site has an ODBC connector you can <a href="http://dev.mysql.com/downloads/connector/odbc/5.1.html" rel="nofollow">download</a>. But I've never used this approach myself, so I can't say how well it will work.</p>
0
2009-03-24T15:12:02Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
677,870
<p>You can find pre-built binary packages for MySQLdb and its dependencies for most operating systems.</p> <p><a href="http://sourceforge.net/project/showfiles.php?group_id=22307&amp;package_id=15775" rel="nofollow">http://sourceforge.net/project/showfiles.php?group_id=22307&amp;package_id=15775</a></p> <p>What platform are you running on?</p>
2
2009-03-24T15:19:39Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
678,066
<p>You've looked at these?</p> <p><a href="http://wiki.python.org/moin/MySQL">http://wiki.python.org/moin/MySQL</a></p>
5
2009-03-24T15:57:04Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
678,233
<p>There's a project at Sun to implement 100% python mysql driver. </p> <p><a href="https://launchpad.net/myconnpy" rel="nofollow">https://launchpad.net/myconnpy</a></p> <p>I haven't found any code for it though. But according to a <a href="http://lucumr.pocoo.org/2009/1/8/the-sad-state-of-mysql-python#comment-864" rel="nofollow">blog comment</a>, it's more than vaporware.</p>
4
2009-03-24T16:40:39Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
1,821,657
<p>Lately there is also <a href="http://pypi.python.org/pypi/oursql/" rel="nofollow">oursql</a> (<a href="http://packages.python.org/oursql/" rel="nofollow">docs</a>), which has various advantages over MySQLdb and other existing drivers -- listed at the top of the documentation.</p>
5
2009-11-30T18:50:18Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
1,824,573
<p>As mentioned in earlier answer, MySQL Connector/Python implements the MySQL Server/Client completely in Python. No compiling, just installing.</p> <p>Here are the links:<br> * <a href="https://launchpad.net/myconnpy" rel="nofollow">https://launchpad.net/myconnpy</a><br> * code: <a href="https://code.launchpad.net/myconnpy" rel="nofollow">https://code.launchpad.net/myconnpy</a><br> * download: <a href="https://launchpad.net/myconnpy/+download" rel="nofollow">https://launchpad.net/myconnpy/+download</a> (development shapshots)</p> <p>It's not complete yet, but it should have enough to keep you going. (FYI, I am the maintainer)</p>
2
2009-12-01T07:34:11Z
[ "python", "mysql", "database" ]
Python and MySQL: is there an alternative to MySQLdb?
677,811
<p>Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier.</p> <p>Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated.</p> <p>Thanks,</p> <p>Tony</p> <hr> <p>Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.</p>
13
2009-03-24T15:04:09Z
27,669,112
<p>I had the problem that I wanted to write code which work for Python 2 and Python 3. I found <a href="http://www.pymysql.org/" rel="nofollow"><code>pymysql</code></a> to fit perfectly. I did not have to adjust code to switch from MySQLdb to pymysql</p> <h2>Installation</h2> <pre><code>$ pip install PyMySQL </code></pre> <p>If you don't have admin rights:</p> <pre><code>$ pip install -u PyMySQL </code></pre> <h2>Usage</h2> <p>The usage is the same as for MySQLdb:</p> <h3>SELECT</h3> <pre><code>import pymysql import pymysql.cursors connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db'], cursorclass=pymysql.cursors.DictCursor) cursor = connection.cursor() sql = ("SELECT `id`, `formula_in_latex` FROM `wm_formula` " "WHERE `is_important` = 1 " "AND id != 1 " # exclude trash class "ORDER BY `id` ASC") cursor.execute(sql) formulas = cursor.fetchall() </code></pre> <h2>INSERT</h2> <pre><code>import pymysql connection = pymysql.connect(host=mysql['host'], user=mysql['user'], passwd=mysql['passwd'], db=mysql['db']) cursor = connection.cursor() cursor.execute("INSERT INTO `toys` (`id`, `arrival`, `duration`) " "VALUES ('1', '2014-12-01', '123');") connection.commit() </code></pre>
1
2014-12-27T16:18:31Z
[ "python", "mysql", "database" ]
python and symbian - keystroke capture
677,846
<p>I'm trying to write a simple prototyping appliaction in python to capture a users keystrokes while writing a text messages (SMS) to collect some stat info for use in a biometric application for Symbian based phones. I have never used python before and have had very little exposure to it. However, I did come across an example <a href="http://wiki.forum.nokia.com/index.php/How_to_use_Keys_in_PyS60" rel="nofollow">http://wiki.forum.nokia.com/index.php/How_to_use_Keys_in_PyS60</a> detailing how to capture UP, DOWN, LEFT, RIGHT, and 0-9 easily enough. I tried to find information on key_codes and keypress in the pys60 API but little is available as I'm looking for an example of how to capture characters such as 'a', 'b' etc. assuming that predictive text is disabled. Also, if it is not possible to capture characters, how feasible is it to map keypresses to characters? i.e. 228 = 'b','t'? </p> <p>Can anyone provide me with some examples, suggestions or a push in the right direction?</p>
1
2009-03-24T15:13:03Z
677,887
<p>I think you are searching for the wrong thing here.</p> <p>Key codes and keypress events will only capture up, down, etc. (actual buttons), as you already stated. The user can enter letters in multiple ways, which is all done through software (e.g. 22 is a 'b', or 228 might be 'cat' or 'bat') and there is no way to tell what the user entered based just on the buttons they hit. There is also auto-completion built into most phones, which will add characters the user did not press buttons for.</p> <p>Try searching for ways of capturing the actual text the user is seeing.</p>
1
2009-03-24T15:22:54Z
[ "python", "symbian", "pys60" ]
Doctest for dynamically created objects
677,931
<p>What is the best way to test code like this (the one below obviously fails while object is created in different block every time):</p> <pre><code>def get_session(db_name, verbose, test): """Returns current DB session from SQLAlchemy pool. &gt;&gt;&gt; get_session('Mmusc20090126', False, True) &lt;sqlalchemy.orm.session.Session object at 0xfb5ff0&gt; """ if test: engine = create_engine('sqlite:///:memory:', echo=verbose) log_load.debug('DB in RAM.') else: engine = create_engine('sqlite:///' + 'DB/' + db_name + '.db', echo=verbose) log_load.debug('DB stored in file: %s' % 'DB/' + db_name + '.db') # Create TABLES: Structures, Interactions, Interactors, PDB_UniProt, UniProtSeq meta.create_all(engine) Session = sessionmaker(bind=engine) session = Session() return session </code></pre>
3
2009-03-24T15:30:12Z
678,050
<p>I think you want to use ellipsis, like this:</p> <pre><code>&gt;&gt;&gt; get_session('Mmusc20090126', False, True) #doctest: +ELLIPSIS &lt;sqlalchemy.orm.session.Session object at 0x...&gt; </code></pre> <p>See <a href="http://docs.python.org/library/doctest.html#doctest.ELLIPSIS" rel="nofollow">here</a> for more info.</p>
8
2009-03-24T15:53:03Z
[ "python", "testing", "sqlalchemy", "doctest", "docstring" ]
Fill Django application with data using very large Python script
677,962
<p>I wrote a program that outputs a Python program that fills my <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?</p> <p>Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer).</p> <p>Any suggestions?</p> <p>The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL.</p>
0
2009-03-24T15:36:39Z
677,982
<p>Your computer wouldn't run it because is a large program?</p> <p>Maybe you should reference an external file, or files, with all the structure, and then dump it inside the database, instead of writing it inside your script/software...</p>
0
2009-03-24T15:40:32Z
[ "python", "database", "django", "migration" ]
Fill Django application with data using very large Python script
677,962
<p>I wrote a program that outputs a Python program that fills my <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?</p> <p>Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer).</p> <p>Any suggestions?</p> <p>The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL.</p>
0
2009-03-24T15:36:39Z
677,984
<p>Put the data in a separate file (or files). Then write a small program that reads in the data and populates your database via Django. </p>
0
2009-03-24T15:41:01Z
[ "python", "database", "django", "migration" ]
Fill Django application with data using very large Python script
677,962
<p>I wrote a program that outputs a Python program that fills my <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?</p> <p>Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer).</p> <p>Any suggestions?</p> <p>The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL.</p>
0
2009-03-24T15:36:39Z
678,248
<p>If I am reading your post correctly, you are reading from the old database and writing a "python program" based on that data. This seems to me to be the wrong way to do this.</p> <p>My suggestion would be to create a malleable version of the old database (XML would work well for this) by reading the data from the DB, modifying it as needed, and then dumping it into a file.</p> <p>With this malleable version of the data, use a separate program to import this data into the new database via your Django Models.</p> <p>This will also give you a level of flexibility if you ever need to duplicate this process.</p>
0
2009-03-24T16:45:03Z
[ "python", "database", "django", "migration" ]
Fill Django application with data using very large Python script
677,962
<p>I wrote a program that outputs a Python program that fills my <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?</p> <p>Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer).</p> <p>Any suggestions?</p> <p>The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL.</p>
0
2009-03-24T15:36:39Z
678,632
<p>In most cases, you can find a natural hierarchy to your objects. Sometimes there is some kind of "master" and all other objects have foreign key (FK) references to this master and to each other.</p> <p>In this case, you can use an XML-like structure with each master object "containing" a lot of subsidiary objects. In this case, you insert the master first, and all the children have FK references to an existing object.</p> <p>In some cases, however, there are relationships that can't be simple FK's to an existing object. In this case you have circular dependencies and you must (1) break this dependency temporarily and (2) recreate the dependency after the objects are loaded.</p> <p>You do this by (a) defining your model to have an optional FK, (b) and having a temporary "natural key" reference. You'll load data without the proper FK (it's optional). </p> <p>Then, after your data is loaded, you go back through a second pass and insert all of the missing FK references. Once this is done you can then modify your model to make the FK mandatory.</p> <p>Program 1 - export from old database to simple flat-file. CSV format or JSON format or something simple.</p> <pre><code>for m in OldModel.objects.all(): aDict = { 'col1':m.col1, 'old_at_fk':m.fktoanothertable.id, 'old_id':id } csvwriter.writerow( aDict ) </code></pre> <p>Program 2 - read simple flat-file; build new database model objects.</p> <pre><code># Pass 1 - raw load for row in csv.reader: new= NewModel.create( **row ) # Pass 2 - resolve FK's for nm in NewModel.objects.all(): ref1= OtherModel.objects.get( old_id=nm.old_at_fk ) nm.properfk = ref1 nm.save() </code></pre>
1
2009-03-24T18:32:23Z
[ "python", "database", "django", "migration" ]
weakref list in python
677,978
<p>I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).</p> <p>I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?</p> <p>Here's an example:</p> <pre><code>import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush() </code></pre>
15
2009-03-24T15:39:59Z
678,336
<p>You could implement it yourself, similarly to how you have done, but with a list subclass that calls flush() before attempting to access an item. </p> <p>Obviously you don't want to do this on every access, but you can optimize this by setting a callback on the weak reference to mark the list dirty when something dies. Then you only need to flush the list when something has died since the last access.</p> <p>Here's a list class implemented using this method. (Note that it's not tested much, and some methods aren't implemented very efficiently (eg. those which just convert to a real list and call the method on that), but it should be a reasonable starting point:</p> <pre><code>import weakref class WeakList(list): def __init__(self, seq=()): list.__init__(self) self._refs = [] self._dirty=False for x in seq: self.append(x) def _mark_dirty(self, wref): self._dirty = True def flush(self): self._refs = [x for x in self._refs if x() is not None] self._dirty=False def __getitem__(self, idx): if self._dirty: self.flush() return self._refs[idx]() def __iter__(self): for ref in self._refs: obj = ref() if obj is not None: yield obj def __repr__(self): return "WeakList(%r)" % list(self) def __len__(self): if self._dirty: self.flush() return len(self._refs) def __setitem__(self, idx, obj): if isinstance(idx, slice): self._refs[idx] = [weakref.ref(obj, self._mark_dirty) for x in obj] else: self._refs[idx] = weakref.ref(obj, self._mark_dirty) def __delitem__(self, idx): del self._refs[idx] def append(self, obj): self._refs.append(weakref.ref(obj, self._mark_dirty)) def count(self, obj): return list(self).count(obj) def extend(self, items): for x in items: self.append(x) def index(self, obj): return list(self).index(obj) def insert(self, idx, obj): self._refs.insert(idx, weakref.ref(obj, self._mark_dirty)) def pop(self, idx): if self._dirty: self.flush() obj=self._refs[idx]() del self._refs[idx] return obj def remove(self, obj): if self._dirty: self.flush() # Ensure all valid. for i, x in enumerate(self): if x == obj: del self[i] def reverse(self): self._refs.reverse() def sort(self, cmp=None, key=None, reverse=False): if self._dirty: self.flush() if key is not None: key = lambda x,key=key: key(x()) else: key = apply self._refs.sort(cmp=cmp, key=key, reverse=reverse) def __add__(self, other): l = WeakList(self) l.extend(other) return l def __iadd__(self, other): self.extend(other) return self def __contains__(self, obj): return obj in list(self) def __mul__(self, n): return WeakList(list(self)*n) def __imul__(self, n): self._refs *= n return self </code></pre> <p>[Edit] Add a more complete list implementation.</p>
5
2009-03-24T17:08:36Z
[ "python", "weak-references" ]
weakref list in python
677,978
<p>I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).</p> <p>I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?</p> <p>Here's an example:</p> <pre><code>import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush() </code></pre>
15
2009-03-24T15:39:59Z
2,625,813
<p>Why can't you just do it like this:</p> <pre><code>import weakref class WeakList(list): def append(self, item): list.append(self, weakref.ref(item, self.remove)) </code></pre> <p>And then do similar for <code>__iadd__</code>, <code>extend</code> etc. Works for me.</p>
1
2010-04-12T22:09:36Z
[ "python", "weak-references" ]
weakref list in python
677,978
<p>I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).</p> <p>I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?</p> <p>Here's an example:</p> <pre><code>import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush() </code></pre>
15
2009-03-24T15:39:59Z
6,272,503
<p>You can use WeakSet from the very same weakref module (it's actually defined elsewhere by the way, but it's imported there).</p> <pre><code>&gt;&gt;&gt; from weakref import WeakSet &gt;&gt;&gt; s = WeakSet() &gt;&gt;&gt; class Obj(object): pass # can't weakref simple objects &gt;&gt;&gt; a = Obj() &gt;&gt;&gt; s.add(a) &gt;&gt;&gt; print len(s) 1 &gt;&gt;&gt; del a &gt;&gt;&gt; print len(s) 0 </code></pre>
2
2011-06-07T22:52:26Z
[ "python", "weak-references" ]
weakref list in python
677,978
<p>I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).</p> <p>I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?</p> <p>Here's an example:</p> <pre><code>import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush() </code></pre>
15
2009-03-24T15:39:59Z
7,958,838
<p>How do you plan on using <code>B</code>? The only thing I ever do with the weakref list I built is iterate over it, so its implementation is simple:</p> <pre><code>import weakref class WeakRefList(object): "weakref psuedo list" def __init__(yo): yo._items = list() def __iter__(yo): yo._items = [s for s in yo._items if s() is not None] return (s() for s in yo._items if s() is not None) def __len__(yo): yo._items = [s for s in yo._items if s() is not None] return len(yo._items) def append(yo, new_item): yo._items.append(weakref.ref(new_item)) yo._items = [s for s in yo._items if s() is not None] </code></pre>
0
2011-10-31T19:43:32Z
[ "python", "weak-references" ]
weakref list in python
677,978
<p>I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).</p> <p>I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?</p> <p>Here's an example:</p> <pre><code>import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush() </code></pre>
15
2009-03-24T15:39:59Z
13,405,875
<p>Use a callback function passed to second argument of a weakref.</p> <p>This code should function:</p> <pre><code>import weakref class weakRefList(list): def addReference(self, obj): self._references.append(weakref.proxy(obj, self.remove)) </code></pre>
1
2012-11-15T20:44:50Z
[ "python", "weak-references" ]
weakref list in python
677,978
<p>I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually).</p> <p>I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this?</p> <p>Here's an example:</p> <pre><code>import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush() </code></pre>
15
2009-03-24T15:39:59Z
13,486,682
<p>As I needed a weakref list like you, I've made one and publish it on pypi.</p> <p>now you can do:</p> <pre><code>pip install weakreflist </code></pre> <p>then:</p> <pre><code>from weakreflist import WeakList </code></pre>
3
2012-11-21T05:06:19Z
[ "python", "weak-references" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
678,242
<p>Getting the name of the file without the extension :</p> <pre><code>import os print(os.path.splitext("path_to_file")[0]) </code></pre> <p>As for your import problem, you solve it this way :</p> <pre><code>from os.path import basename # now you can call it directly with basename print(basename("/a/b/c.txt")) </code></pre>
425
2009-03-24T16:43:15Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
678,247
<blockquote> <p>But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?</p> </blockquote> <p><code>import os</code>, and then use <code>os.path.basename</code></p> <p><code>import</code>ing <code>os</code> doesn't mean you can use <code>os.foo</code> without referring to <code>os</code>.</p>
7
2009-03-24T16:45:02Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
678,266
<p>Just roll it:</p> <pre><code>&gt;&gt;&gt; base=os.path.basename('/root/dir/sub/file.ext') &gt;&gt;&gt; base 'file.ext' &gt;&gt;&gt; os.path.splitext(base) ('file', '.ext') &gt;&gt;&gt; os.path.splitext(base)[0] 'file' &gt;&gt;&gt; </code></pre>
143
2009-03-24T16:49:53Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
1,228,618
<pre><code>&gt;&gt;&gt; print os.path.splitext(os.path.basename("hemanth.txt"))[0] hemanth </code></pre>
91
2009-08-04T16:44:50Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
18,310,208
<p>On Windows system I used drivername prefix as well, like:</p> <pre><code>&gt;&gt;&gt; s = 'c:\\temp\\akarmi.txt' &gt;&gt;&gt; print(os.path.splitext(s)[0]) c:\temp\akarmi </code></pre> <p>So because I do not need drive letter or directory name, I use:</p> <pre><code>&gt;&gt;&gt; print(os.path.splitext(os.path.basename(s))[0]) akarmi </code></pre>
2
2013-08-19T09:12:48Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
19,488,791
<p>If you want to keep the path to the file and just remove the extension</p> <pre><code>&gt;&gt;&gt; file = '/root/dir/sub.exten/file.data.1.2.dat' &gt;&gt;&gt; print ('.').join(file.split('.')[:-1]) /root/dir/sub.exten/file.data.1.2 </code></pre>
9
2013-10-21T07:46:11Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
22,291,806
<p>If you know the exact file extension for example .txt then you can use</p> <blockquote> <blockquote> <blockquote> <p>print fileName[0:-4]</p> </blockquote> </blockquote> </blockquote>
-5
2014-03-10T03:52:20Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
27,873,728
<p>We could do some simple <code>split</code> / <code>pop</code> magic as seen here (<a href="http://stackoverflow.com/a/424006/1250044">http://stackoverflow.com/a/424006/1250044</a>), to extract the filename (respecting the windows and POSIX differences).</p> <pre><code>def getFileNameWithoutExtension(path): return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0] getFileNameWithoutExtension('/path/to/file-0.0.1.ext') # =&gt; file-0.0.1 getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext') # =&gt; file-0.0.1 </code></pre>
1
2015-01-10T07:05:52Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
30,507,881
<pre><code>import os path = "a/b/c/abc.txt" print os.path.splitext(os.path.basename(path))[0] </code></pre>
2
2015-05-28T13:24:52Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
37,760,212
<p>os.path.splitext() <strong>won't</strong> work if there are multiple dots in the extension.</p> <p>For example, images.tar.gz</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; file_path = '/home/dc/images.tar.gz' &gt;&gt;&gt; file_name = os.path.basename(file_path) &gt;&gt;&gt; print os.path.splitext(file_name)[0] images.tar </code></pre> <p>You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; file_path = '/home/dc/images.tar.gz' &gt;&gt;&gt; file_name = os.path.basename(file_path) &gt;&gt;&gt; index_of_dot = file_name.index('.') &gt;&gt;&gt; file_name_without_extension = file_name[:index_of_dot] &gt;&gt;&gt; print file_name_without_extension images </code></pre>
2
2016-06-11T05:17:08Z
[ "python", "string", "path" ]
How to get the filename without the extension from a path in Python?
678,236
<p>How to get the filename without the extension from a path in Python?</p> <p>I found out a method called <code>os.path.basename</code> to get the filename with extension. But even when I import os, I am not able to call it <code>path.basename</code>. Is it possible to call it as directly as basename?</p>
294
2009-03-24T16:41:03Z
39,648,242
<p>For convenience, a simple function wrapping the two methods from <a href="https://docs.python.org/3/library/os.path.html" rel="nofollow"><code>os.path</code></a> :</p> <pre><code>def filename(path): """Return file name without extension from path. See https://docs.python.org/3/library/os.path.html """ import os.path b = os.path.split(path)[1] # path, *filename* f = os.path.splitext(b)[0] # *file*, ext #print(path, b, f) return f </code></pre> <p>Tested with Python 3.5.</p>
0
2016-09-22T20:23:28Z
[ "python", "string", "path" ]
Does any one know of an RTF report generator in Django?
678,308
<p>I know about the PDF report generator, but I need to use RTF instead.</p>
3
2009-03-24T17:00:38Z
678,670
<p>There is <a href="http://pypi.python.org/pypi/PyRTF/0.45" rel="nofollow">PyRTF</a> but it hasn't been updated in a while.</p> <p>If that doesn't work and you are willing to do some hacking then I can also point you to the <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage" rel="nofollow">GRAMPS Project</a> that has an RTF report generator (look in gramps/docgen/RTFDoc.py). This code is very specific to their genealogy reporting needs, but it is clean and decently documented so could make a good starting point.</p>
3
2009-03-24T18:40:03Z
[ "python", "django", "report", "rtf" ]
Does any one know of an RTF report generator in Django?
678,308
<p>I know about the PDF report generator, but I need to use RTF instead.</p>
3
2009-03-24T17:00:38Z
1,336,541
<p><code>(can't comment yet so I post it as an answer)</code></p> <p>There's a fork of PyRTF called <a href="http://code.google.com/p/pyrtf-ng/" rel="nofollow">pyrtf-ng</a>, it's maintained and has Unicode support. Documentation doesn't exist from what I've seen, but api looks nice, and you can figure out a lot from tests in <code>tests</code> dir.</p>
2
2009-08-26T18:11:14Z
[ "python", "django", "report", "rtf" ]
Does any one know of an RTF report generator in Django?
678,308
<p>I know about the PDF report generator, but I need to use RTF instead.</p>
3
2009-03-24T17:00:38Z
5,085,766
<p><a href="http://www.windwardreports.com/" rel="nofollow">Windward Reports</a> has a very nice RTF generator. And you create the template in Word so very easy to use. (Disclaimer - I'm the CTO at Windward.) And yes the Java engine is callable from Python.</p>
0
2011-02-23T00:31:39Z
[ "python", "django", "report", "rtf" ]
soaplib with mod_wsgi/cherrypy
678,409
<p>I've followed the tutorials for setting up Apache with mod_wsgi to interface cherrypy and make a site running of it. This is my "myapp.wsgi", and opening <a href="http://localhost/" rel="nofollow">http://localhost/</a> works great. Opening <a href="http://localhost/ape/" rel="nofollow">http://localhost/ape/</a> actually returns the text instead of a soap-response, and <a href="http://localhost/ape/service.wsdl" rel="nofollow">http://localhost/ape/service.wsdl</a> returns a 500 HTTP error code. What am I doing wrong in getting such a simple SOAP service to run? How can I get it to return valid WSDL? My code follows below</p> <p>Cheers</p> <p>Nik</p> <pre><code>import atexit, threading, cherrypy,sys from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers.primitive import String, Integer, Array sys.stdout = sys.stderr cherrypy.config.update({'environment': 'embedded'}) class Root(object): def index(self): return 'Hello World!' index.exposed = True @soapmethod(_returns=String) def ape(self): return 'Ape!!' ape.exposed = True application = cherrypy.Application(Root(), None) </code></pre>
1
2009-03-24T17:28:40Z
678,527
<p>I just tested this myself by replacing the last line of your file with</p> <pre><code>cherrypy.quickstart(Root(), "/") </code></pre> <p>and it worked just fine for me. I suggest trying this and seeing whether it works for you; if it does then you'll know that it's an issue relating to running it under Apache/mod_wsgi and not an inherent problem with your code.</p>
1
2009-03-24T17:59:45Z
[ "python", "soap", "mod-wsgi", "cherrypy" ]
soaplib with mod_wsgi/cherrypy
678,409
<p>I've followed the tutorials for setting up Apache with mod_wsgi to interface cherrypy and make a site running of it. This is my "myapp.wsgi", and opening <a href="http://localhost/" rel="nofollow">http://localhost/</a> works great. Opening <a href="http://localhost/ape/" rel="nofollow">http://localhost/ape/</a> actually returns the text instead of a soap-response, and <a href="http://localhost/ape/service.wsdl" rel="nofollow">http://localhost/ape/service.wsdl</a> returns a 500 HTTP error code. What am I doing wrong in getting such a simple SOAP service to run? How can I get it to return valid WSDL? My code follows below</p> <p>Cheers</p> <p>Nik</p> <pre><code>import atexit, threading, cherrypy,sys from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers.primitive import String, Integer, Array sys.stdout = sys.stderr cherrypy.config.update({'environment': 'embedded'}) class Root(object): def index(self): return 'Hello World!' index.exposed = True @soapmethod(_returns=String) def ape(self): return 'Ape!!' ape.exposed = True application = cherrypy.Application(Root(), None) </code></pre>
1
2009-03-24T17:28:40Z
688,069
<p>Eli is right; it's not enough to just make an Application instance. You have to mount it on cherrypy.tree, which quickstart() does for you.</p>
1
2009-03-27T00:27:15Z
[ "python", "soap", "mod-wsgi", "cherrypy" ]
How can I add non-sequential numbers to a range?
678,410
<p>I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:</p> <pre><code> >>> for x in range(750, 765), 769, 770, 774: print x ... [750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764] 769 770 774 </code></pre> <p>How can I get all the numbers in a single list?</p>
5
2009-03-24T17:28:44Z
678,421
<p>Use the built-in + operator to append your non-sequential numbers to the range.</p> <pre><code>for x in range(750, 765) + [769, 770, 774]: print x </code></pre>
21
2009-03-24T17:31:23Z
[ "python", "range" ]
How can I add non-sequential numbers to a range?
678,410
<p>I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:</p> <pre><code> >>> for x in range(750, 765), 769, 770, 774: print x ... [750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764] 769 770 774 </code></pre> <p>How can I get all the numbers in a single list?</p>
5
2009-03-24T17:28:44Z
678,423
<p>are you looking for this:</p> <pre><code>mylist = range(750, 765) mylist.extend([769, 770, 774]) </code></pre>
2
2009-03-24T17:32:18Z
[ "python", "range" ]
How can I add non-sequential numbers to a range?
678,410
<p>I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:</p> <pre><code> >>> for x in range(750, 765), 769, 770, 774: print x ... [750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764] 769 770 774 </code></pre> <p>How can I get all the numbers in a single list?</p>
5
2009-03-24T17:28:44Z
678,429
<p>There are two ways to do it.</p> <pre><code>&gt;&gt;&gt; for x in range(5, 7) + [8, 9]: print x ... 5 6 8 9 &gt;&gt;&gt; import itertools &gt;&gt;&gt; for x in itertools.chain(xrange(5, 7), [8, 9]): print x ... 5 6 8 9 </code></pre> <p><a href="http://docs.python.org/library/itertools.html#itertools.chain">itertools.chain()</a> is by far superior, since it allows you to use arbitrary iterables, rather than just lists and lists. It's also more efficient, not requiring list copying. And it lets you use xrange, which you should when looping.</p>
13
2009-03-24T17:33:50Z
[ "python", "range" ]
How can I add non-sequential numbers to a range?
678,410
<p>I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:</p> <pre><code> >>> for x in range(750, 765), 769, 770, 774: print x ... [750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764] 769 770 774 </code></pre> <p>How can I get all the numbers in a single list?</p>
5
2009-03-24T17:28:44Z
678,436
<p>The other answers on this page will serve you well. Just a quick note that in Python3.0, <code>range</code> is an iterator (like xrange was in Python2.x... xrange is gone in 3.0). If you try to do this in Python 3.0, be sure to create a list from the range iterator before doing the addition:</p> <pre><code>for x in list(range(750, 765)) + [769, 770, 774]: print(x) </code></pre>
5
2009-03-24T17:34:51Z
[ "python", "range" ]
What payment processing frameworks, like ActiveMerchant, are available for other languages?
678,525
<p>Rails has frameworks such as <a href="http://www.activemerchant.org/" rel="nofollow">ActiveMerchant</a> and <a href="http://github.com/cainlevy/freemium/tree/master" rel="nofollow">Freemium</a> (which uses ActiveMerchant) to simplify dealing with payment processing. What other frameworks are there for other programming languages such as PHP or Python?</p>
6
2009-03-24T17:59:00Z
678,542
<p><strong>Edit</strong> For processing payments, there are several GetPaid modules available for Python. Check out the <a href="http://pypi.python.org/pypi/getpaid.core/0.7.3" rel="nofollow">core package</a>, as well as <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=getpaid&amp;submit=search" rel="nofollow">some extensions for different payment methods</a>.</p> <p><em>----------original answer------------</em></p> <p>From a <a href="http://stackoverflow.com/questions/76420/best-php-ruby-python-e-commerce-solution">StackOverflow search</a>: <a href="http://www.satchmoproject.com/" rel="nofollow">Satchmo</a> is a Python alternative.</p> <p>See that question link above for other ideas.</p>
2
2009-03-24T18:04:01Z
[ "php", "python", "ruby-on-rails", "programming-languages", "activemerchant" ]
Select Distinct Years and Months for Django Archive Page
678,927
<p>I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this</p> <pre>2009 - Jan, Feb, Mar 2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 2007 - Sep, Oct, Nov, Dec</pre>
7
2009-03-24T19:37:30Z
678,966
<p>You should be able to get all the info you describe from the built-in views. Can you be more specific as to what you cannot get? This should have everything you need:</p> <pre><code>django.views.generic.date_based.archive_month </code></pre> <p><a href="http://docs.djangobrasil.org/ref/generic-views.html" rel="nofollow">Reference page</a> (search for the above string on that page)</p>
1
2009-03-24T19:46:38Z
[ "python", "django", "datetime", "django-views", "django-queryset" ]
Select Distinct Years and Months for Django Archive Page
678,927
<p>I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this</p> <pre>2009 - Jan, Feb, Mar 2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 2007 - Sep, Oct, Nov, Dec</pre>
7
2009-03-24T19:37:30Z
679,105
<p>This will give you a list of unique posting dates:</p> <pre><code>Posts.objects.filter(draft=False).dates('post_date','month',order='DESC') </code></pre> <p>Of course you might not need the draft filter, and change 'post_date' to your field name, etc.</p>
28
2009-03-24T20:26:37Z
[ "python", "django", "datetime", "django-views", "django-queryset" ]
Select Distinct Years and Months for Django Archive Page
678,927
<p>I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this</p> <pre>2009 - Jan, Feb, Mar 2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 2007 - Sep, Oct, Nov, Dec</pre>
7
2009-03-24T19:37:30Z
679,164
<p>I found the answer to my own question. </p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/">It's on this page</a> in the documentation.</p> <p>There's a function called dates that will give you distinct dates. So I can do</p> <p>Entry.objects.dates('pub_date','month') to get a list of datetime objects, one for each year/month. </p>
9
2009-03-24T20:39:09Z
[ "python", "django", "datetime", "django-views", "django-queryset" ]
Why does windows give an sqlite3.OperationalError and linux does not?
679,162
<h1>The problem</h1> <p>I've got a programm that uses <a href="http://storm.canonical.com" rel="nofollow">storm 0.14</a> and it gives me this error on windows:</p> <pre> sqlite3.OperationError: database table is locked </pre> <p>The thing is, under linux it works correctly.</p> <p>I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects.</p> <p>Turning on the debug mode gives me this on windows:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked </pre> <p>On linux:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE </pre> <h1>System info</h1> <p><em>Windows</em></p> <ul> <li>Windows XP SP 3</li> <li>Python 2.5.4</li> <li>NTFS partition</li> </ul> <p><em>Linux</em></p> <ul> <li>Ubuntu 8.10</li> <li>Python 2.5.2</li> <li>ext3 partition</li> </ul> <h1>Some code</h1> <pre><code>def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week </code></pre> <h1>The question</h1> <p>Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it?</p> <h1>Another observation</h1> <p>When adding a <code>COMMIT</code> at the place where the error happens, this error is thrown instead: <code>sqlite3.OperationalError: cannot commit transaction - SQL statements in progress</code></p> <h1>Answers to answers</h1> <p>I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object.</p>
3
2009-03-24T20:38:04Z
679,186
<p>The "database table is locked" error is often a generic/default error in SQLite, so narrowing down your problem is not obvious.</p> <p>Are you able to execute <em>any</em> SQL queries? I would start there, and get some basic SELECT statements working. It could just be a permissions issue.</p>
1
2009-03-24T20:48:23Z
[ "python", "windows", "linux", "sqlite" ]
Why does windows give an sqlite3.OperationalError and linux does not?
679,162
<h1>The problem</h1> <p>I've got a programm that uses <a href="http://storm.canonical.com" rel="nofollow">storm 0.14</a> and it gives me this error on windows:</p> <pre> sqlite3.OperationError: database table is locked </pre> <p>The thing is, under linux it works correctly.</p> <p>I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects.</p> <p>Turning on the debug mode gives me this on windows:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked </pre> <p>On linux:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE </pre> <h1>System info</h1> <p><em>Windows</em></p> <ul> <li>Windows XP SP 3</li> <li>Python 2.5.4</li> <li>NTFS partition</li> </ul> <p><em>Linux</em></p> <ul> <li>Ubuntu 8.10</li> <li>Python 2.5.2</li> <li>ext3 partition</li> </ul> <h1>Some code</h1> <pre><code>def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week </code></pre> <h1>The question</h1> <p>Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it?</p> <h1>Another observation</h1> <p>When adding a <code>COMMIT</code> at the place where the error happens, this error is thrown instead: <code>sqlite3.OperationalError: cannot commit transaction - SQL statements in progress</code></p> <h1>Answers to answers</h1> <p>I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object.</p>
3
2009-03-24T20:38:04Z
679,194
<p>Hard to say without a little more info on the structure of your database access (which is a little obscured by using Storm).</p> <p><em>I'd start by reading these documents; they contain very relevant information:</em></p> <ol> <li><p>https://storm.canonical.com/Manual#SQLite%20and%20threads</p></li> <li><p><a href="http://sqlite.org/lockingv3.html" rel="nofollow">http://sqlite.org/lockingv3.html</a></p></li> </ol>
1
2009-03-24T20:51:23Z
[ "python", "windows", "linux", "sqlite" ]
Why does windows give an sqlite3.OperationalError and linux does not?
679,162
<h1>The problem</h1> <p>I've got a programm that uses <a href="http://storm.canonical.com" rel="nofollow">storm 0.14</a> and it gives me this error on windows:</p> <pre> sqlite3.OperationError: database table is locked </pre> <p>The thing is, under linux it works correctly.</p> <p>I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects.</p> <p>Turning on the debug mode gives me this on windows:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked </pre> <p>On linux:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE </pre> <h1>System info</h1> <p><em>Windows</em></p> <ul> <li>Windows XP SP 3</li> <li>Python 2.5.4</li> <li>NTFS partition</li> </ul> <p><em>Linux</em></p> <ul> <li>Ubuntu 8.10</li> <li>Python 2.5.2</li> <li>ext3 partition</li> </ul> <h1>Some code</h1> <pre><code>def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week </code></pre> <h1>The question</h1> <p>Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it?</p> <h1>Another observation</h1> <p>When adding a <code>COMMIT</code> at the place where the error happens, this error is thrown instead: <code>sqlite3.OperationalError: cannot commit transaction - SQL statements in progress</code></p> <h1>Answers to answers</h1> <p>I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object.</p>
3
2009-03-24T20:38:04Z
679,291
<p>Are you running any sort of anti-virus scanners? Anti-virus scanners will frequently lock a file after it has been updated, so that they can inspect it without it being changed. This may explain why you get this error after a lot of changes have been made; the anti-virus scanner has more new data to scan.</p> <p>If you are running an anti-virus scanner, try turning it off and see if you can reproduce this problem.</p>
1
2009-03-24T21:19:51Z
[ "python", "windows", "linux", "sqlite" ]
Why does windows give an sqlite3.OperationalError and linux does not?
679,162
<h1>The problem</h1> <p>I've got a programm that uses <a href="http://storm.canonical.com" rel="nofollow">storm 0.14</a> and it gives me this error on windows:</p> <pre> sqlite3.OperationError: database table is locked </pre> <p>The thing is, under linux it works correctly.</p> <p>I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects.</p> <p>Turning on the debug mode gives me this on windows:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked </pre> <p>On linux:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE </pre> <h1>System info</h1> <p><em>Windows</em></p> <ul> <li>Windows XP SP 3</li> <li>Python 2.5.4</li> <li>NTFS partition</li> </ul> <p><em>Linux</em></p> <ul> <li>Ubuntu 8.10</li> <li>Python 2.5.2</li> <li>ext3 partition</li> </ul> <h1>Some code</h1> <pre><code>def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week </code></pre> <h1>The question</h1> <p>Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it?</p> <h1>Another observation</h1> <p>When adding a <code>COMMIT</code> at the place where the error happens, this error is thrown instead: <code>sqlite3.OperationalError: cannot commit transaction - SQL statements in progress</code></p> <h1>Answers to answers</h1> <p>I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object.</p>
3
2009-03-24T20:38:04Z
679,438
<p>It looks to me like storm is broken, though my first guess was virus scanner as Brian suggested.</p> <p>Have you tried using <code>sqlite3_busy_timeout()</code> to set the timeout very high? This might cause <code>SQLite3</code> to wait long enough for the lock holder, whoever that is, to release the lock.</p>
1
2009-03-24T22:03:16Z
[ "python", "windows", "linux", "sqlite" ]
Why does windows give an sqlite3.OperationalError and linux does not?
679,162
<h1>The problem</h1> <p>I've got a programm that uses <a href="http://storm.canonical.com" rel="nofollow">storm 0.14</a> and it gives me this error on windows:</p> <pre> sqlite3.OperationError: database table is locked </pre> <p>The thing is, under linux it works correctly.</p> <p>I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects.</p> <p>Turning on the debug mode gives me this on windows:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked </pre> <p>On linux:</p> <pre> 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE </pre> <h1>System info</h1> <p><em>Windows</em></p> <ul> <li>Windows XP SP 3</li> <li>Python 2.5.4</li> <li>NTFS partition</li> </ul> <p><em>Linux</em></p> <ul> <li>Ubuntu 8.10</li> <li>Python 2.5.2</li> <li>ext3 partition</li> </ul> <h1>Some code</h1> <pre><code>def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week </code></pre> <h1>The question</h1> <p>Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it?</p> <h1>Another observation</h1> <p>When adding a <code>COMMIT</code> at the place where the error happens, this error is thrown instead: <code>sqlite3.OperationalError: cannot commit transaction - SQL statements in progress</code></p> <h1>Answers to answers</h1> <p>I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object.</p>
3
2009-03-24T20:38:04Z
680,390
<p>I've solved the problem at the moment by replacing the sqlite3-dll with the newest version. I'm still not sure if this was a bug in the windows code of sqlite or if python installed an older version on windows than on linux.</p> <p>Thanks for your help.</p>
1
2009-03-25T06:04:53Z
[ "python", "windows", "linux", "sqlite" ]