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 |
|---|---|---|---|---|---|---|---|---|---|
Reducing Django Memory Usage. Low hanging fruit?
| 487,224
|
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127
|
2009-01-28T10:52:19Z
| 4,684,418
|
<p>We stumbled over a bug in Django with big sitemaps (10.000 items). Seems Django is trying to load them all in memory when generating the sitemap: <a href="http://code.djangoproject.com/ticket/11572" rel="nofollow">http://code.djangoproject.com/ticket/11572</a> - effectively kills the apache process when Google pays a visit to the site.</p>
| 1
|
2011-01-13T19:37:37Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Client Server programming in python?
| 487,229
|
<p>Here is source code for multithreaed server and client in python.</p>
<p>In the code client and server closes connection after the job is finished.
I want to keep the connections alive and send more data over the same connections to <strong>avoid overhead of closing and opening sockets every time</strong>.</p>
<p>Following code is from : <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/</a></p>
<pre><code>import pickle
import socket
import threading
# We'll pickle a list of numbers:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# Our thread class:
class ClientThread ( threading.Thread ):
# Override Thread's __init__ method to accept the parameters needed:
def __init__ ( self, channel, details ):
self.channel = channel
self.details = details
threading.Thread.__init__ ( self )
def run ( self ):
print 'Received connection:', self.details [ 0 ]
self.channel.send ( pickledList )
for x in xrange ( 10 ):
print self.channel.recv ( 1024 )
self.channel.close()
print 'Closed connection:', self.details [ 0 ]
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
channel, details = server.accept()
ClientThread ( channel, details ).start()
</code></pre>
<hr>
<pre><code>import pickle
import socket
import threading
# Here's our thread:
class ConnectionThread ( threading.Thread ):
def run ( self ):
# Connect to the server:
client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
client.connect ( ( 'localhost', 2727 ) )
# Retrieve and unpickle the list object:
print pickle.loads ( client.recv ( 1024 ) )
# Send some messages:
for x in xrange ( 10 ):
client.send ( 'Hey. ' + str ( x ) + '\n' )
# Close the connection
client.close()
# Let's spawn a few threads:
for x in xrange ( 5 ):
ConnectionThread().start()
</code></pre>
| 8
|
2009-01-28T10:55:51Z
| 487,255
|
<p>I'm not sure I understand the question, but don't call <code>close()</code> if you don't want to close the connection...</p>
| 2
|
2009-01-28T11:08:09Z
|
[
"python",
"multithreading",
"client",
"sockets"
] |
Client Server programming in python?
| 487,229
|
<p>Here is source code for multithreaed server and client in python.</p>
<p>In the code client and server closes connection after the job is finished.
I want to keep the connections alive and send more data over the same connections to <strong>avoid overhead of closing and opening sockets every time</strong>.</p>
<p>Following code is from : <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/</a></p>
<pre><code>import pickle
import socket
import threading
# We'll pickle a list of numbers:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# Our thread class:
class ClientThread ( threading.Thread ):
# Override Thread's __init__ method to accept the parameters needed:
def __init__ ( self, channel, details ):
self.channel = channel
self.details = details
threading.Thread.__init__ ( self )
def run ( self ):
print 'Received connection:', self.details [ 0 ]
self.channel.send ( pickledList )
for x in xrange ( 10 ):
print self.channel.recv ( 1024 )
self.channel.close()
print 'Closed connection:', self.details [ 0 ]
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
channel, details = server.accept()
ClientThread ( channel, details ).start()
</code></pre>
<hr>
<pre><code>import pickle
import socket
import threading
# Here's our thread:
class ConnectionThread ( threading.Thread ):
def run ( self ):
# Connect to the server:
client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
client.connect ( ( 'localhost', 2727 ) )
# Retrieve and unpickle the list object:
print pickle.loads ( client.recv ( 1024 ) )
# Send some messages:
for x in xrange ( 10 ):
client.send ( 'Hey. ' + str ( x ) + '\n' )
# Close the connection
client.close()
# Let's spawn a few threads:
for x in xrange ( 5 ):
ConnectionThread().start()
</code></pre>
| 8
|
2009-01-28T10:55:51Z
| 487,281
|
<p>Spawning a new thread for every connection is a <strong>really bad</strong> design choice.
What happens if you get hit by a lot of connections?</p>
<p>In fact, using threads to wait for network IO is not worth it. Your program gets really complex and you get absolutely <strong>no benefit</strong> since waiting for network in threads won't make you <strong>wait faster</strong>. You only lose by using threads in this case.</p>
<p>The following text is from python documentation:</p>
<blockquote>
<p>There are only two ways to have a
program on a single processor do âmore
than one thing at a time.â
Multi-threaded programming is the
simplest and most popular way to do
it, but there is another very
different technique, that lets you
have nearly all the advantages of
multi-threading, without actually
using multiple threads. Itâs really
only practical if your program is
largely I/O bound. If your program is
processor bound, then pre-emptive
scheduled threads are probably what
you really need. Network servers are
rarely processor bound, however.</p>
</blockquote>
<p>And if it is a processor bound server case. you could always leave another process/thread to do the processor part. Continuing:</p>
<blockquote>
<p>If your operating system supports the
select system call in its I/O library
(and nearly all do), then you can use
it to juggle multiple communication
channels at once; doing other work
while your I/O is taking place in the
âbackground.â Although this strategy
can seem strange and complex,
especially at first, it is in many
ways easier to understand and control
than multi-threaded programming.</p>
</blockquote>
<p>So instead of using threads, use non-blocking input/output: collect the sockets in a list and use an event loop with <a href="http://docs.python.org/library/select.html#select.select">select.select</a> to know which socket has data to read. Do that in a single thread.</p>
<p>You could choose a python asynchronous networking framework like <a href="http://twistedmatrix.com/">twisted</a> to do that for you. That will save you a lot of headaches. Twisted's code has been improved for years, and covers some corner cases you'll take time to master.</p>
<p><strong>EDIT</strong>: Any existing async IO libraries (like Twisted) are python code. You could have written it yourself, but it has already been written for you. I don't see why you wouldn't use one of those libraries and write your own <strong>worst</strong> code instead, since you are a beginner. Networing IO is hard to get right.</p>
| 18
|
2009-01-28T11:19:49Z
|
[
"python",
"multithreading",
"client",
"sockets"
] |
Client Server programming in python?
| 487,229
|
<p>Here is source code for multithreaed server and client in python.</p>
<p>In the code client and server closes connection after the job is finished.
I want to keep the connections alive and send more data over the same connections to <strong>avoid overhead of closing and opening sockets every time</strong>.</p>
<p>Following code is from : <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/</a></p>
<pre><code>import pickle
import socket
import threading
# We'll pickle a list of numbers:
someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )
# Our thread class:
class ClientThread ( threading.Thread ):
# Override Thread's __init__ method to accept the parameters needed:
def __init__ ( self, channel, details ):
self.channel = channel
self.details = details
threading.Thread.__init__ ( self )
def run ( self ):
print 'Received connection:', self.details [ 0 ]
self.channel.send ( pickledList )
for x in xrange ( 10 ):
print self.channel.recv ( 1024 )
self.channel.close()
print 'Closed connection:', self.details [ 0 ]
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
channel, details = server.accept()
ClientThread ( channel, details ).start()
</code></pre>
<hr>
<pre><code>import pickle
import socket
import threading
# Here's our thread:
class ConnectionThread ( threading.Thread ):
def run ( self ):
# Connect to the server:
client = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
client.connect ( ( 'localhost', 2727 ) )
# Retrieve and unpickle the list object:
print pickle.loads ( client.recv ( 1024 ) )
# Send some messages:
for x in xrange ( 10 ):
client.send ( 'Hey. ' + str ( x ) + '\n' )
# Close the connection
client.close()
# Let's spawn a few threads:
for x in xrange ( 5 ):
ConnectionThread().start()
</code></pre>
| 8
|
2009-01-28T10:55:51Z
| 487,284
|
<p>For an example of a client the keeps a TCP connection open and uses a familiar protocol,
look at the <a href="http://svn.python.org/view/python/trunk/Lib/telnetlib.py?rev=63788&view=log" rel="nofollow">source</a> of the <a href="http://docs.python.org/library/telnetlib.html#module-telnetlib" rel="nofollow">telnetlib module</a>. (sorry, someone else will have to answer your threading questions.)</p>
<p>An example of a server that keeps a TCP connection open is in the source for the <a href="http://docs.python.org/library/socketserver.html" rel="nofollow">SocketServer module</a> (any standard Python installation includes the source).</p>
| 0
|
2009-01-28T11:20:54Z
|
[
"python",
"multithreading",
"client",
"sockets"
] |
pyqt import problem
| 487,484
|
<p>I am having some trouble doing this in Python:</p>
<pre><code>from PyQt4 import QtCore, QtGui
from dcopext import DCOPClient, DCOPApp
</code></pre>
<p>The traceback I get is</p>
<pre><code>from dcopext import DCOPClient, DCOPApp
File "/usr/lib/python2.5/site-packages/dcopext.py", line 35, in <module>
from dcop import DCOPClient
RuntimeError: the qt and PyQt4.QtCore modules both wrap the QObject class
</code></pre>
<p>I tried switching the imports, importing dcopext later in the file, but none worked.
Thanks for any suggestions.</p>
<p><strong>Edit:</strong> I have narrowed it down to one problem: I am using dcopext which internally uses qt3, but I want it to use PyQt4.</p>
| 2
|
2009-01-28T12:44:30Z
| 487,568
|
<p>The <code>dcopext</code> module is part of <a href="http://www.riverbankcomputing.co.uk/software/pykde/intro" rel="nofollow">PyKDE3</a>, the Python bindings for KDE3 which uses Qt 3.x, while you're using PyQt/Qt 4.x. </p>
<p>You need to upgrade to <a href="http://techbase.kde.org/Development/Languages/Python/Using_PyKDE_4" rel="nofollow">PyKDE4</a>, now released as part of KDE itself, unless you want to target KDE 3 in which case you need a corresponding old version of Qt and PyQt (3.x).</p>
| 1
|
2009-01-28T13:14:55Z
|
[
"python",
"pyqt",
"dcop"
] |
Transfering object through Pyro
| 487,553
|
<p>I'm using Pyro in a project, and can't seem to understand how to transfer a complete object over the wire. The object is <strong>not</strong> distributed (my distributed objects works perfectly fine), but should function as an argument to an already available distributed object. </p>
<p>My object is a derived from a custom class containing some methods and some variables - an integer and a list. The class is available for both the server and the client. When using my object as an argument to a method of a distributed object the integer variable is "received" correctly, but the list is empty, even though I can see that it contains values just before it's "sent".</p>
<p>Why is this?</p>
<p>Short version of the class:</p>
<pre><code>class Collection(Pyro.core.ObjBase):
num = 0
operations = [("Operation:", "Value:", "Description", "Timestamp")]
def __init__(self):
Pyro.core.ObjBase.__init__(self)
def add(self, val, desc):
entry = ("Add", val, desc, strftime("%Y-%m-%d %H:%M:%S"))
self.operations.append(entry)
self.num = self.num + 1
def printop(self):
print "This collection will execute the following operations:"
for item in self.operations:
print item
</code></pre>
<p>The receving method in the distributed object:</p>
<pre><code>def apply(self, collection):
print "Todo: Apply collection"
#op = collection.getop()
print "Number of collected operations:", collection.a
collection.printop()
</code></pre>
| 4
|
2009-01-28T13:07:31Z
| 487,720
|
<p>Operations is a class attribute, not the object attribute. That is why it's not transferred. Try setting it in <code>__init__</code> via <code>self.operations = <whatever></code>.</p>
| 4
|
2009-01-28T14:04:50Z
|
[
"python",
"distributed"
] |
Transfering object through Pyro
| 487,553
|
<p>I'm using Pyro in a project, and can't seem to understand how to transfer a complete object over the wire. The object is <strong>not</strong> distributed (my distributed objects works perfectly fine), but should function as an argument to an already available distributed object. </p>
<p>My object is a derived from a custom class containing some methods and some variables - an integer and a list. The class is available for both the server and the client. When using my object as an argument to a method of a distributed object the integer variable is "received" correctly, but the list is empty, even though I can see that it contains values just before it's "sent".</p>
<p>Why is this?</p>
<p>Short version of the class:</p>
<pre><code>class Collection(Pyro.core.ObjBase):
num = 0
operations = [("Operation:", "Value:", "Description", "Timestamp")]
def __init__(self):
Pyro.core.ObjBase.__init__(self)
def add(self, val, desc):
entry = ("Add", val, desc, strftime("%Y-%m-%d %H:%M:%S"))
self.operations.append(entry)
self.num = self.num + 1
def printop(self):
print "This collection will execute the following operations:"
for item in self.operations:
print item
</code></pre>
<p>The receving method in the distributed object:</p>
<pre><code>def apply(self, collection):
print "Todo: Apply collection"
#op = collection.getop()
print "Number of collected operations:", collection.a
collection.printop()
</code></pre>
| 4
|
2009-01-28T13:07:31Z
| 487,740
|
<p>Your receiving method, <strong>apply</strong>, has the same name as the built-in Python function.</p>
| 1
|
2009-01-28T14:10:33Z
|
[
"python",
"distributed"
] |
Inventory Control Across Multiple Servers .. Ideas?
| 487,642
|
<p>We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. </p>
<p>This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.</p>
<p>Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.</p>
<p>See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.</p>
<p>Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.</p>
<p>The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.</p>
<p>Thanks in advance for any answers, and I hope that made sense .. I can elaborate.</p>
| 0
|
2009-01-28T13:39:54Z
| 487,660
|
<p>One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches against the inventory system.</p>
<p>Notes:</p>
<ol>
<li><p>You would still have to add a reasonable security layer to the inventory service in case the web shopfront was compromised.</p></li>
<li><p>You would have to make sure your inventory management application and server was big enough to handle the load, or could be reasonably easily scaled so it could do so.</p></li>
</ol>
<p>Your SLA for the inventory application would need to be good enough to support the web shopfront. This probably means some sort of hot failover arrangement.</p>
| 1
|
2009-01-28T13:45:27Z
|
[
"python",
"tracking",
"inventory"
] |
Inventory Control Across Multiple Servers .. Ideas?
| 487,642
|
<p>We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. </p>
<p>This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.</p>
<p>Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.</p>
<p>See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.</p>
<p>Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.</p>
<p>The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.</p>
<p>Thanks in advance for any answers, and I hope that made sense .. I can elaborate.</p>
| 0
|
2009-01-28T13:39:54Z
| 487,674
|
<p>I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database.</p>
<p>Of course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refactor to use something sort of actual DB sooner rather than later.</p>
| 0
|
2009-01-28T13:50:56Z
|
[
"python",
"tracking",
"inventory"
] |
Inventory Control Across Multiple Servers .. Ideas?
| 487,642
|
<p>We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. </p>
<p>This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.</p>
<p>Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.</p>
<p>See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.</p>
<p>Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.</p>
<p>The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.</p>
<p>Thanks in advance for any answers, and I hope that made sense .. I can elaborate.</p>
| 0
|
2009-01-28T13:39:54Z
| 706,707
|
<p>I'm not sure if there is any one really good solution for your problem. I think the way you are doing it now works fine, but if you don't agree then I don't know what to tell you.</p>
| 0
|
2009-04-01T18:03:48Z
|
[
"python",
"tracking",
"inventory"
] |
Inventory Control Across Multiple Servers .. Ideas?
| 487,642
|
<p>We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. </p>
<p>This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.</p>
<p>Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.</p>
<p>See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.</p>
<p>Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.</p>
<p>The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.</p>
<p>Thanks in advance for any answers, and I hope that made sense .. I can elaborate.</p>
| 0
|
2009-01-28T13:39:54Z
| 3,858,221
|
<p>I know you wanted to find a solution that works with your existing code, but have you considered a third party multi channel manager system? As your business grows and the scale of your orders increase, it may become easier to use a multi channel manager system such as Mailware. As an <a href="http://www.mailware.com/mailware/mailware-features/inventory/inventory-control/" rel="nofollow">inventory control software</a>, it handles a large number of orders for multiple locations and manages your inventory levels at the multiple locations. This software also integrates with shopping cart software to give your customers accurate levels of inventory to prevent back orders. Best of luck to you.</p>
| 1
|
2010-10-04T18:54:38Z
|
[
"python",
"tracking",
"inventory"
] |
How can I get interactive Python to avoid using readline while allowing utf-8 input?
| 487,800
|
<p>I use a terminal (9term) that does command-line editing itself - programs that use readline just get in its way. It's fully utf-8 aware. How can I make an interactive python session disable readline while retaining utf-8 input and output?</p>
<p>Currently I use:</p>
<pre><code>LANG=en_GB.UTF-8 export LANG
cat | python -i
</code></pre>
<p>however this causes sys.stdin.encoding to be None, which implies Ascii
(the system default encoding, which doesn't seem to be changeable)</p>
<pre><code>TERM=dumb python
</code></pre>
<p>doesn't disable readline (and it mangles utf-8 input also).</p>
<p>I'm new to python, so apologies if this is an obvious question.</p>
| 3
|
2009-01-28T14:26:28Z
| 487,891
|
<p>In the past, I've disabled Python readline by rebuilding it from source: <code>configure --disable-readline</code></p>
<p>This might be overkill, though, for your situation.</p>
| 2
|
2009-01-28T14:51:43Z
|
[
"python",
"utf-8",
"interactive"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 487,981
|
<p>print dir(module)</p>
| 0
|
2009-01-28T15:13:17Z
|
[
"python",
"module",
"package"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 489,489
|
<pre><code>import module
help(module)
</code></pre>
| 11
|
2009-01-28T21:35:25Z
|
[
"python",
"module",
"package"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 489,649
|
<p>Maybe this will do what you're looking for?</p>
<pre><code>import imp
import os
MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')
def package_contents(package_name):
file, pathname, description = imp.find_module(package_name)
if file:
raise ImportError('Not a package: %r', package_name)
# Use a set because some may be both source and compiled.
return set([os.path.splitext(module)[0]
for module in os.listdir(pathname)
if module.endswith(MODULE_EXTENSIONS)])
</code></pre>
| 14
|
2009-01-28T22:14:44Z
|
[
"python",
"module",
"package"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 681,980
|
<pre><code>def package_contents(package_name):
package = __import__(package_name)
return [module_name for module_name in dir(package) if not module_name.startswith("__")]
</code></pre>
| -2
|
2009-03-25T14:58:11Z
|
[
"python",
"module",
"package"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 1,310,912
|
<p>Using <a href="http://docs.python.org/library/pkgutil.html">python2.3 and above</a>, you could also use the <code>pkgutil</code> module:</p>
<pre><code>>>> import pkgutil
>>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])]
['modulea', 'moduleb']
</code></pre>
<p><strong>EDIT:</strong> Note that the parameter is not a list of modules, but a list of paths, so you might want to do something like this:</p>
<pre><code>>>> import os.path, pkgutil
>>> import testpkg
>>> pkgpath = os.path.dirname(testpkg.__file__)
>>> print [name for _, name, _ in pkgutil.iter_modules([pkgpath])]
</code></pre>
| 124
|
2009-08-21T09:21:02Z
|
[
"python",
"module",
"package"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 15,833,780
|
<p><strike>Don't know if I'm overlooking something, or if the answers are just out-dated but;</strike></p>
<p>As stated by user815423426 this only works for live objects and the listed modules are only modules that were imported before.</p>
<p>Listing modules in a package seems really easy using <a href="http://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a>:</p>
<pre><code>>>> import inspect, testpkg
>>> inspect.getmembers(testpkg, inspect.ismodule)
['modulea', 'moduleb']
</code></pre>
| 5
|
2013-04-05T12:18:29Z
|
[
"python",
"module",
"package"
] |
Is there a standard way to list names of Python modules in a package?
| 487,971
|
<p>Is there a straightforward way to list the names of all modules in a package, without using <code>__all__</code>?</p>
<p>For example, given this package:</p>
<pre><code>/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
</code></pre>
<p>I'm wondering if there is a standard or built-in way to do something like this:</p>
<pre><code>>>> package_contents("testpkg")
['modulea', 'moduleb']
</code></pre>
<p>The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?</p>
| 57
|
2009-01-28T15:11:32Z
| 36,764,029
|
<p>Based on cdleary's example, here's a recursive version listing path for all submodules:</p>
<pre><code>import imp, os
def iter_submodules(package):
file, pathname, description = imp.find_module('isc_datasources')
for dirpath, _, filenames in os.walk(pathname):
for filename in filenames:
if os.path.splitext(filename)[1] == ".py":
yield os.path.join(dirpath, filename)
</code></pre>
| 0
|
2016-04-21T08:33:14Z
|
[
"python",
"module",
"package"
] |
Django: ModelMultipleChoiceField doesn't select initial choices
| 488,036
|
<p>ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example:</p>
<p><a href="http://code.djangoproject.com/ticket/5247#comment:6">http://code.djangoproject.com/ticket/5247#comment:6</a></p>
<p>My models and form:</p>
<pre><code>class Company(models.Model):
company_name = models.CharField(max_length=200)
class Contact(models.Model):
company = models.ForeignKey(Company)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Action(models.Model):
company = models.ForeignKey(Company, blank=True, null=True)
from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True)
class Action_Form(ModelForm):
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple())
class Meta:
model = Action
</code></pre>
<p>What I do and the results:</p>
<pre>
>>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable
>>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix
>>> print form['from_company']
<ul>
</ul>
>>> print contacts_from_company
[<Contact: test person>, <Contact: another person>]
>>> form2 = Action_Form(initial={'from_company': contacts_from_company})
>>> print form2['from_company']
<ul>
</ul>
>>> form3 = Action_Form(initial={'from_company': Contact.objects.all()})
>>> print form3['from_company']
<ul>
</ul>
</pre>
<p>The way I was hoping it would work:<br />
1. My view gets "company" from request.GET<br />
2. It then filters all "contacts" for that "company"<br />
3. Finally, it creates a form and passes those "contacts" as "initial={...}" </p>
<p><strong>Two questions:</strong><br />
<strong>1. [not answered yet]</strong> How can I make ModelMultipleChoiceField take those "initial" values?<br />
<strong>2. [answered]</strong> As an alternative, can I pass a variable to Action_Form(ModelForm) so that in my ModelForm I could have:</p>
<pre>
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view
</pre>
| 18
|
2009-01-28T15:30:02Z
| 488,113
|
<p>You will need to add an <code>__init__</code> method to <code>Action_Form</code> to set your initial values, remembering to call <code>__init__</code> on the base <code>ModelForm</code> class via <strong>super</strong>.</p>
<pre><code>class Action_Form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Action_Form, self).__init__(*args, **kwargs)
self.fields['from_company'].queryset = Contact.object.filter(...
</code></pre>
<p>If you plan to pass your filter params as keyword args to <code>Action_Form</code>, you'll need to remove them prior invoking super:</p>
<pre><code>myfilter = kwargs['myfilter']
del kwargs['myfilter']
</code></pre>
<p>or, probably better:</p>
<pre><code>myfilter = kwargs.pop('myfilter')
</code></pre>
<p>For more information, here's another link referring to <a href="http://www.rossp.org/blog/2008/dec/15/modelforms/" rel="nofollow">Dynamic ModelForms in Django</a>.</p>
| 8
|
2009-01-28T15:45:06Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Django: ModelMultipleChoiceField doesn't select initial choices
| 488,036
|
<p>ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example:</p>
<p><a href="http://code.djangoproject.com/ticket/5247#comment:6">http://code.djangoproject.com/ticket/5247#comment:6</a></p>
<p>My models and form:</p>
<pre><code>class Company(models.Model):
company_name = models.CharField(max_length=200)
class Contact(models.Model):
company = models.ForeignKey(Company)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Action(models.Model):
company = models.ForeignKey(Company, blank=True, null=True)
from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True)
class Action_Form(ModelForm):
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple())
class Meta:
model = Action
</code></pre>
<p>What I do and the results:</p>
<pre>
>>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable
>>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix
>>> print form['from_company']
<ul>
</ul>
>>> print contacts_from_company
[<Contact: test person>, <Contact: another person>]
>>> form2 = Action_Form(initial={'from_company': contacts_from_company})
>>> print form2['from_company']
<ul>
</ul>
>>> form3 = Action_Form(initial={'from_company': Contact.objects.all()})
>>> print form3['from_company']
<ul>
</ul>
</pre>
<p>The way I was hoping it would work:<br />
1. My view gets "company" from request.GET<br />
2. It then filters all "contacts" for that "company"<br />
3. Finally, it creates a form and passes those "contacts" as "initial={...}" </p>
<p><strong>Two questions:</strong><br />
<strong>1. [not answered yet]</strong> How can I make ModelMultipleChoiceField take those "initial" values?<br />
<strong>2. [answered]</strong> As an alternative, can I pass a variable to Action_Form(ModelForm) so that in my ModelForm I could have:</p>
<pre>
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view
</pre>
| 18
|
2009-01-28T15:30:02Z
| 1,530,632
|
<p>I'm replying for 1)</p>
<blockquote>1. How can I make ModelMultipleChoiceField take those "initial" values?</blockquote>
<p>This could be done in your <code>Action_Form</code> <code>__init__</code> method using ModelMultipleChoiceField <code>initial</code> attribute.</p>
<p>As it says in the Django source code (<em>db/models/fields/related.py</em>)
in <code>def formfield(self, **kwargs)</code>:</p>
<p><pre><code> # If initial is passed in, it's a list of related objects, but the
# MultipleChoiceField takes a list of IDs.
</pre></code></p>
<p>So you need to give it a list of IDs:</p>
<pre><code>class Action_Form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Action_Form, self).__init__(*args, **kwargs)
self.fields['from_company'].initial = [c.pk for c in Contact.object.filter()]
</code></pre>
| 18
|
2009-10-07T10:01:37Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Django: ModelMultipleChoiceField doesn't select initial choices
| 488,036
|
<p>ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example:</p>
<p><a href="http://code.djangoproject.com/ticket/5247#comment:6">http://code.djangoproject.com/ticket/5247#comment:6</a></p>
<p>My models and form:</p>
<pre><code>class Company(models.Model):
company_name = models.CharField(max_length=200)
class Contact(models.Model):
company = models.ForeignKey(Company)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Action(models.Model):
company = models.ForeignKey(Company, blank=True, null=True)
from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True)
class Action_Form(ModelForm):
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple())
class Meta:
model = Action
</code></pre>
<p>What I do and the results:</p>
<pre>
>>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable
>>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix
>>> print form['from_company']
<ul>
</ul>
>>> print contacts_from_company
[<Contact: test person>, <Contact: another person>]
>>> form2 = Action_Form(initial={'from_company': contacts_from_company})
>>> print form2['from_company']
<ul>
</ul>
>>> form3 = Action_Form(initial={'from_company': Contact.objects.all()})
>>> print form3['from_company']
<ul>
</ul>
</pre>
<p>The way I was hoping it would work:<br />
1. My view gets "company" from request.GET<br />
2. It then filters all "contacts" for that "company"<br />
3. Finally, it creates a form and passes those "contacts" as "initial={...}" </p>
<p><strong>Two questions:</strong><br />
<strong>1. [not answered yet]</strong> How can I make ModelMultipleChoiceField take those "initial" values?<br />
<strong>2. [answered]</strong> As an alternative, can I pass a variable to Action_Form(ModelForm) so that in my ModelForm I could have:</p>
<pre>
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view
</pre>
| 18
|
2009-01-28T15:30:02Z
| 3,915,048
|
<p>If previous answer wasn't straight-forward enough, I try to answer 1) again:</p>
<blockquote>
<ol>
<li>How can I make ModelMultipleChoiceField take those "initial" values?</li>
</ol>
</blockquote>
<p>You can leave <code>Action_Form</code> as it was in the original question, and just use this to render exactly what you want:</p>
<pre><code>>>> form4 = Action_Form(initial={'from_company': Contact.objects.all().values_list('id',flat=True)})
>>> print form4['from_company']
</code></pre>
| 8
|
2010-10-12T13:13:25Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Django: ModelMultipleChoiceField doesn't select initial choices
| 488,036
|
<p>ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example:</p>
<p><a href="http://code.djangoproject.com/ticket/5247#comment:6">http://code.djangoproject.com/ticket/5247#comment:6</a></p>
<p>My models and form:</p>
<pre><code>class Company(models.Model):
company_name = models.CharField(max_length=200)
class Contact(models.Model):
company = models.ForeignKey(Company)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Action(models.Model):
company = models.ForeignKey(Company, blank=True, null=True)
from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True)
class Action_Form(ModelForm):
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple())
class Meta:
model = Action
</code></pre>
<p>What I do and the results:</p>
<pre>
>>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable
>>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix
>>> print form['from_company']
<ul>
</ul>
>>> print contacts_from_company
[<Contact: test person>, <Contact: another person>]
>>> form2 = Action_Form(initial={'from_company': contacts_from_company})
>>> print form2['from_company']
<ul>
</ul>
>>> form3 = Action_Form(initial={'from_company': Contact.objects.all()})
>>> print form3['from_company']
<ul>
</ul>
</pre>
<p>The way I was hoping it would work:<br />
1. My view gets "company" from request.GET<br />
2. It then filters all "contacts" for that "company"<br />
3. Finally, it creates a form and passes those "contacts" as "initial={...}" </p>
<p><strong>Two questions:</strong><br />
<strong>1. [not answered yet]</strong> How can I make ModelMultipleChoiceField take those "initial" values?<br />
<strong>2. [answered]</strong> As an alternative, can I pass a variable to Action_Form(ModelForm) so that in my ModelForm I could have:</p>
<pre>
from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view
</pre>
| 18
|
2009-01-28T15:30:02Z
| 20,661,777
|
<p>Answer to (1) question!</p>
<p>This will not work:</p>
<pre><code>self.fields['from_company'].initial = [c.pk for c in Contact.object.filter()]
</code></pre>
<p>But this will <strong>really work</strong>:</p>
<pre><code>self.initial['from_company'] = [c.pk for c in Contact.object.filter()]
</code></pre>
| 5
|
2013-12-18T15:14:45Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
ZipFile complains, is there a way around using the zipfile module?
| 488,054
|
<p>I am trying to decompress some MMS messages sent to me zipped. The problem is that sometimes it works, and others not. And when it doesnt work, the python zipfile module complains and says that it is a bad zip file. But the zipfile decompresses fine using the unix unzip command.</p>
<p>This is what ive got</p>
<pre><code>zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'w+')
zippedfile.write(string)
z = zipfile.ZipFile(zippedfile)
</code></pre>
<p>I am using 'w+' and writing a string to it, the string contains a base64 decoded string representation of a zip file.</p>
<p>Then I do like this:</p>
<pre><code>filelist = z.infolist()
images = []
for f in filelist:
raw_mimetype = mimetypes.guess_type(f.filename)[0]
if raw_mimetype:
mimetype = raw_mimetype.split('/')[0]
else:
mimetype = 'unknown'
if mimetype == 'image':
images.append(f.filename)
</code></pre>
<p>This way I've got a list of all the images in the zip file. But this doesnt always work, since the zipfile module complains about some of the files.</p>
<p>Is there a way to do this, without using the zipfile module?</p>
<p>Could I somehow use the unix command unzip instead of zipfile and then to the same thing to retrive all the images from the archive?</p>
| 1
|
2009-01-28T15:34:11Z
| 488,074
|
<p>You should very probably open the file in binary mode, when writing zipped data into it. That is, you should use</p>
<pre><code>zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+')
</code></pre>
| 4
|
2009-01-28T15:37:03Z
|
[
"python",
"zip",
"popen",
"zipfile"
] |
ZipFile complains, is there a way around using the zipfile module?
| 488,054
|
<p>I am trying to decompress some MMS messages sent to me zipped. The problem is that sometimes it works, and others not. And when it doesnt work, the python zipfile module complains and says that it is a bad zip file. But the zipfile decompresses fine using the unix unzip command.</p>
<p>This is what ive got</p>
<pre><code>zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'w+')
zippedfile.write(string)
z = zipfile.ZipFile(zippedfile)
</code></pre>
<p>I am using 'w+' and writing a string to it, the string contains a base64 decoded string representation of a zip file.</p>
<p>Then I do like this:</p>
<pre><code>filelist = z.infolist()
images = []
for f in filelist:
raw_mimetype = mimetypes.guess_type(f.filename)[0]
if raw_mimetype:
mimetype = raw_mimetype.split('/')[0]
else:
mimetype = 'unknown'
if mimetype == 'image':
images.append(f.filename)
</code></pre>
<p>This way I've got a list of all the images in the zip file. But this doesnt always work, since the zipfile module complains about some of the files.</p>
<p>Is there a way to do this, without using the zipfile module?</p>
<p>Could I somehow use the unix command unzip instead of zipfile and then to the same thing to retrive all the images from the archive?</p>
| 1
|
2009-01-28T15:34:11Z
| 488,261
|
<p>You might have to close and reopen the file, or maybe seek to the start of the file after writing it.</p>
<pre><code>filename = '%stemp/tempfile.zip' % settings.MEDIA_ROOT
zippedfile = open(filename , 'wb+')
zippedfile.write(string)
zippedfile.close()
z = zipfile.ZipFile(filename,"r")
</code></pre>
<p>You say the string is base64 decoded, but you haven't shown any code that decodes it - are you sure it's not still encoded?</p>
<pre><code>data = string.decode('base64')
</code></pre>
| 0
|
2009-01-28T16:21:03Z
|
[
"python",
"zip",
"popen",
"zipfile"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 488,402
|
<p>According to <a href="http://bytes.com/groups/python/22914-os-environ-os-path-chdir" rel="nofollow">this discussion</a>, you cannot do it. What are you trying to accomplish?</p>
| 3
|
2009-01-28T16:46:09Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 488,407
|
<p>You are forking a new process and cannot change the environment of the parent process as you cannot do if you start a new shell process from the shell</p>
| 2
|
2009-01-28T16:46:48Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 488,419
|
<p>I don't believe you can do this; there are two work-arounds I can think of.</p>
<ol>
<li><p>The <code>os.putenv</code> function sets the environment for processes you start with, i.e. os.system, popen, etc. Depending on what you're trying to do, perhaps you could have one master Python instance that sets the variable, and then spawns new instances.</p></li>
<li><p>You could run a shell script or batch file to set it for you, but that becomes much less portable. See this article:</p></li>
</ol>
<p><a href="http://code.activestate.com/recipes/159462/" rel="nofollow">http://code.activestate.com/recipes/159462/</a></p>
| 4
|
2009-01-28T16:48:48Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 488,475
|
<p>Under Windows it's possible for you to make changes to environment variables persistent via the registry with <a href="http://code.activestate.com/recipes/416087/">this recipe</a>, though it seems like overkill.</p>
<p>To echo Brian's question, what are you trying to accomplish? There is probably an easier way.</p>
| 5
|
2009-01-28T17:09:48Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 488,713
|
<blockquote>
<p>make them stick by committing them to
the system?</p>
</blockquote>
<p>I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates.</p>
<p>If you really do think you need to set environment variables for the system you will need to look at changing them in the location they get initially loaded from like the registry on windows or your shell configuration file on Linux.</p>
| 7
|
2009-01-28T18:16:58Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 488,904
|
<p>You might want to try <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Python Win32 Extensions</a>, developed by Mark Hammond, which is included in the <a href="http://www.activestate.com/activepython/downloads" rel="nofollow">ActivePython</a> (or can be installed separately). You can learn how to perform many Windows related tasks in <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Hammond's and Robinson's book</a>.</p>
<p>Using <em>PyWin32</em> to access windows <em>COM objects</em>, a Python program can use the <a href="http://msdn.microsoft.com/en-us/library/fd7hxfdd.aspx" rel="nofollow">Environment Property</a> (a collection of environment variables) of the <code>WScript.Shell</code> object.</p>
| 2
|
2009-01-28T19:05:00Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 490,350
|
<p>Think about it this way.</p>
<p>You're not setting shell environment variables.</p>
<p>You're spawning a subshell with some given environment variable settings; this subshell runs your application with the modified environment.</p>
| 2
|
2009-01-29T02:57:14Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 490,404
|
<p>From within Python? No, it can't be done!</p>
<p>If you are not bound to Python, you should consider using shell scripts (sh, bash, etc). The "source" command allows you to run a script that modifies the environment and will "stick" like you want to the shell you "sourced" the script in. What's going on here is that the shell executes the script directly rather creating a sub-process to execute the script.</p>
<p>This will be quite portable - you can use cygwin on windows to do this.</p>
| 1
|
2009-01-29T03:38:25Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 18,283,127
|
<p>You can using SETX at the command-line.</p>
<p>By default these actions go on the USER env vars.
To set and modify SYSTEM vars use the /M flag</p>
<pre><code>import os
env_var = "BUILD_NUMBER"
env_val = "3.1.3.3.7"
os.system("SETX {0} {1} /M".format(env_var,env_val))
</code></pre>
| 1
|
2013-08-16T22:35:26Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 36,040,437
|
<p>Seems like there is simplier solution for Windows</p>
<pre><code>import subprocess
subprocess.call(['setx', 'Hello', 'World!'], shell=True)
</code></pre>
| 0
|
2016-03-16T15:41:30Z
|
[
"python",
"environment-variables"
] |
How do I make environment variable changes stick in Python?
| 488,366
|
<p>From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?</p>
<p>The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.</p>
<p>My test code is</p>
<pre><code>import os
os.environ['FAKE'] = 'C:\\'
</code></pre>
<p>Opening another instance of Python and requesting <code>os.environ['FAKE']</code> yields a <code>KeyError</code>.</p>
<p><strong>NOTE:</strong> Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.</p>
<p>That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.</p>
| 10
|
2009-01-28T16:36:47Z
| 38,419,436
|
<p>In case someone might need this info. I realize this was asked 7 yrs ago, but even I forget how sometimes. .</p>
<p>Yes there is a way to make them "stick" in windows. Simply go control panel, system, advanced system settings,when the system properties window opens you should see an option (button) for Environment Variables. .The process for getting to this is a little different depending on what OS you're using (google it).</p>
<p>Choose that (click button), then the Environment Variables window will open. It has 2 split windows, the top one should be your "User Variables For yourusername". . .choose "new", then simply set the variable. For instance one of mine is "Database_Password = mypassword".</p>
<p>Then in your app you can access them like this: import os, os.environ.get('Database_Password'). You can do something like <code>pass = os.environ.get('Database_Password')</code>.</p>
| 0
|
2016-07-17T08:45:49Z
|
[
"python",
"environment-variables"
] |
Can a python script persistently change a Windows environment variable? (elegantly)
| 488,449
|
<p>Following on from my <a href="http://stackoverflow.com/questions/488294/how-can-i-make-a-windows-batch-file-which-changes-an-environment-variable">previous question</a>, is it possible to make a Python script which persistently changes a Windows environment variable? </p>
<p>Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like:</p>
<pre><code>set foo=`myscript.py`
</code></pre>
<p>But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this:</p>
<pre><code>for /f "tokens=1* delims=" %%a in ('python ..\myscript.py') do set path=%path%;%%a
</code></pre>
<p>Surely the minds at Microsoft have a better solution than this!</p>
<p><strong>Note</strong>: exact duplicate of <a href="http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python">this question</a>.</p>
| 6
|
2009-01-28T17:00:53Z
| 488,535
|
<p>Your long-winded solution is probably the best idea; I don't believe this is possible from Python directly. This article suggests another way, using a temporary batch file:</p>
<p><a href="http://code.activestate.com/recipes/159462/" rel="nofollow">http://code.activestate.com/recipes/159462/</a></p>
| 1
|
2009-01-28T17:24:23Z
|
[
"python",
"windows",
"scripting",
"batch-file"
] |
Can a python script persistently change a Windows environment variable? (elegantly)
| 488,449
|
<p>Following on from my <a href="http://stackoverflow.com/questions/488294/how-can-i-make-a-windows-batch-file-which-changes-an-environment-variable">previous question</a>, is it possible to make a Python script which persistently changes a Windows environment variable? </p>
<p>Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like:</p>
<pre><code>set foo=`myscript.py`
</code></pre>
<p>But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this:</p>
<pre><code>for /f "tokens=1* delims=" %%a in ('python ..\myscript.py') do set path=%path%;%%a
</code></pre>
<p>Surely the minds at Microsoft have a better solution than this!</p>
<p><strong>Note</strong>: exact duplicate of <a href="http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python">this question</a>.</p>
| 6
|
2009-01-28T17:00:53Z
| 488,696
|
<p>You might want to try <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Python Win32 Extensions</a>, developed by Mark Hammond, which is included in the <a href="http://www.activestate.com/activepython/downloads" rel="nofollow">ActivePython</a> (or can be installed separately). You can learn how to perform many Windows related tasks in <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Hammond's and Robinson's book</a>.</p>
<p>Using <em>PyWin32</em> to access windows <em>COM objects</em>, a Python program can use the <a href="http://msdn.microsoft.com/en-us/library/fd7hxfdd.aspx" rel="nofollow">Environment Property</a> of the <code>WScript.Shell</code> object - a collection of environment variables.</p>
| 5
|
2009-01-28T18:10:53Z
|
[
"python",
"windows",
"scripting",
"batch-file"
] |
Can a python script persistently change a Windows environment variable? (elegantly)
| 488,449
|
<p>Following on from my <a href="http://stackoverflow.com/questions/488294/how-can-i-make-a-windows-batch-file-which-changes-an-environment-variable">previous question</a>, is it possible to make a Python script which persistently changes a Windows environment variable? </p>
<p>Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like:</p>
<pre><code>set foo=`myscript.py`
</code></pre>
<p>But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this:</p>
<pre><code>for /f "tokens=1* delims=" %%a in ('python ..\myscript.py') do set path=%path%;%%a
</code></pre>
<p>Surely the minds at Microsoft have a better solution than this!</p>
<p><strong>Note</strong>: exact duplicate of <a href="http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python">this question</a>.</p>
| 6
|
2009-01-28T17:00:53Z
| 488,737
|
<p>Windows sets Environment variables from values stored in the Registry for each process independently.</p>
<p>However, there is a tool in the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=49AE8576-9BB9-4126-9761-BA8011FABF38&displaylang=en" rel="nofollow">Windows XP Service Pack 2 Support Tools</a> named setx.exe that allows you to change global Environment variables from the command line.</p>
| 3
|
2009-01-28T18:25:05Z
|
[
"python",
"windows",
"scripting",
"batch-file"
] |
Can a python script persistently change a Windows environment variable? (elegantly)
| 488,449
|
<p>Following on from my <a href="http://stackoverflow.com/questions/488294/how-can-i-make-a-windows-batch-file-which-changes-an-environment-variable">previous question</a>, is it possible to make a Python script which persistently changes a Windows environment variable? </p>
<p>Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like:</p>
<pre><code>set foo=`myscript.py`
</code></pre>
<p>But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this:</p>
<pre><code>for /f "tokens=1* delims=" %%a in ('python ..\myscript.py') do set path=%path%;%%a
</code></pre>
<p>Surely the minds at Microsoft have a better solution than this!</p>
<p><strong>Note</strong>: exact duplicate of <a href="http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python">this question</a>.</p>
| 6
|
2009-01-28T17:00:53Z
| 594,917
|
<p>My solution using win32api:</p>
<pre><code>import os, sys, win32api, win32con
'''Usage: appendenv.py envvar data_to_append'''
def getenv_system(varname, default=None):
'''
Author: Denis Barmenkov <barmenkov at bpc.ru>
Copyright: this code is free, but if you want to use it,
please keep this multiline comment along with function source.
Thank you.
2006-01-28 15:30
'''
v = default
try:
rkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
try:
v = str(win32api.RegQueryValueEx(rkey, varname)[0])
v = win32api.ExpandEnvironmentStrings(v)
except:
pass
finally:
win32api.RegCloseKey(rkey)
return v
#My set function
def setenv_system(varname, value):
try:
rkey = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment',0 ,win32con.KEY_WRITE)
try:
win32api.RegSetValueEx(rkey, varname, 0, win32con.REG_SZ, value)
return True
except Exception, (error):
pass
finally:
win32api.RegCloseKey(rkey)
return False
if len(sys.argv) == 3:
value = getenv_system(sys.argv[1])
if value:
setenv_system(sys.argv[1],value + ";" + sys.argv[2])
print "OK! %s = %s" % (sys.argv[1], getenv_system(sys.argv[1]))
else:
print "ERROR: No such environment variable. (%s)" % sys.argv[1]
else:
print "Usage: appendenv.py envvar data_to_append"
</code></pre>
| 3
|
2009-02-27T14:16:08Z
|
[
"python",
"windows",
"scripting",
"batch-file"
] |
Can a python script persistently change a Windows environment variable? (elegantly)
| 488,449
|
<p>Following on from my <a href="http://stackoverflow.com/questions/488294/how-can-i-make-a-windows-batch-file-which-changes-an-environment-variable">previous question</a>, is it possible to make a Python script which persistently changes a Windows environment variable? </p>
<p>Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like:</p>
<pre><code>set foo=`myscript.py`
</code></pre>
<p>But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this:</p>
<pre><code>for /f "tokens=1* delims=" %%a in ('python ..\myscript.py') do set path=%path%;%%a
</code></pre>
<p>Surely the minds at Microsoft have a better solution than this!</p>
<p><strong>Note</strong>: exact duplicate of <a href="http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python">this question</a>.</p>
| 6
|
2009-01-28T17:00:53Z
| 19,640,752
|
<p>This <a href="http://code.activestate.com/recipes/577621/" rel="nofollow">link</a> provides a solution that uses the built-in <code>winreg</code> library.</p>
<p>(copypasta)</p>
<pre><code>import sys
from subprocess import check_call
if sys.hexversion > 0x03000000:
import winreg
else:
import _winreg as winreg
class Win32Environment:
"""Utility class to get/set windows environment variable"""
def __init__(self, scope):
assert scope in ('user', 'system')
self.scope = scope
if scope == 'user':
self.root = winreg.HKEY_CURRENT_USER
self.subkey = 'Environment'
else:
self.root = winreg.HKEY_LOCAL_MACHINE
self.subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
def getenv(self, name):
key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ)
try:
value, _ = winreg.QueryValueEx(key, name)
except WindowsError:
value = ''
return value
def setenv(self, name, value):
# Note: for 'system' scope, you must run this as Administrator
key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
winreg.CloseKey(key)
# For some strange reason, calling SendMessage from the current process
# doesn't propagate environment changes at all.
# TODO: handle CalledProcessError (for assert)
check_call('''\
"%s" -c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')"''' % sys.executable)
</code></pre>
| 1
|
2013-10-28T17:00:31Z
|
[
"python",
"windows",
"scripting",
"batch-file"
] |
about one to many relationship in datastore and dereferncing in google app engine?
| 488,498
|
<p>i have a one to many relationship between two entities the first one is a satellite and the second one is channel and the satellite form returns a satellite name which i want to appear in another html page with the channel data where you can say that this channel is related to that satellite
how to make this</p>
| 4
|
2009-01-28T17:17:57Z
| 492,750
|
<p>This sounds like a good case for using the ReferenceProperty that is part of the Datastore API of App Engine. Here's an idea to get you started:</p>
<pre><code>class Satellite(db.Model):
name = db.StringProperty()
class Channel(db.Model):
satellite = db.ReferenceProperty(Satellite, collection_name='channels')
freq = db.StringProperty()
</code></pre>
<p>With this you can assign channels like so:</p>
<pre><code>my_sat = Satellite(name='SatCOM1')
my_sat.put()
Channel(satellite=my_sat,freq='28.1200Hz').put()
... #Add other channels ...
</code></pre>
<p>Then loop through channels for a given Satellite object:</p>
<pre><code>for chan in my_sat.channels:
print 'Channel frequency: %s' % (chan.freq)
</code></pre>
<p>Anyway, this pretty much follows <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">this article</a> that describes how to model entity relationships in App Engine. Hope this helps.</p>
| 6
|
2009-01-29T18:13:02Z
|
[
"python",
"google-app-engine"
] |
MS Outlook CDO/MAPI Blocking Python File Output?
| 488,504
|
<p>Here is an example of the problem I am running into. I am using the Python Win32 extensions to access an Outlook mailbox and retrieve messages.</p>
<p>Below is a script that should write "hello world" to a text file. I need to grab some messages from an Outlook mailbox and I noticed something weird. After I attach to the mailbox once, I can no longer print anything to a file. Here is a trimmed down version showing the problem:</p>
<pre><code>#!/usr/bin/env python
from win32com.client import Dispatch
fh = open('foo.txt', 'w')
fh.write('hello ')
fh.close()
session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nprodreport');
session.Logoff()
fh = open('foo.txt', 'a')
fh.write('world')
fh.close()
</code></pre>
<p>If I don't attach to the mailbox and comment out the following lines, it obviously works fine:</p>
<pre><code>session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\ncorey');
session.Logoff()
</code></pre>
<p>Why is opening a session to a mailbox in the middle of my script blocking further file output? any ideas? (other operations are not blocked, just this file i/o asfaik)</p>
| 1
|
2009-01-28T17:19:56Z
| 489,403
|
<p>answering my own question. it looks like your working directory gets changed when you read the email. If you set it back, your file i/o works fine.</p>
<p>the correct script would look like this:</p>
<pre><code>#!/usr/bin/env python
import os
from win32com.client import Dispatch
fh = open('foo.txt', 'w')
fh.write('hello ')
fh.close()
cwd = os.getcwd()
session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\ncorey');
session.Logoff()
os.chdir(cwd)
fh = open('foo.txt', 'a')
fh.write('world')
fh.close()
</code></pre>
| 1
|
2009-01-28T21:12:38Z
|
[
"python",
"winapi",
"outlook",
"mapi",
"cdo"
] |
MS Outlook CDO/MAPI Blocking Python File Output?
| 488,504
|
<p>Here is an example of the problem I am running into. I am using the Python Win32 extensions to access an Outlook mailbox and retrieve messages.</p>
<p>Below is a script that should write "hello world" to a text file. I need to grab some messages from an Outlook mailbox and I noticed something weird. After I attach to the mailbox once, I can no longer print anything to a file. Here is a trimmed down version showing the problem:</p>
<pre><code>#!/usr/bin/env python
from win32com.client import Dispatch
fh = open('foo.txt', 'w')
fh.write('hello ')
fh.close()
session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nprodreport');
session.Logoff()
fh = open('foo.txt', 'a')
fh.write('world')
fh.close()
</code></pre>
<p>If I don't attach to the mailbox and comment out the following lines, it obviously works fine:</p>
<pre><code>session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\ncorey');
session.Logoff()
</code></pre>
<p>Why is opening a session to a mailbox in the middle of my script blocking further file output? any ideas? (other operations are not blocked, just this file i/o asfaik)</p>
| 1
|
2009-01-28T17:19:56Z
| 491,245
|
<p>Yes, the directory change is a known gotcha when using CDO/MAPI. It is "documented" somewhere in MSDN (eg <a href="http://support.microsoft.com/kb/269170" rel="nofollow">http://support.microsoft.com/kb/269170</a>). You can reproduce it easily in Python like this:</p>
<pre>
<code>
import os
import win32com.client
print os.getcwd ()
win32com.client.Dispatch ("MAPI.Session")
print os.getcwd ()
</code>
</pre>
| 1
|
2009-01-29T11:15:22Z
|
[
"python",
"winapi",
"outlook",
"mapi",
"cdo"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 488,695
|
<p>I don't know Python, but for the averaging part, do you mean an exponentially decaying low-pass filter of the form</p>
<pre><code>y_new = y_old + (input - y_old)*alpha
</code></pre>
<p>where alpha = dt/tau, dt = the timestep of the filter, tau = the time constant of the filter? (the variable-timestep form of this is as follows, just clip dt/tau to not be more than 1.0)</p>
<pre><code>y_new = y_old + (input - y_old)*dt/tau
</code></pre>
<p>If you want to filter something like a date, make sure you convert to a floating-point quantity like # of seconds since Jan 1 1970.</p>
| 4
|
2009-01-28T18:10:09Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 488,700
|
<p>I did a bit of googling and I found the following sample code (http://osdir.com/ml/python.matplotlib.general/2005-04/msg00044.html):</p>
<pre><code>def ema(s, n):
"""
returns an n period exponential moving average for
the time series s
s is a list ordered from oldest (index 0) to most
recent (index -1)
n is an integer
returns a numeric array of the exponential
moving average
"""
s = array(s)
ema = []
j = 1
#get n sma first and calculate the next n period ema
sma = sum(s[:n]) / n
multiplier = 2 / float(1 + n)
ema.append(sma)
#EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
ema.append(( (s[n] - sma) * multiplier) + sma)
#now calculate the rest of the values
for i in s[n+1:]:
tmp = ( (i - ema[j]) * multiplier) + ema[j]
j = j + 1
ema.append(tmp)
return ema
</code></pre>
| 8
|
2009-01-28T18:12:07Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 488,825
|
<p>My python is a little bit rusty (anyone can feel free to edit this code to make corrections, if I've messed up the syntax somehow), but here goes....</p>
<pre><code>def movingAverageExponential(values, alpha, epsilon = 0):
if not 0 < alpha < 1:
raise ValueError("out of range, alpha='%s'" % alpha)
if not 0 <= epsilon < alpha:
raise ValueError("out of range, epsilon='%s'" % epsilon)
result = [None] * len(values)
for i in range(len(result)):
currentWeight = 1.0
numerator = 0
denominator = 0
for value in values[i::-1]:
numerator += value * currentWeight
denominator += currentWeight
currentWeight *= alpha
if currentWeight < epsilon:
break
result[i] = numerator / denominator
return result
</code></pre>
<p>This function moves backward, from the end of the list to the beginning, calculating the exponential moving average for each value by working backward until the weight coefficient for an element is less than the given epsilon.</p>
<p>At the end of the function, it reverses the values before returning the list (so that they're in the correct order for the caller).</p>
<p>(SIDE NOTE: if I was using a language other than python, I'd create a full-size empty array first and then fill it backwards-order, so that I wouldn't have to reverse it at the end. But I don't think you can declare a big empty array in python. And in python lists, appending is much less expensive than prepending, which is why I built the list in reverse order. Please correct me if I'm wrong.)</p>
<p>The 'alpha' argument is the decay factor on each iteration. For example, if you used an alpha of 0.5, then today's moving average value would be composed of the following weighted values:</p>
<pre><code>today: 1.0
yesterday: 0.5
2 days ago: 0.25
3 days ago: 0.125
...etc...
</code></pre>
<p>Of course, if you've got a huge array of values, the values from ten or fifteen days ago won't contribute very much to today's weighted average. The 'epsilon' argument lets you set a cutoff point, below which you will cease to care about old values (since their contribution to today's value will be insignificant).</p>
<p>You'd invoke the function something like this:</p>
<pre><code>result = movingAverageExponential(values, 0.75, 0.0001)
</code></pre>
| 5
|
2009-01-28T18:46:59Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 488,941
|
<p>EDIT:
It seems that <a href="http://www.scipy.org/scipy/scikits/browser/trunk/timeseries/scikits/timeseries/lib/moving_funcs.py"><code>mov_average_expw()</code></a> function from <a href="http://pytseries.sourceforge.net/lib/moving_funcs.html">scikits.timeseries.lib.moving_funcs</a> submodule from <a href="http://scikits.appspot.com/">SciKits</a> (add-on toolkits that complement <a href="http://scipy.org/">SciPy</a>) better suits the wording of your question. </p>
<p><hr /></p>
<p>To calculate an <a href="http://en.wikipedia.org/wiki/Exponential_smoothing">exponential smoothing</a> of your data with a smoothing factor <code>alpha</code> (it is <code>(1 - alpha)</code> in Wikipedia's terms):</p>
<pre><code>>>> alpha = 0.5
>>> assert 0 < alpha <= 1.0
>>> av = sum(alpha**n.days * iq
... for n, iq in map(lambda (day, iq), today=max(days): (today-day, iq),
... sorted(zip(days, IQ), key=lambda p: p[0], reverse=True)))
95.0
</code></pre>
<p>The above is not pretty, so let's refactor it a bit:</p>
<pre><code>from collections import namedtuple
from operator import itemgetter
def smooth(iq_data, alpha=1, today=None):
"""Perform exponential smoothing with factor `alpha`.
Time period is a day.
Each time period the value of `iq` drops `alpha` times.
The most recent data is the most valuable one.
"""
assert 0 < alpha <= 1
if alpha == 1: # no smoothing
return sum(map(itemgetter(1), iq_data))
if today is None:
today = max(map(itemgetter(0), iq_data))
return sum(alpha**((today - date).days) * iq for date, iq in iq_data)
IQData = namedtuple("IQData", "date iq")
if __name__ == "__main__":
from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
iqdata = list(map(IQData, days, IQ))
print("\n".join(map(str, iqdata)))
print(smooth(iqdata, alpha=0.5))
</code></pre>
<p>Example:</p>
<pre><code>$ python26 smooth.py
IQData(date=datetime.date(2008, 1, 1), iq=110)
IQData(date=datetime.date(2008, 1, 2), iq=105)
IQData(date=datetime.date(2008, 1, 7), iq=90)
95.0
</code></pre>
| 15
|
2009-01-28T19:15:34Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 21,739,006
|
<p>I found the above code snippet by @earino pretty useful - but I needed something that could continuously smooth a stream of values - so I refactored it to this:</p>
<pre class="lang-py prettyprint-override"><code>def exponential_moving_average(period=1000):
""" Exponential moving average. Smooths the values in v over ther period. Send in values - at first it'll return a simple average, but as soon as it's gahtered 'period' values, it'll start to use the Exponential Moving Averge to smooth the values.
period: int - how many values to smooth over (default=100). """
multiplier = 2 / float(1 + period)
cum_temp = yield None # We are being primed
# Start by just returning the simple average until we have enough data.
for i in xrange(1, period + 1):
cum_temp += yield cum_temp / float(i)
# Grab the timple avergae
ema = cum_temp / period
# and start calculating the exponentially smoothed average
while True:
ema = (((yield ema) - ema) * multiplier) + ema
</code></pre>
<p>and I use it like this:</p>
<pre class="lang-py prettyprint-override"><code>def temp_monitor(pin):
""" Read from the temperature monitor - and smooth the value out. The sensor is noisy, so we use exponential smoothing. """
ema = exponential_moving_average()
next(ema) # Prime the generator
while True:
yield ema.send(val_to_temp(pin.read()))
</code></pre>
<p>(where pin.read() produces the next value I'd like to consume). </p>
| 2
|
2014-02-12T20:35:05Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 24,398,487
|
<p>In matplotlib.org examples (<a href="http://matplotlib.org/examples/pylab_examples/finance_work2.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/finance_work2.html</a>) is provided one good example of Exponential Moving Average (EMA) function using numpy:</p>
<pre><code>def moving_average(x, n, type):
x = np.asarray(x)
if type=='simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
a = np.convolve(x, weights, mode='full')[:len(x)]
a[:n] = a[n]
return a
</code></pre>
| 4
|
2014-06-25T00:38:56Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 31,955,317
|
<p>Here is a simple sample I worked up based on <a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages" rel="nofollow">http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages</a></p>
<p>Note that unlike in their spreadsheet, I don't calculate the SMA, and I don't wait to generate the EMA after 10 samples. This means my values differ slightly, but if you chart it, it follows exactly after 10 samples. During the first 10 samples, the EMA I calculate is appropriately smoothed. </p>
<pre><code>def emaWeight(numSamples):
return 2 / float(numSamples + 1)
def ema(close, prevEma, numSamples):
return ((close-prevEma) * emaWeight(numSamples) ) + prevEma
samples = [
22.27, 22.19, 22.08, 22.17, 22.18, 22.13, 22.23, 22.43, 22.24, 22.29,
22.15, 22.39, 22.38, 22.61, 23.36, 24.05, 23.75, 23.83, 23.95, 23.63,
23.82, 23.87, 23.65, 23.19, 23.10, 23.33, 22.68, 23.10, 22.40, 22.17,
]
emaCap = 10
e=samples[0]
for s in range(len(samples)):
numSamples = emaCap if s > emaCap else s
e = ema(samples[s], e, numSamples)
print e
</code></pre>
| 0
|
2015-08-12T03:00:42Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
calculate exponential moving average in python
| 488,670
|
<p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| 14
|
2009-01-28T18:01:44Z
| 32,933,590
|
<p>I'm always calculating EMAs with Pandas:</p>
<p>Here is an example how to do it:</p>
<pre><code>import pandas as pd
import numpy as np
def ema(values, period):
values = np.array(values)
return pd.ewma(values, span=period)[-1]
values = [9, 5, 10, 16, 5]
period = 5
print ema(values, period)
</code></pre>
<p>More infos about Pandas EWMA:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ewma.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ewma.html</a></p>
| 2
|
2015-10-04T12:42:55Z
|
[
"python",
"signal-processing",
"average",
"digital-filter"
] |
Validating Python Arguments in Subclasses
| 488,772
|
<p>I'm trying to validate a few python arguments. Until we get the new static typing in Python 3.0, what is the best way of going about this.</p>
<p>Here is an example of what I am attempting:</p>
<pre><code>class A(object):
@accepts(int, int, int)
def __init__(a, b, c):
pass
class B(A):
@accepts(int, int, int, int)
def __init__(a, b, c, d):
A.__init__(a, b, c)
</code></pre>
<p>As you can see the decorator is nicely performing type checking of the inputs to my class, but I have to define all the arguments to the second class, which gets very nasty when I have multiple levels of inheritance. I can use kwargs with some success, but it's not quite as nice as the above approach for type checking.</p>
<p>Essentially I want to pop one argument off the kwargs list and check it's type, then pass the remainder to it's parent, but do this in a very flexible and clean way as this scales.</p>
<p>Any suggestions?</p>
| 0
|
2009-01-28T18:31:42Z
| 488,946
|
<p>You might want to play around with the <code>inspect</code> module. It will let you enumerate superclasses, argument lists, and other fun stuff. It seems that you might want to inspect the argument list of the superclass <code>__init__</code> method and compare it against what you have in the subclass. I'm not sure if this is going to work for you or not.</p>
<p>I would be careful about what assumptions you make though. It might not be safe to assume that just because class A has <em>N</em> arguments to <code>__init__</code>, subclasses will contain at least <em>N</em> arguments and pass the first <em>N</em> through to the super class. If the subclass is more specific, then it might fill in all by 2 of the arguments to its superclasses <code>__init__</code> method.</p>
| 0
|
2009-01-28T19:17:18Z
|
[
"python",
"inheritance",
"decorator",
"static-typing"
] |
Validating Python Arguments in Subclasses
| 488,772
|
<p>I'm trying to validate a few python arguments. Until we get the new static typing in Python 3.0, what is the best way of going about this.</p>
<p>Here is an example of what I am attempting:</p>
<pre><code>class A(object):
@accepts(int, int, int)
def __init__(a, b, c):
pass
class B(A):
@accepts(int, int, int, int)
def __init__(a, b, c, d):
A.__init__(a, b, c)
</code></pre>
<p>As you can see the decorator is nicely performing type checking of the inputs to my class, but I have to define all the arguments to the second class, which gets very nasty when I have multiple levels of inheritance. I can use kwargs with some success, but it's not quite as nice as the above approach for type checking.</p>
<p>Essentially I want to pop one argument off the kwargs list and check it's type, then pass the remainder to it's parent, but do this in a very flexible and clean way as this scales.</p>
<p>Any suggestions?</p>
| 0
|
2009-01-28T18:31:42Z
| 488,996
|
<p>Why not just define an <code>any</code> value, and decorate the subclass constructor with <code>@accepts(any, any, any, int)</code>? Your decorator won't check parameters marked with <code>any</code>, and the <code>@accepts</code> on the superclass constructor will check all the arguments passed up to it by subclasses.</p>
| 1
|
2009-01-28T19:32:30Z
|
[
"python",
"inheritance",
"decorator",
"static-typing"
] |
Given an rpm package name, query the yum database for updates
| 489,113
|
<p>I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible?</p>
<p>Is writing a wrapper for 'yum list package-name' the only way to do this?</p>
| 5
|
2009-01-28T20:12:07Z
| 490,314
|
<p><a href="http://fpaste.org/paste/2453">http://fpaste.org/paste/2453</a></p>
<p>and there are many examples of the yum api and some guides to getting started with it here:</p>
<p><a href="http://yum.baseurl.org/#DeveloperDocumentationExamples">http://yum.baseurl.org/#DeveloperDocumentationExamples</a></p>
| 7
|
2009-01-29T02:36:40Z
|
[
"python",
"rpm",
"yum"
] |
Given an rpm package name, query the yum database for updates
| 489,113
|
<p>I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible?</p>
<p>Is writing a wrapper for 'yum list package-name' the only way to do this?</p>
| 5
|
2009-01-28T20:12:07Z
| 490,410
|
<p>As Seth points out, you can use the updates APIs to ask if something is available as an update. For something that's close to what the "yum list" does you probably want to use the doPackageLists(). Eg.</p>
<pre><code>import os, sys
import yum
yb = yum.YumBase()
yb.conf.cache = os.geteuid() != 1
pl = yb.doPackageLists(patterns=sys.argv[1:])
if pl.installed:
print "Installed Packages"
for pkg in sorted(pl.installed):
print pkg
if pl.available:
print "Available Packages"
for pkg in sorted(pl.available):
print pkg, pkg.repo
if pl.reinstall_available:
print "Re-install Available Packages"
for pkg in sorted(pl.reinstall_available):
print pkg, pkg.repo
</code></pre>
| 5
|
2009-01-29T03:41:55Z
|
[
"python",
"rpm",
"yum"
] |
Python super() raises TypeError
| 489,269
|
<p>In Python 2.5.2, the following code raises a TypeError:</p>
<pre><code>>>> class X:
... def a(self):
... print "a"
...
>>> class Y(X):
... def a(self):
... super(Y,self).a()
... print "b"
...
>>> c = Y()
>>> c.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I replace the <code>class X</code> with <code>class X(object)</code>, it will work. What's the explanation for this?</p>
| 98
|
2009-01-28T20:47:10Z
| 489,278
|
<p>The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.</p>
| 121
|
2009-01-28T20:48:26Z
|
[
"python",
"super"
] |
Python super() raises TypeError
| 489,269
|
<p>In Python 2.5.2, the following code raises a TypeError:</p>
<pre><code>>>> class X:
... def a(self):
... print "a"
...
>>> class Y(X):
... def a(self):
... super(Y,self).a()
... print "b"
...
>>> c = Y()
>>> c.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I replace the <code>class X</code> with <code>class X(object)</code>, it will work. What's the explanation for this?</p>
| 98
|
2009-01-28T20:47:10Z
| 500,110
|
<p>In addition, don't use super() unless you have to. It's not the general-purpose "right thing" to do with new-style classes that you might suspect.</p>
<p>There are times when you're expecting multiple inheritance and you might possibly want it, but until you know the hairy details of the MRO, best leave it alone and stick to:</p>
<pre><code> X.a(self)
</code></pre>
| 13
|
2009-02-01T03:23:05Z
|
[
"python",
"super"
] |
Python super() raises TypeError
| 489,269
|
<p>In Python 2.5.2, the following code raises a TypeError:</p>
<pre><code>>>> class X:
... def a(self):
... print "a"
...
>>> class Y(X):
... def a(self):
... super(Y,self).a()
... print "b"
...
>>> c = Y()
>>> c.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I replace the <code>class X</code> with <code>class X(object)</code>, it will work. What's the explanation for this?</p>
| 98
|
2009-01-28T20:47:10Z
| 9,974,607
|
<p>I tried the various X.a() methods; however, they seem to require an instance of X in order to perform a(), so I did X().a(self), which seems more complete than the previous answers, at least for the applications I've encountered. It doesn't seem to be a good way of handling the problem as there is unnecessary construction and destruction, but it works fine.</p>
<p>My specific application was Python's cmd.Cmd module, which is evidently not a NewStyle object for some reason.</p>
<p>Final Result:</p>
<pre><code>X().a(self)
</code></pre>
| 1
|
2012-04-02T10:18:40Z
|
[
"python",
"super"
] |
Why am I getting the following error in Python "ImportError: No module named py"?
| 489,497
|
<p>I'm a Python newbie, so bear with me :)</p>
<p>I created a file called test.py with the contents as follows:</p>
<pre><code>test.py
import sys
print sys.platform
print 2 ** 100
</code></pre>
<p>I then ran <code>import test.py</code> file in the interpreter to follow an example in my book.
When I do this, I get the output with the import error on the end.</p>
<pre><code>win32
1267650600228229401496703205376
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named py
</code></pre>
<p>Why do I get this error and how do I fix it? Thanks!</p>
| 11
|
2009-01-28T21:37:27Z
| 489,501
|
<p>You don't specify the extension when importing. Just do:</p>
<pre><code>import test
</code></pre>
| 5
|
2009-01-28T21:39:12Z
|
[
"python"
] |
Why am I getting the following error in Python "ImportError: No module named py"?
| 489,497
|
<p>I'm a Python newbie, so bear with me :)</p>
<p>I created a file called test.py with the contents as follows:</p>
<pre><code>test.py
import sys
print sys.platform
print 2 ** 100
</code></pre>
<p>I then ran <code>import test.py</code> file in the interpreter to follow an example in my book.
When I do this, I get the output with the import error on the end.</p>
<pre><code>win32
1267650600228229401496703205376
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named py
</code></pre>
<p>Why do I get this error and how do I fix it? Thanks!</p>
| 11
|
2009-01-28T21:37:27Z
| 489,503
|
<p>Instead of:</p>
<pre><code>import test.py
</code></pre>
<p>simply write:</p>
<pre><code>import test
</code></pre>
<p>This assumes test.py is in the same directory as the file that imports it.</p>
| 26
|
2009-01-28T21:39:36Z
|
[
"python"
] |
Why am I getting the following error in Python "ImportError: No module named py"?
| 489,497
|
<p>I'm a Python newbie, so bear with me :)</p>
<p>I created a file called test.py with the contents as follows:</p>
<pre><code>test.py
import sys
print sys.platform
print 2 ** 100
</code></pre>
<p>I then ran <code>import test.py</code> file in the interpreter to follow an example in my book.
When I do this, I get the output with the import error on the end.</p>
<pre><code>win32
1267650600228229401496703205376
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named py
</code></pre>
<p>Why do I get this error and how do I fix it? Thanks!</p>
| 11
|
2009-01-28T21:37:27Z
| 489,540
|
<p>As others have mentioned, you don't need to put the file extension in your import statement. Recommended reading is the <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">Modules section of the Python Tutorial</a>.</p>
<p>For a little more background into the error, the interpreter thinks you're trying to import a module named <code>py</code> from inside the <code>test</code> package, since the dot indicates encapsulation. Because no such module exists (and <a href="http://docs.python.org/tutorial/modules.html#packages" rel="nofollow">test isn't even a package</a>!), it raises that error.</p>
<p>As indicated in the <a href="http://docs.python.org/reference/simple_stmts.html#the-import-statement" rel="nofollow">more in-depth documentation on the import statement</a> it still executes all the statements in the <code>test</code> module before attempting to import the <code>py</code> module, which is why you get the values printed out.</p>
| 2
|
2009-01-28T21:47:51Z
|
[
"python"
] |
Why am I getting the following error in Python "ImportError: No module named py"?
| 489,497
|
<p>I'm a Python newbie, so bear with me :)</p>
<p>I created a file called test.py with the contents as follows:</p>
<pre><code>test.py
import sys
print sys.platform
print 2 ** 100
</code></pre>
<p>I then ran <code>import test.py</code> file in the interpreter to follow an example in my book.
When I do this, I get the output with the import error on the end.</p>
<pre><code>win32
1267650600228229401496703205376
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named py
</code></pre>
<p>Why do I get this error and how do I fix it? Thanks!</p>
| 11
|
2009-01-28T21:37:27Z
| 489,547
|
<p>This strange-looking error is a result of how Python imports modules. </p>
<p><strong>Python sees</strong>: </p>
<pre><code>import test.py
</code></pre>
<p><strong>Python thinks</strong> (simplified a bit):</p>
<blockquote>
<p>import module test.</p>
<ul>
<li>search for a test.py in the module search paths</li>
<li>execute test.py (where you get your output)</li>
<li>import 'test' as name into current namespace</li>
</ul>
<p>import test.py</p>
<ul>
<li>search for file test/py.py</li>
<li>throw ImportError (no module named 'py') found.</li>
</ul>
</blockquote>
<p>Because python allows dotted module names, it just thinks you have a submodule named <code>py</code> within the <code>test</code> module, and tried to find that. It has no idea you're attempting to import a file.</p>
| 5
|
2009-01-28T21:48:36Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 489,529
|
<p>No, it is not possible.</p>
<p>As you can see from the <a href="http://docs.python.org/3.0/reference/simple_stmts.html#simple-statements" rel="nofollow">Language Reference</a>, there is no room left for extensions of the list of simple statements in the specification.</p>
<p>Moreover, <code>print</code> as a statement no longer exists in Python 3.0 and is replaced by the <code>print()</code> builtin function.</p>
| 9
|
2009-01-28T21:45:29Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 489,543
|
<p>If what you're looking for is to add a new statement (like <code>print</code>) to Python's language, then this would not be easy. You'd probably have to modify lexer, parser and then recompile Python's C sources. A lot of work to do for a questionable convenience.</p>
| 3
|
2009-01-28T21:48:16Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 489,550
|
<p>Not if you want to pass in arguments. You could do something build an object that ABUSES the <code>__str__</code> method, but it is highly not recommended. You can also use other operators like overload the <code><<</code> operator like <code>cout</code> does in C++.</p>
| 2
|
2009-01-28T21:49:13Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 489,566
|
<p>In Python 2.x print is not a function it is a statement just as if, while and def are statements.</p>
| 1
|
2009-01-28T21:56:11Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 489,611
|
<p>I would not implement this, but if I was implementing this, I would give code with myfunc a special extension, write an import hook to parse the file, add the parenthesis to make it valid Python, and feed that into the interpreter.</p>
| 3
|
2009-01-28T22:05:38Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 494,066
|
<p>This probably isn't going to cover your problem, but I'll mention it anyway. If <code>myfunc</code> is part of a module, and you are using it like this:</p>
<pre><code>from mymodule import myfunc
myfunc # I want this to turn into a function call
</code></pre>
<p>Then you could instead do this:</p>
<pre><code>import mymodule
mymodule.myfunc # I want this to turn into a function call
</code></pre>
<p>You could then remove <code>myfunc</code> from <code>mymodule</code> and overload the module so it calls a particular function each time the <code>myfunc</code> member is requested.</p>
| 0
|
2009-01-30T00:30:34Z
|
[
"python"
] |
Is there a way to make a user-defined Python function act like a built-in statement?
| 489,524
|
<p>Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:</p>
<pre><code>myfunc
</code></pre>
<p>rather than:</p>
<pre><code>myfunc()
</code></pre>
<p>and have it get called anyway -- the way that, say, <code>print</code> would.</p>
<p>I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.</p>
| 1
|
2009-01-28T21:43:58Z
| 7,842,942
|
<p>Not possible in a planned way, or without a lot of work.</p>
<p>If you are bold and adventurous, read this wikipedia article about meta circular evaluation. Python has pretty good inspection and reflection on its own compiler/evaluater objects, you may be able to cobble something together along these lines.</p>
<blockquote>
<p>"""Meta-circular implementations are suited to extending the language
they are written in. They are also useful for writing tools that are
tightly integrated with the programming language, such as
sophisticated debuggers. A language designed with a meta-circular
implementation in mind is often more suited for building languages in
general, even ones completely different from the host language."""</p>
</blockquote>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Meta-circular_evaluator" rel="nofollow">http://en.wikipedia.org/wiki/Meta-circular_evaluator</a></li>
</ul>
<p>I believe pypy is doing something similarily, you might want to look into it.</p>
<ul>
<li><a href="http://pypy.org" rel="nofollow">http://pypy.org</a></li>
</ul>
| 1
|
2011-10-20T22:18:54Z
|
[
"python"
] |
Connecting to MySQL with Python 2.6...how?
| 489,807
|
<p>All my searches, including <a href="http://stackoverflow.com/questions/372885/how-to-connect-to-a-mysql-database-from-python">this question</a> on Stack, point me to MySQLdb. Unfortunately MySQLdb doesn't have a version for Python 2.6.</p>
<p>What am I to do?</p>
| 1
|
2009-01-28T22:57:04Z
| 489,825
|
<p>Have you tried compiling it for Python 2.6? The APIs change very little in minor releases, so it's likely to Just Work (TM).</p>
<p>Edit: According to <a href="http://mail.python.org/pipermail/python-list/2008-November/516315.html" rel="nofollow">this post</a>, it does work and the poster mentions that Windows binaries have been posted.</p>
| 2
|
2009-01-28T23:01:13Z
|
[
"python",
"mysql"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 489,924
|
<p>Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:</p>
<pre><code>import os
def my_lock(f):
if os.name == "posix":
# Unix or OS X specific locking here
elif os.name == "nt":
# Windows specific locking here
else:
print "Unknown operating system, lock unavailable"
</code></pre>
| 5
|
2009-01-28T23:45:51Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 490,032
|
<p>Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.</p>
<p>Your best bet is have a separate process that coordinates read/write access to that file.</p>
| 9
|
2009-01-29T00:24:06Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 490,102
|
<p>There is a cross-platform file locking module here: <a href="https://pypi.python.org/pypi/portalocker" rel="nofollow">Portalocker</a></p>
<p>Although as Kevin says, writing to a file from multiple processes at once is something you want to avoid if at all possible.</p>
<p>If you can shoehorn your problem into a database, you could use SQLite. It supports concurrent access and handles its own locking.</p>
| 25
|
2009-01-29T01:01:50Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 490,919
|
<p>Locking is platform and device specific, but generally, you have a few options:</p>
<ol>
<li>use flock(), or equivilent (if your os supports it). This is advisory locking, unless you check for the lock, its ignored.</li>
<li>Use a lock-copy-move-unlock methodology, where you copy the file, write the new data, then move it (move, not copy - move is an atomic operation in Linux -- check your OS), and you check for the existence of the lock file.</li>
<li>Use a directory as a "lock". This is necessary if you're writing to NFS, since NFS doesn't support flock().</li>
<li>There's also the possibility of using shared memory between the processes, but I've never tried that; its very os-specific.</li>
</ol>
<p>For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock. This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue.</p>
<p>If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above). </p>
<p>Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.</p>
| 7
|
2009-01-29T08:46:38Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 498,505
|
<p>Alright, so I ended up going with the code I wrote <a href="http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/">here, on my website</a> (<a href="https://github.com/dmfrey/FileLock">also available on GitHub</a>). I can use it in the following fashion:</p>
<pre><code>from filelock import FileLock
with FileLock("myfile.txt"):
# work with the file as it is now locked
print("Lock acquired.")
</code></pre>
| 65
|
2009-01-31T08:30:04Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 2,872,043
|
<p>Kernel-level file locking is an extremly complex subject, since different types of locks have very different semantic, and the main lock of unix systems (fcntl) has horrible flaws.</p>
<p>But I've just released a python library which deals with the issue in a very portable way. It can achieve shared/exclusive file record locking in a system-wide manner, and provides workaround for fcntl flaws.</p>
<p>Enjoy RSFile - <a href="http://bitbucket.org/pchambon/python-rock-solid-tools/" rel="nofollow">http://bitbucket.org/pchambon/python-rock-solid-tools/</a></p>
| 0
|
2010-05-20T08:20:23Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 3,343,885
|
<p>I prefer <strong><a href="https://github.com/smontanaro/pylockfile">lockfile</a></strong> â Platform-independent file locking</p>
| 15
|
2010-07-27T13:04:47Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 18,317,453
|
<p>I found a simple and worked(!) <a href="https://github.com/bmc/grizzled-python/blob/master/grizzled/io/filelock.py" rel="nofollow">implementation</a> from grizzled-python.</p>
<p>Simple use os.open(..., O_EXCL) + os.close() didn't work on windows.</p>
| 1
|
2013-08-19T15:22:58Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 25,172,660
|
<p>I have been working on a situation like this where I run multiple copies of the same program from within the same directory/folder and logging errors. My approach was to write a "lock file" to the disc before opening the log file. The program checks for the presence of the "lock file" before proceeding, and waits it's turn if the "lock file" exists.</p>
<p>Here is the code:</p>
<pre><code>def errlogger(error):
while True:
if not exists('errloglock'):
lock = open('errloglock', 'w')
if exists('errorlog'): log = open('errorlog', 'a')
else: log = open('errorlog', 'w')
log.write(str(datetime.utcnow())[0:-7] + ' ' + error + '\n')
log.close()
remove('errloglock')
return
else:
check = stat('errloglock')
if time() - check.st_ctime > 0.01: remove('errloglock')
print('waiting my turn')
</code></pre>
<p>EDIT---
After thinking over some of the comments about stale locks above I edited the code to add a check for staleness of the "lock file." Timing several thousand iterations of this function on my system gave and average of 0.002066... seconds from just before:</p>
<pre><code>lock = open('errloglock', 'w')
</code></pre>
<p>to just after:</p>
<pre><code>remove('errloglock')
</code></pre>
<p>so I figured I will start with 5 times that amount to indicate staleness and monitor the situation for problems.</p>
<p>Also, as I was working with the timing, I realized that I had a bit of code that was not really necessary:</p>
<pre><code>lock.close()
</code></pre>
<p>which I had immediately following the open statement, so I have removed it in this edit.</p>
| 0
|
2014-08-07T01:01:51Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 34,124,007
|
<p>I have been looking at several solutions to do that and my choice has been
<a href="http://docs.openstack.org/developer/oslo.concurrency/" rel="nofollow">oslo.concurrency</a></p>
<p>It's powerful and relatively well documented. It's based on fasterners.</p>
<p>Other solutions:</p>
<ul>
<li><a href="https://pypi.python.org/pypi/portalocker" rel="nofollow">Portalocker</a>: requires pywin32, which is an exe installation, so not possible via pip</li>
<li><a href="https://pypi.python.org/pypi/fasteners" rel="nofollow">fasterners</a>: poorly documented</li>
<li><a href="https://pypi.python.org/pypi/lockfile" rel="nofollow">lockfile</a>: deprecated</li>
<li><a href="https://pypi.python.org/pypi/flufl.lock/2.4.1" rel="nofollow">flufl.lock</a>: NFS-safe file locking for POSIX systems.</li>
<li><a href="https://github.com/derpston/python-simpleflock" rel="nofollow">simpleflock</a> : Last update 2013-07</li>
<li><a href="https://pypi.python.org/pypi/zc.lockfile?" rel="nofollow">zc.lockfile</a> : Last update 2013-02</li>
<li><a href="https://pypi.python.org/pypi/lock_file/2.0" rel="nofollow">lock_file</a> : Last update in 2007-10</li>
</ul>
| 2
|
2015-12-06T23:09:02Z
|
[
"python",
"file-locking"
] |
Locking a file in Python
| 489,861
|
<p>I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.</p>
| 81
|
2009-01-28T23:20:03Z
| 39,708,102
|
<p>you may find <a href="https://bachiraoun.github.io/pylocker/" rel="nofollow">pyloker</a> very useful. It can be used to lock a file or for locking mechanisms in general and can be accessed from multiple Python processes at once. </p>
<p>If you want simply to lock a file here's how it works </p>
<pre><code>import uuid
from pylocker import Locker
# create a unique lock pass. This can be any string.
lpass = str(uuid.uuid1())
# create locker instance.
FL = Locker(filePath='myfile.txt', lockPass=lpass, mode='w')
# aquire the lock
with FL as r:
# get the result
acquired, code, fd = r
# check if aquired.
if fd is not None:
print fd
fd.write("I have succesfuly aquired the lock !")
# no need to release anything or to close the file descriptor,
# with statement takes care of that. let's print fd and verify that.
print fd
</code></pre>
| 0
|
2016-09-26T16:41:45Z
|
[
"python",
"file-locking"
] |
How can I extract x, y and z coordinates from geographical data by Python?
| 489,901
|
<p>I have geographical data which has 14 variables. The data is in the following format:</p>
<blockquote>
<p>QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625<br />
ULLON: -97.87527466 LRLAT: 43.5<br />
LRLON: -97.75027466 HDATUM: 27<br />
ZMIN: 361.58401489 ZMAX:
413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5<br />
QUADDATE: 20001001</p>
</blockquote>
<p>The whole data has many previous variables in the sequence.</p>
<p>How can I extract the coordinates ULLAT, ULLON and LRLAT from the data into three lists, so that the each row corresponds to one location?</p>
<p>This question was raised by the problem in <a href="http://stackoverflow.com/questions/486807/where-can-i-get-the-x-y-z-coordinates-for-california-to-use-a-contour-plot">the post</a>.</p>
| 0
|
2009-01-28T23:36:31Z
| 490,065
|
<p>Given a <a href="http://docs.python.org/library/codecs.html#streamreader-objects" rel="nofollow">StreamReader</a> named reader, this should give you a list of (float, float, float). I suggest a list of 3-tuples because it'll probably be more convenient and more efficient to walk through, unless for some reason you only want to get all the points individually. </p>
<pre><code>coords = []
reader
while line=reader.readline():
index_ullat = line.find("ULLAT")
if index_ullat >= 0:
ullat = float(line[ index_ULLAT+7 : ])
line = reader.readline()
index_ullon = line.find("ULLON")
index_lrlat = line.find("LRLAT")
if index_ullon >= 0 and index_lrlat >= 0:
ullon = float(line[ index_ullon+7 : index_lrlat-1 ])
lrlat = float(line[ index_lrlat+7 : ])
else:
raise InputError, "ULLON and LRLAT didn't follow ULLAT."
coords.append(ullat, ullon, lrlat)
</code></pre>
<p>It may work, but it's ugly. I'm no expert at string parsing.</p>
| 2
|
2009-01-29T00:40:57Z
|
[
"python",
"extraction",
"geography"
] |
How can I extract x, y and z coordinates from geographical data by Python?
| 489,901
|
<p>I have geographical data which has 14 variables. The data is in the following format:</p>
<blockquote>
<p>QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625<br />
ULLON: -97.87527466 LRLAT: 43.5<br />
LRLON: -97.75027466 HDATUM: 27<br />
ZMIN: 361.58401489 ZMAX:
413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5<br />
QUADDATE: 20001001</p>
</blockquote>
<p>The whole data has many previous variables in the sequence.</p>
<p>How can I extract the coordinates ULLAT, ULLON and LRLAT from the data into three lists, so that the each row corresponds to one location?</p>
<p>This question was raised by the problem in <a href="http://stackoverflow.com/questions/486807/where-can-i-get-the-x-y-z-coordinates-for-california-to-use-a-contour-plot">the post</a>.</p>
| 0
|
2009-01-28T23:36:31Z
| 490,347
|
<p>Something like this might work if the data is all in a big flat text file:</p>
<pre><code>import re
data = """
QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625
ULLON: -97.87527466 LRLAT: 43.5
LRLON: -97.75027466 HDATUM: 27
ZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5
QUADDATE: 20001001
"""
regex = re.compile(
r"""ULLAT:\ (?P<ullat>-?[\d.]+).*?
ULLON:\ (?P<ullon>-?[\d.]+).*?
LRLAT:\ (?P<lrlat>-?[\d.]+)""", re.DOTALL|re.VERBOSE)
print regex.findall(data) # Yields: [('43.625', '-97.87527466', '43.5')]
</code></pre>
| 4
|
2009-01-29T02:55:42Z
|
[
"python",
"extraction",
"geography"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,020
|
<pre><code># Over-explaining a bit:
def magic(numList): # [1,2,3]
s = map(str, numList) # ['1','2','3']
s = ''.join(s) # '123'
s = int(s) # 123
return s
# How I'd probably write it:
def magic(numList):
s = ''.join(map(str, numList))
return int(s)
# As a one-liner
num = int(''.join(map(str,numList)))
# Functionally:
s = reduce(lambda x,y: x+str(y), numList, '')
num = int(s)
# Using some oft-forgotten built-ins:
s = filter(str.isdigit, repr(numList))
num = int(s)
</code></pre>
| 92
|
2009-01-29T00:21:26Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,024
|
<p>pseudo-code:</p>
<pre>int magic(list nums)
{
int tot = 0
while (!nums.isEmpty())
{
int digit = nums.takeFirst()
tot *= 10
tot += digit
}
return tot
}</pre>
| 3
|
2009-01-29T00:22:17Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,029
|
<pre><code>def magic(numbers):
return int(''.join([ "%d"%x for x in numbers]))
</code></pre>
| 5
|
2009-01-29T00:23:31Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,031
|
<p>Two solutions:</p>
<pre><code>>>> nums = [1, 2, 3]
>>> magic = lambda nums: int(''.join(str(i) for i in nums)) # Generator exp.
>>> magic(nums)
123
>>> magic = lambda nums: sum(digit * 10 ** (len(nums) - 1 - i) # Summation
... for i, digit in enumerate(nums))
>>> magic(nums)
123
</code></pre>
<p>The <code>map</code>-oriented solution actually comes out ahead on my box -- you definitely should not use <code>sum</code> for things that might be large numbers:</p>
<p><img src="http://lh3.ggpht.com/_t58Xs7CN35o/SYETlAnN6NI/AAAAAAAABSg/KJetpOdJcKw/s400/image.png" alt="Timeit Comparison" /></p>
<pre><code>import collections
import random
import timeit
import matplotlib.pyplot as pyplot
MICROSECONDS_PER_SECOND = 1E6
FUNS = []
def test_fun(fun):
FUNS.append(fun)
return fun
@test_fun
def with_map(nums):
return int(''.join(map(str, nums)))
@test_fun
def with_interpolation(nums):
return int(''.join('%d' % num for num in nums))
@test_fun
def with_genexp(nums):
return int(''.join(str(num) for num in nums))
@test_fun
def with_sum(nums):
return sum(digit * 10 ** (len(nums) - 1 - i)
for i, digit in enumerate(nums))
@test_fun
def with_reduce(nums):
return int(reduce(lambda x, y: x + str(y), nums, ''))
@test_fun
def with_builtins(nums):
return int(filter(str.isdigit, repr(nums)))
@test_fun
def with_accumulator(nums):
tot = 0
for num in nums:
tot *= 10
tot += num
return tot
def time_test(digit_count, test_count=10000):
"""
:return: Map from func name to (normalized) microseconds per pass.
"""
print 'Digit count:', digit_count
nums = [random.randrange(1, 10) for i in xrange(digit_count)]
stmt = 'to_int(%r)' % nums
result_by_method = {}
for fun in FUNS:
setup = 'from %s import %s as to_int' % (__name__, fun.func_name)
t = timeit.Timer(stmt, setup)
per_pass = t.timeit(number=test_count) / test_count
per_pass *= MICROSECONDS_PER_SECOND
print '%20s: %.2f usec/pass' % (fun.func_name, per_pass)
result_by_method[fun.func_name] = per_pass
return result_by_method
if __name__ == '__main__':
pass_times_by_method = collections.defaultdict(list)
assert_results = [fun([1, 2, 3]) for fun in FUNS]
assert all(result == 123 for result in assert_results)
digit_counts = range(1, 100, 2)
for digit_count in digit_counts:
for method, result in time_test(digit_count).iteritems():
pass_times_by_method[method].append(result)
for method, pass_times in pass_times_by_method.iteritems():
pyplot.plot(digit_counts, pass_times, label=method)
pyplot.legend(loc='upper left')
pyplot.xlabel('Number of Digits')
pyplot.ylabel('Microseconds')
pyplot.show()
</code></pre>
| 31
|
2009-01-29T00:23:42Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,250
|
<pre><code>def magic(number):
return int(''.join(str(i) for i in number))
</code></pre>
| 5
|
2009-01-29T02:04:01Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,312
|
<p>This seems pretty clean, to me.</p>
<pre><code>def magic( aList, base=10 ):
n= 0
for d in aList:
n = base*n + d
return n
</code></pre>
| 3
|
2009-01-29T02:34:59Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,392
|
<p>This method works in 2.x as long as each element in the list is only a single digit. But you shouldn't actually use this. It's horrible.</p>
<pre><code>>>> magic = lambda l:int(`l`[1::3])
>>> magic([3,1,3,3,7])
31337
</code></pre>
| 2
|
2009-01-29T03:31:57Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 490,400
|
<p>Using a generator expression:</p>
<pre><code>def magic(numbers):
digits = ''.join(str(n) for n in numbers)
return int(digits)
</code></pre>
| 2
|
2009-01-29T03:37:16Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 493,944
|
<p>Just for completeness, here's a variant that uses <code>print()</code> (works on Python 2.6-3.x):</p>
<pre><code>from __future__ import print_function
try: from cStringIO import StringIO
except ImportError:
from io import StringIO
def to_int(nums, _s = StringIO()):
print(*nums, sep='', end='', file=_s)
s = _s.getvalue()
_s.truncate(0)
return int(s)
</code></pre>
<p><hr /></p>
<p>I've measured performance of <a href="http://stackoverflow.com/questions/489999/python-convert-list-of-ints-to-one-number#490031">@cdleary's functions</a>. The results are slightly different. </p>
<p>Each function tested with the input list generated by:</p>
<pre><code>def randrange1_10(digit_count): # same as @cdleary
return [random.randrange(1, 10) for i in xrange(digit_count)]
</code></pre>
<p>You may supply your own function via <code>--sequence-creator=yourmodule.yourfunction</code> command-line argument (see below).</p>
<p>The fastest functions for a given number of integers in a list (<code>len(nums) == digit_count</code>) are:</p>
<ul>
<li><p><code>len(nums)</code> in <strong>1..30</strong> </p>
<pre><code>def _accumulator(nums):
tot = 0
for num in nums:
tot *= 10
tot += num
return tot
</code></pre></li>
<li><p><code>len(nums)</code> in <strong>30..1000</strong> </p>
<pre><code>def _map(nums):
return int(''.join(map(str, nums)))
def _imap(nums):
return int(''.join(imap(str, nums)))
</code></pre></li>
</ul>
<p><img src="http://i403.photobucket.com/albums/pp111/uber_ulrich/ints2int/_010randrange1_10.png" alt="Figure: N = 1000" /></p>
<pre><code>|------------------------------+-------------------|
| Fitting polynom | Function |
|------------------------------+-------------------|
| 1.00 log2(N) + 1.25e-015 | N |
| 2.00 log2(N) + 5.31e-018 | N*N |
| 1.19 log2(N) + 1.116 | N*log2(N) |
| 1.37 log2(N) + 2.232 | N*log2(N)*log2(N) |
|------------------------------+-------------------|
| 1.21 log2(N) + 0.063 | _interpolation |
| 1.24 log2(N) - 0.610 | _genexp |
| 1.25 log2(N) - 0.968 | _imap |
| 1.30 log2(N) - 1.917 | _map |
</code></pre>
<p><img src="http://i403.photobucket.com/albums/pp111/uber_ulrich/ints2int/_020randrange1_10.png" alt="Figure: N = 1000_000" /></p>
<p>To plot the first figure download <a href="http://gist.github.com/51074" rel="nofollow"><code>cdleary.py</code> and <code>make-figures.py</code></a> and run (<code>numpy</code> and <code>matplotlib</code> must be installed to plot):</p>
<pre><code>$ python cdleary.py
</code></pre>
<p>Or </p>
<pre><code>$ python make-figures.py --sort-function=cdleary._map \
> --sort-function=cdleary._imap \
> --sort-function=cdleary._interpolation \
> --sort-function=cdleary._genexp --sort-function=cdleary._sum \
> --sort-function=cdleary._reduce --sort-function=cdleary._builtins \
> --sort-function=cdleary._accumulator \
> --sequence-creator=cdleary.randrange1_10 --maxn=1000
</code></pre>
| 3
|
2009-01-29T23:26:56Z
|
[
"python"
] |
Convert list of ints to one number?
| 489,999
|
<p>I have a list of integers that I would like to convert to one number like:</p>
<pre><code>numList = [1, 2, 3]
num = magic(numList)
print num, type(num)
>>> 123, <type 'int'>
</code></pre>
<p>What is the best way to implement the <em>magic</em> function?</p>
<p><strong>EDIT</strong> <br>
I did find <a href="http://bytes.com/groups/python/722951-int-str-list-elements" rel="nofollow">this</a>, but it seems like there has to be a better way.</p>
| 29
|
2009-01-29T00:16:23Z
| 37,451,273
|
<p>A one-liner without needing to cast to and from <code>str</code></p>
<pre><code>def magic(num):
return sum(e * 10**i for i, e in enumerate(num[::-1]))
</code></pre>
| 0
|
2016-05-26T03:52:47Z
|
[
"python"
] |
QScintilla scrollbar
| 490,130
|
<p>When I add a QsciScintilla object to my main window the horizontal scrollbar is active and super wide (tons of apparent white space). Easy fix?</p>
| 1
|
2009-01-29T01:10:18Z
| 490,198
|
<p>Easy fix:</p>
<pre><code>sc.SendScintilla(sc.SCI_SETHSCROLLBAR, 0)
</code></pre>
| 1
|
2009-01-29T01:36:37Z
|
[
"python",
"qt",
"scintilla"
] |
split a multi-page pdf file into multiple pdf files with python?
| 490,195
|
<p>I'd like to take a multi-page pdf file and create separate pdf files per page.</p>
<p>I've downloaded <a href="http://www.reportlab.org/index.html">reportlab</a> and have browsed the documentation, but it seems aimed at pdf generation, I haven't yet seen anything about processing pdf's themselves.</p>
<p>Is there an easy way to do this in python?</p>
| 20
|
2009-01-29T01:35:48Z
| 490,203
|
<p>pyPdf can handle this nicely (c.f. <a href="http://pybrary.net/pyPdf/">http://pybrary.net/pyPdf/</a> )</p>
<pre>
from pyPdf import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(open("document.pdf", "rb"))
for i in xrange(inputpdf.numPages):
output = PdfFileWriter()
output.addPage(inputpdf.getPage(i))
with open("document-page%s.pdf" % i, "wb") as outputStream:
output.write(outputStream)
</pre>
<p>etc.</p>
| 46
|
2009-01-29T01:38:47Z
|
[
"python",
"pdf"
] |
split a multi-page pdf file into multiple pdf files with python?
| 490,195
|
<p>I'd like to take a multi-page pdf file and create separate pdf files per page.</p>
<p>I've downloaded <a href="http://www.reportlab.org/index.html">reportlab</a> and have browsed the documentation, but it seems aimed at pdf generation, I haven't yet seen anything about processing pdf's themselves.</p>
<p>Is there an easy way to do this in python?</p>
| 20
|
2009-01-29T01:35:48Z
| 35,910,519
|
<p>also, you can use PDFSplitterX at <a href="https://www.coolutils.com/PDFSplitterXPython" rel="nofollow">https://www.coolutils.com/PDFSplitterXPython</a></p>
<p>example</p>
<pre><code>import win32com.client
import os.path
c = win32com.client.Dispatch("PDFSplitter.PDFSplitterX")
src="C:\\test\\test.pdf";
dest="C:\\test\\DestFolder";
c.convert(src, dest, "-c PDF -log c:\\test\\PDFSplitter.log");
if not os.path.exists(file_path):
print(c.ErrorMessage)
</code></pre>
| 0
|
2016-03-10T07:49:15Z
|
[
"python",
"pdf"
] |
What is the most pythonic way to make a bound method act like a function?
| 490,429
|
<p>I'm using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API will not call it with the correct 'self' argument, so I'm wondering how to turn a method into a function that knows what 'self' it belongs to.</p>
<p>There are a couple of ways that I can think of to do this, including using a lambda and a closure. I've included some examples of this below, but I'm wondering if there is a standard mechanism for achieving the same effect.</p>
<pre><code>class A(object):
def hello(self, salutation):
print('%s, my name is %s' % (salutation, str(self)))
def bind_hello1(self):
return lambda x: self.hello(x)
def bind_hello2(self):
def hello2(*args):
self.hello(*args)
return hello2
>>> a1, a2 = A(), A()
>>> a1.hello('Greetings'); a2.hello('Greetings')
Greetings, my name is <__main__.A object at 0x71570>
Greetings, my name is <__main__.A object at 0x71590>
>>> f1, f2 = a1.bind_hello1(), a2.bind_hello1()
>>> f1('Salutations'); f2('Salutations')
Salutations, my name is <__main__.A object at 0x71570>
Salutations, my name is <__main__.A object at 0x71590>
>>> f1, f2 = a1.bind_hello2(), a2.bind_hello2()
>>> f1('Aloha'); f2('Aloha')
Aloha, my name is <__main__.A object at 0x71570>
Aloha, my name is <__main__.A object at 0x71590>
</code></pre>
| 3
|
2009-01-29T03:55:06Z
| 490,437
|
<p>Will passing in the method bound to a instance work? If so, you don't have to do anything special.</p>
<pre><code>In [2]: class C(object):
...: def method(self, a, b, c):
...: print a, b, c
...:
...:
In [3]: def api_function(a_func):
...: a_func("One Fish", "Two Fish", "Blue Fish")
...:
...:
In [4]: c = C()
In [5]: api_function(c.method)
One Fish Two Fish Blue Fish
</code></pre>
| 8
|
2009-01-29T03:58:53Z
|
[
"python",
"function",
"methods",
"closures"
] |
What is the most pythonic way to make a bound method act like a function?
| 490,429
|
<p>I'm using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API will not call it with the correct 'self' argument, so I'm wondering how to turn a method into a function that knows what 'self' it belongs to.</p>
<p>There are a couple of ways that I can think of to do this, including using a lambda and a closure. I've included some examples of this below, but I'm wondering if there is a standard mechanism for achieving the same effect.</p>
<pre><code>class A(object):
def hello(self, salutation):
print('%s, my name is %s' % (salutation, str(self)))
def bind_hello1(self):
return lambda x: self.hello(x)
def bind_hello2(self):
def hello2(*args):
self.hello(*args)
return hello2
>>> a1, a2 = A(), A()
>>> a1.hello('Greetings'); a2.hello('Greetings')
Greetings, my name is <__main__.A object at 0x71570>
Greetings, my name is <__main__.A object at 0x71590>
>>> f1, f2 = a1.bind_hello1(), a2.bind_hello1()
>>> f1('Salutations'); f2('Salutations')
Salutations, my name is <__main__.A object at 0x71570>
Salutations, my name is <__main__.A object at 0x71590>
>>> f1, f2 = a1.bind_hello2(), a2.bind_hello2()
>>> f1('Aloha'); f2('Aloha')
Aloha, my name is <__main__.A object at 0x71570>
Aloha, my name is <__main__.A object at 0x71590>
</code></pre>
| 3
|
2009-01-29T03:55:06Z
| 490,465
|
<p>You may want to clarify your question. As Ryan points out,</p>
<pre><code>def callback(fn):
fn('Welcome')
callback(a1.hello)
callback(a2.hello)
</code></pre>
<p>will result in <code>hello</code> being called with the correct <code>self</code> bound, <code>a1</code> or <code>a2</code>. If you are not experiencing this, something is deeply wrong, because that's how Python works.</p>
<p>What you seem to want, judging by what you've written, is to bind arguments -- in other words, <a href="http://en.wikipedia.org/wiki/Function_currying" rel="nofollow">currying</a>. You can find examples all over the place, but <a href="http://code.activestate.com/recipes/52549/" rel="nofollow">Recipe 52549</a> has the best Pythonic appearance, by my tastes.</p>
<pre><code>class curry:
def __init__(self, fun, *args, **kwargs):
self.fun = fun
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
if kwargs and self.kwargs:
kw = self.kwargs.copy()
kw.update(kwargs)
else:
kw = kwargs or self.kwargs
return self.fun(*(self.pending + args), **kw)
f1 = curry(a1.hello, 'Salutations')
f1() # == a1.hello('Salutations')
</code></pre>
| 0
|
2009-01-29T04:19:17Z
|
[
"python",
"function",
"methods",
"closures"
] |
django-cart or Satchmo?
| 490,439
|
<p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p>
| 23
|
2009-01-29T04:00:49Z
| 490,446
|
<p>I think the reason there aren't really many out-of-the-box solutions is because most people who use Django are power users. They tend to want to roll out their own solutions, especially considering how easy it is to do in Django.</p>
<p>To answer your question, <a href="http://demo.djwarehouse.org/" rel="nofollow">DJwarehouse</a> is the only other cart I'm aware of. </p>
| 5
|
2009-01-29T04:04:28Z
|
[
"python",
"django",
"e-commerce",
"satchmo"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.