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 |
|---|---|---|---|---|---|---|---|---|---|
Retrieving network mask in Python | 936,444 | <p>How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?</p>
<pre><code>ioctl(socknr, SIOCGIFNETMASK, &ifreq) // C version
</code></pre>
| 3 | 2009-06-01T19:50:14Z | 32,545,039 | <p>I had the idea to rely on subprocess to use a simple ifconfig (Linux) or ipconfig (windows) request to retrieve the info (if the ip is known).
<strong><em>Comments welcome</em></strong> : </p>
<p>WINDOWS</p>
<pre><code>ip = '192.168.1.10' #Example
proc = subprocess.Popen('ipconfig',stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ip.encode() in line:
break
mask = proc.stdout.readline().rstrip().split(b':')[-1].replace(b' ',b'').decode()
</code></pre>
<p>UNIX-Like</p>
<pre><code>ip = '192.168.1.10' #Example
proc = subprocess.Popen('ifconfig',stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ip.encode() in line:
break
mask = line.rstrip().split(b':')[-1].replace(b' ',b'').decode()
</code></pre>
<p>IP is retrieved using a socket connection to the web and using <code>getsockname()[0]</code></p>
| 1 | 2015-09-13T00:09:12Z | [
"python"
] |
Python and subprocess | 936,505 | <p>This is for a script I'm working on. It's supposed to run an .exe file for the loop below. (By the way not sure if it's visible but for el in ('90','52.6223',...) is outside the loop and makes a nested loop with the rest) I'm not sure if the ordering is correct or what not. Also when the .exe file is ran, it spits some stuff out and I need a certain line printed to the screen (hence where you see AspecificLinfe= ... ). Any helpful answers would be great!</p>
<pre><code>for el in ('90.','52.62263.','26.5651.','10.8123.'):
if el == '90.':
z = ('0.')
elif el == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif el == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
else el == '10.8123':
z = ('288.', '0.', '72.', '144.', '216.')
for az in z:
comstring = os.path.join('Path where .exe file is')
comstring = os.path.normpath(comstring)
comstring = '"' + comstring + '"'
comstringfull = comstring + ' -el ' + str(el) + ' -n ' + str(z)
print 'The python program is running this command with the shell:'
print comstring + '\n'
process = Popen(comstring,shell=True,stderr=STDOUT,stdout=PIPE)
outputstring = myprocesscommunicate()
print 'The command shell returned the following back to python:'
print outputstring[0]
AspecificLine=linecache.getline(' ??filename?? ', # ??
sys.stderr.write('az', 'el', 'AREA' ) # ??
</code></pre>
| 0 | 2009-06-01T20:04:33Z | 936,705 | <p>Using <code>shell=True</code> is wrong because that needlessy invokes the shell.</p>
<p>Instead, do this:</p>
<pre><code>for el in ('90.','52.62263.','26.5651.','10.8123.'):
if el == '90.':
z = ('0.')
elif el == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif el == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
else el == '10.8123':
z = ('288.', '0.', '72.', '144.', '216.')
for az in z:
exepath = os.path.join('Path where .exe file is')
exepath = os.path.normpath(comstring)
cmd = [exepath, '-el', str(el), '-n', str(z)]
print 'The python program is running this command:'
print cmd
process = Popen(cmd, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
print 'The command returned the following back to python:'
print outputstring
outputlist = outputstring.splitlines()
AspecificLine = outputlist[22] # get some specific line. 23?
print AspecificLine
</code></pre>
| 1 | 2009-06-01T20:45:47Z | [
"python",
"loops",
"subprocess",
"popen"
] |
How do I pass an exception between threads in python | 936,556 | <p>I need to pass exceptions across a thread boundary.</p>
<p>I'm using python embedded in a non thread safe app which has one thread safe call, post_event(callable), which calls callable from its main thread.</p>
<p>I am running a pygtk gui in a seperate thread, so when a button is clicked I post an event with post_event, and wait for it to finish before continuing. But I need the caller to know if the callee threw an exception, and raise it if so. I'm not too worried about the traceback, just the exception itself.</p>
<p>My code is roughly:</p>
<pre><code>class Callback():
def __init__(self,func,*args):
self.func=func
self.args=args
self.event=threading.Event()
self.result=None
self.exception=None
def __call__(self):
gtk.gdk.threads_enter()
try:
self.result=self.func(*self.args)
except:
#what do I do here? How do I store the exception?
pass
finally:
gtk.gdk.threads_leave()
self.event.set()
def post(self):
post_event(self)
gtk.gdk.threads_leave()
self.event.wait()
gtk.gdk.threads_enter()
if self.exception:
raise self.exception
return self.result
</code></pre>
<p>Any help appreciated, thanks.</p>
| 7 | 2009-06-01T20:17:57Z | 936,675 | <blockquote>
<p>#what do I do here? How do I store the exception?</p>
</blockquote>
<p>Use <code>sys.exc_info()[:2]</code>, see <a href="http://pyref.infogami.com/sys.exc%5Finfo">this wiki</a></p>
<p>Best way to communicate among threads is <a href="http://docs.python.org/library/queue.html">Queue</a>. Have the main thread instantiate a <code>Queue.Queue</code> instance and pass it to subthreads; when a subthread has something to communicate back to the master it uses <code>.put</code> on that queue (e.g. a tuple with thread id, exception type, exception value -- or, other useful info, not necessarily exception-related, just make sure the first item of a tuple identifies the kind of info;-). The master can <code>.get</code> those info-units back when it wants, with various choices for synchronization and so on.</p>
| 11 | 2009-06-01T20:41:14Z | [
"python",
"multithreading",
"exception"
] |
Creating connection between two computers in python | 936,625 | <p>The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use?</p>
<p>The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed.</p>
<p>Thanks!</p>
| 9 | 2009-06-01T20:32:24Z | 936,656 | <p><a href="http://twistedmatrix.com/">Twisted</a> is a python event-driven networking engine licensed under MIT. Means that a single machine can communicate with one or more other machines, while doing other things between data being received and sent, all asynchronously, and running a in a single thread/process.</p>
<p>It supports many protocols out of the box, so you can just as well using an existing one. That's better because you get support for the protocol from 3rd party software (i.e. using HTTP for communication means middleware software that uses HTTP will be compatible: proxies etc.)</p>
<p>It also makes easy to create your own communication protocol, if that's what you want.</p>
<p>The <a href="http://twistedmatrix.com/projects/core/documentation/howto/index.html">documentation</a> is filled with examples.</p>
| 10 | 2009-06-01T20:36:38Z | [
"python",
"networking"
] |
Creating connection between two computers in python | 936,625 | <p>The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use?</p>
<p>The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed.</p>
<p>Thanks!</p>
| 9 | 2009-06-01T20:32:24Z | 936,679 | <p>A great place to start looking is the <a href="http://docs.python.org/library/" rel="nofollow">Python Standard Library</a>. In particular there are a few sections that will be relevant:</p>
<ul>
<li><a href="http://docs.python.org/library/ipc.html" rel="nofollow">18. Interprocess Communication and Networking</a></li>
<li><a href="http://docs.python.org/library/netdata.html" rel="nofollow">19. Internet Data Handling</a></li>
<li><a href="http://docs.python.org/library/internet.html" rel="nofollow">21. Internet Protocols and Support</a></li>
</ul>
<p>Since you mentioned that you have no experience with this, I'd suggest starting with a HTTP based implementation. The <a href="http://en.wikipedia.org/wiki/Http" rel="nofollow">HTTP</a> protocol is fairly simple and easy to work with. In addition, there are nice frameworks to support this operation, such as <a href="http://webpy.org/" rel="nofollow">webpy</a> for the server and <a href="http://docs.python.org/library/httplib.html" rel="nofollow">HTTPLib</a> from the standard library for the client.</p>
<p>If you really want to dive into networking, then a <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket</a> based implementation might be educational. This will teach you the underlying concepts that are used in <em>lots</em> of networking code while resulting in an interface that is similar to a file stream.</p>
| 3 | 2009-06-01T20:41:46Z | [
"python",
"networking"
] |
Creating connection between two computers in python | 936,625 | <p>The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use?</p>
<p>The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed.</p>
<p>Thanks!</p>
| 9 | 2009-06-01T20:32:24Z | 936,685 | <p>The standard library includes SocketServer (documented <a href="http://docs.python.org/library/socketserver.html">here</a>), which might do what you want.</p>
<p>However I wonder if a better solution might be to use a message queue. Lots of good implementations already exist, including Python interfaces. I've used <a href="http://www.rabbitmq.com/">RabbitMQ</a> before. The idea is that the computers both subscribe to the queue, and can either post or listen for events. </p>
| 7 | 2009-06-01T20:42:17Z | [
"python",
"networking"
] |
Creating connection between two computers in python | 936,625 | <p>The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use?</p>
<p>The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed.</p>
<p>Thanks!</p>
| 9 | 2009-06-01T20:32:24Z | 936,760 | <p>Communication will take place with sockets, one way or another. Just a question of whether you use existing higher-level libraries, or roll your own.</p>
<p>If you're doing this as a learning experience, probably want to start as low-level as you can, to see the real nuts and bolts. Which means you probably want to start with <a href="http://docs.python.org/library/socketserver.html" rel="nofollow">a SocketServer</a>, using a TCP connection (TCP is basically guaranteed delivery of data; UDP is not).</p>
<p>Google for some simple example code. Setting one up is very easy. But you will have to define all the details of your communications protocol: which end sends when and what, which end listens and when, what exactly the listener will expect, does it reply to confirm receipt, etc.</p>
| 1 | 2009-06-01T20:58:48Z | [
"python",
"networking"
] |
Creating connection between two computers in python | 936,625 | <p>The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use?</p>
<p>The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed.</p>
<p>Thanks!</p>
| 9 | 2009-06-01T20:32:24Z | 938,881 | <p>Also, check out <a href="http://pyro.sourceforge.net/" rel="nofollow">Pyro</a> (Python remoting objects). Se <a href="http://stackoverflow.com/questions/656933/communicating-with-a-running-python-daemon/658156#658156">this answer</a> for more details. </p>
<p>Pyro basically allows you to publish Python object instances as services that can be called remotely. Pyro is probably the easiest way to implement Python-to-python process communication.</p>
| 1 | 2009-06-02T10:45:33Z | [
"python",
"networking"
] |
Creating connection between two computers in python | 936,625 | <p>The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use?</p>
<p>The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've recently decided to start on a bigger project. I'm considering creating a Magic: the Gathering booster draft simulator, but I'm not sure if it is feasible given my skill set so I'm asking around before I get started. The application would need to send data between computers about which cards are being picked/passed.</p>
<p>Thanks!</p>
| 9 | 2009-06-01T20:32:24Z | 944,642 | <p>It's also worth looking at <a href="http://www.kamaelia.org/Home" rel="nofollow">Kamaelia</a> for this sort of thing - it's original usecase was network systems, and makes building such things relatively intuitive.
Some links: <a href="http://www.kamaelia.org/Cookbook/TCPSystems" rel="nofollow">Overview of basic TCP system</a>, <a href="http://yeoldeclue.com/cgi-bin/blog/blog.cgi?rm=viewpost&nodeid=1226574014" rel="nofollow">Simple Chat server</a>, <a href="http://yeoldeclue.com/cgi-bin/blog/blog.cgi?rm=viewpost&nodeid=1223342651" rel="nofollow">Building a layered protocol</a>, <a href="http://edit.kamaelia.org/cgi-bin/blog/blog.cgi?rm=viewpost&nodeid=1113495151" rel="nofollow">walk-through of how to evolve new components</a>. Other extreme: P2P radio system: <a href="http://code.google.com/p/kamaelia/source/browse/trunk/Sketches/MPS/Examples/LUGRadio/SimpleSwarmRadioSource.py" rel="nofollow">source</a>, <a href="http://code.google.com/p/kamaelia/source/browse/trunk/Sketches/MPS/Examples/LUGRadio/SimpleSwarm.py" rel="nofollow">peer</a>.</p>
<p>If it makes any difference, we've tested whether the system is accessible to novices through involvement in google summer of code 3 years in a row, actively taking on both experienced and inexperienced developers. All of them managed to build useful systems.</p>
<p>Essentially, if you've ever played with unix pipelines the ideas should be familiar.</p>
<p>Caveat: I wrote major chunks of Kamaelia :-)</p>
<p>If you want to learn how to do these things though, playing with a few different approaches makes sense, and you should definitely check out Twisted (the standard answer to this question), Pyro & the standard library tools. Each has a different approach, and learning them will definitely benefit you!</p>
<p>However, like nosklo, I would recommend against using the socket library directly and use a library instead - simply because it is much much harder to get sockets programming correct than people tend to realise.</p>
| 1 | 2009-06-03T13:07:58Z | [
"python",
"networking"
] |
Why no pure Python SSH1 (version 1) client implementations? | 936,783 | <p>There seem to be a few good pure Python SSH2 client implementations out there, but I haven't been able to find one for SSH1. Is there some specific reason for this other than lack of interest in such a project? I am fully aware of the many SSH1 vulnerabilities, but a pure Python SSH1 client implementation would still be very useful to those of us who want to write SSH clients to manage older embedded devices which only support SSH1 (Cisco PIX for example). I also know I'm not the only person looking for this.</p>
<p>The reason I'm asking is because I'm bored, and I've been thinking about taking a stab at writing this myself. I've just been hesitant to start, since I know there are a lot of people out there who are much smarter than me, and I figured there might be some reason why nobody has done it yet.</p>
| 2 | 2009-06-01T21:06:31Z | 936,816 | <p>Well, the main reason probably was that when people started getting interested in such things in VHLLs such as Python, it didn't make sense to <em>them</em> to implement a standard which they themselves would not find useful.</p>
<p>I am not familiar with the protocol differences, but would it be possible for you to adapt an existing codebase to the older protocol?</p>
| 1 | 2009-06-01T21:14:18Z | [
"python",
"ssh"
] |
Why no pure Python SSH1 (version 1) client implementations? | 936,783 | <p>There seem to be a few good pure Python SSH2 client implementations out there, but I haven't been able to find one for SSH1. Is there some specific reason for this other than lack of interest in such a project? I am fully aware of the many SSH1 vulnerabilities, but a pure Python SSH1 client implementation would still be very useful to those of us who want to write SSH clients to manage older embedded devices which only support SSH1 (Cisco PIX for example). I also know I'm not the only person looking for this.</p>
<p>The reason I'm asking is because I'm bored, and I've been thinking about taking a stab at writing this myself. I've just been hesitant to start, since I know there are a lot of people out there who are much smarter than me, and I figured there might be some reason why nobody has done it yet.</p>
| 2 | 2009-06-01T21:06:31Z | 940,483 | <p>SSHv1 was considered deprecated in 2001, so I assume nobody really wanted to put the effort into it. I'm not sure if there's even an rfc for SSH1, so getting the full protocol spec may require reading through old source code.</p>
<p>Since there are known vulnerabilities, it's not much better than telnet, which is almost universally supported on old and/or embedded devices.</p>
| 2 | 2009-06-02T16:25:55Z | [
"python",
"ssh"
] |
Why does "**" bind more tightly than negation? | 936,904 | <p>I was just bitten by the following scenario:</p>
<pre><code>>>> -1 ** 2
-1
</code></pre>
<p>Now, digging through the Python docs, <a href="http://docs.python.org/reference/expressions.html#the-power-operator">it's clear that this is intended behavior</a>, but <em>why?</em> I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.</p>
<p>Is there a reason it was done this way? Do other languages with power operators behave similarly?</p>
| 9 | 2009-06-01T21:33:07Z | 936,926 | <p>That behaviour is the same as in math formulas, so I am not sure what the problem is, or why it is counter-intuitive. Can you explain where have you seen something different? "**" always bind more than "-": -x^2 is not the same as (-x)^2</p>
<p>Just use (-1) ** 2, exactly as you'd do in math.</p>
| 22 | 2009-06-01T21:37:53Z | [
"python",
"order-of-operations"
] |
Why does "**" bind more tightly than negation? | 936,904 | <p>I was just bitten by the following scenario:</p>
<pre><code>>>> -1 ** 2
-1
</code></pre>
<p>Now, digging through the Python docs, <a href="http://docs.python.org/reference/expressions.html#the-power-operator">it's clear that this is intended behavior</a>, but <em>why?</em> I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.</p>
<p>Is there a reason it was done this way? Do other languages with power operators behave similarly?</p>
| 9 | 2009-06-01T21:33:07Z | 936,931 | <p>If I had to guess, it would be because having an exponentiation operator allows programmers to easily raise numbers to fractional powers. Negative numbers raised to fractional powers end up with an imaginary component (usually), so that can be avoided by binding ** more tightly than unary -. Most languages don't like imaginary numbers.</p>
<p>Ultimately, of course, it's just a convention - and to make your code readable by yourself and others down the line, you'll probably want to explicitly group your (-1) so no one else gets caught by the same trap :) Good luck!</p>
| 3 | 2009-06-01T21:39:32Z | [
"python",
"order-of-operations"
] |
Why does "**" bind more tightly than negation? | 936,904 | <p>I was just bitten by the following scenario:</p>
<pre><code>>>> -1 ** 2
-1
</code></pre>
<p>Now, digging through the Python docs, <a href="http://docs.python.org/reference/expressions.html#the-power-operator">it's clear that this is intended behavior</a>, but <em>why?</em> I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.</p>
<p>Is there a reason it was done this way? Do other languages with power operators behave similarly?</p>
| 9 | 2009-06-01T21:33:07Z | 936,949 | <p>Short answer: it's the standard way precedence works in math.</p>
<p>Let's say I want to evaluate the polynomial 3x**3 - x**2 + 5.</p>
<pre><code>def polynomial(x):
return 3*x**3 - x**2 + 5
</code></pre>
<p>It looks better than...</p>
<pre><code>def polynomial
return 3*x**3 - (x**2) + 5
</code></pre>
<p>And the first way is the way mathematicians do it. Other languages with exponentiation work the same way. Note that the negation operator also binds more loosely than multiplication, so</p>
<pre><code>-x*y === -(x*y)
</code></pre>
<p>Which is also the way they do it in math.</p>
| 4 | 2009-06-01T21:43:36Z | [
"python",
"order-of-operations"
] |
Why does "**" bind more tightly than negation? | 936,904 | <p>I was just bitten by the following scenario:</p>
<pre><code>>>> -1 ** 2
-1
</code></pre>
<p>Now, digging through the Python docs, <a href="http://docs.python.org/reference/expressions.html#the-power-operator">it's clear that this is intended behavior</a>, but <em>why?</em> I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.</p>
<p>Is there a reason it was done this way? Do other languages with power operators behave similarly?</p>
| 9 | 2009-06-01T21:33:07Z | 936,958 | <p>Ocaml doesn't do the same</p>
<pre><code># -12.0**2.0
;;
- : float = 144.
</code></pre>
<p>That's kind of weird...</p>
<pre><code># -12.0**0.5;;
- : float = nan
</code></pre>
<p>Look at that link though...
<a href="http://en.wikipedia.org/wiki/Order%5Fof%5Foperations" rel="nofollow">order of operations</a></p>
| -1 | 2009-06-01T21:44:37Z | [
"python",
"order-of-operations"
] |
Why does "**" bind more tightly than negation? | 936,904 | <p>I was just bitten by the following scenario:</p>
<pre><code>>>> -1 ** 2
-1
</code></pre>
<p>Now, digging through the Python docs, <a href="http://docs.python.org/reference/expressions.html#the-power-operator">it's clear that this is intended behavior</a>, but <em>why?</em> I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.</p>
<p>Is there a reason it was done this way? Do other languages with power operators behave similarly?</p>
| 9 | 2009-06-01T21:33:07Z | 936,971 | <p>It seems intuitive to me.</p>
<p>Fist, because it's consistent with mathematical notaiton: -2^2 = -4.</p>
<p>Second, the operator ** was widely introduced by FORTRAN long time ago. In FORTRAN, -2**2 is -4, as well. </p>
| 1 | 2009-06-01T21:48:41Z | [
"python",
"order-of-operations"
] |
BoundedSemaphore hangs in threads on KeyboardInterrupt | 936,933 | <p>If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely.</p>
<p>Code:</p>
<pre><code>import threading
import time
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
sema = threading.BoundedSemaphore(value=5)
threads = []
for x in xrange(100):
sema.acquire()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
threads.append(t)
</code></pre>
<p>Start this up and then ^C as it is running. It will hang and never exit.</p>
<pre><code>0 finished
3 finished
1 finished
2 finished
4 finished
^C5 finished
Traceback (most recent call last):
File "/tmp/proof.py", line 15, in <module>
sema.acquire()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 290, in acquire
self.__cond.wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 214, in wait
waiter.acquire()
KeyboardInterrupt
6 finished
7 finished
8 finished
9 finished
</code></pre>
<p>How can I get it to let the last few threads die natural deaths and then exit normally? (which it does if you don't try to interrupt it)</p>
| 2 | 2009-06-01T21:40:35Z | 937,345 | <p>You can use the signal module to set a flag that tells the main thread to stop processing:</p>
<pre><code>import threading
import time
import signal
import sys
sigint = False
def sighandler(num, frame):
global sigint
sigint = True
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
signal.signal(signal.SIGINT, sighandler)
sema = threading.BoundedSemaphore(value=5)
threads = []
for x in xrange(100):
sema.acquire()
if sigint:
sys.exit()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
t.join()
threads.append(t)
</code></pre>
| 2 | 2009-06-01T23:52:14Z | [
"python",
"multithreading"
] |
BoundedSemaphore hangs in threads on KeyboardInterrupt | 936,933 | <p>If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely.</p>
<p>Code:</p>
<pre><code>import threading
import time
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
sema = threading.BoundedSemaphore(value=5)
threads = []
for x in xrange(100):
sema.acquire()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
threads.append(t)
</code></pre>
<p>Start this up and then ^C as it is running. It will hang and never exit.</p>
<pre><code>0 finished
3 finished
1 finished
2 finished
4 finished
^C5 finished
Traceback (most recent call last):
File "/tmp/proof.py", line 15, in <module>
sema.acquire()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 290, in acquire
self.__cond.wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 214, in wait
waiter.acquire()
KeyboardInterrupt
6 finished
7 finished
8 finished
9 finished
</code></pre>
<p>How can I get it to let the last few threads die natural deaths and then exit normally? (which it does if you don't try to interrupt it)</p>
| 2 | 2009-06-01T21:40:35Z | 937,383 | <p>In this case, it looks like you might just want to use a thread pool to control the starting and stopping of your threads. You could use <a href="http://www.chrisarndt.de/projects/threadpool/" rel="nofollow">Chris Arndt's threadpool library</a> in a manner something like this:</p>
<pre><code>pool = ThreadPool(5)
try:
# enqueue 100 worker threads
pool.wait()
except KeyboardInterrupt, k:
pool.dismiss(5)
# the program will exit after all running threads are complete
</code></pre>
| 0 | 2009-06-02T00:09:46Z | [
"python",
"multithreading"
] |
BoundedSemaphore hangs in threads on KeyboardInterrupt | 936,933 | <p>If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely.</p>
<p>Code:</p>
<pre><code>import threading
import time
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
sema = threading.BoundedSemaphore(value=5)
threads = []
for x in xrange(100):
sema.acquire()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
threads.append(t)
</code></pre>
<p>Start this up and then ^C as it is running. It will hang and never exit.</p>
<pre><code>0 finished
3 finished
1 finished
2 finished
4 finished
^C5 finished
Traceback (most recent call last):
File "/tmp/proof.py", line 15, in <module>
sema.acquire()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 290, in acquire
self.__cond.wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 214, in wait
waiter.acquire()
KeyboardInterrupt
6 finished
7 finished
8 finished
9 finished
</code></pre>
<p>How can I get it to let the last few threads die natural deaths and then exit normally? (which it does if you don't try to interrupt it)</p>
| 2 | 2009-06-01T21:40:35Z | 18,344,591 | <p>In your original code you could also make the threads daemon threads. When you interrupt the script, the daemon threads all die as you expected.</p>
<pre><code> t = ...
t.setDaemon(True)
t.start()
</code></pre>
| 0 | 2013-08-20T20:42:05Z | [
"python",
"multithreading"
] |
BoundedSemaphore hangs in threads on KeyboardInterrupt | 936,933 | <p>If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely.</p>
<p>Code:</p>
<pre><code>import threading
import time
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
sema = threading.BoundedSemaphore(value=5)
threads = []
for x in xrange(100):
sema.acquire()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
threads.append(t)
</code></pre>
<p>Start this up and then ^C as it is running. It will hang and never exit.</p>
<pre><code>0 finished
3 finished
1 finished
2 finished
4 finished
^C5 finished
Traceback (most recent call last):
File "/tmp/proof.py", line 15, in <module>
sema.acquire()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 290, in acquire
self.__cond.wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 214, in wait
waiter.acquire()
KeyboardInterrupt
6 finished
7 finished
8 finished
9 finished
</code></pre>
<p>How can I get it to let the last few threads die natural deaths and then exit normally? (which it does if you don't try to interrupt it)</p>
| 2 | 2009-06-01T21:40:35Z | 23,964,243 | <p>This is bug <a href="http://bugs.python.org/issue11714" rel="nofollow">#11714</a>, and has been <a href="http://hg.python.org/cpython/rev/2253b8a18bbf" rel="nofollow">patched</a> in newer versions of python.</p>
<p>If you are using an older python, you could copy the the version of <code>Semaphore</code> found in that patch into your project and use it instead of relying on the buggy version in <code>threading</code></p>
| 0 | 2014-05-30T22:25:45Z | [
"python",
"multithreading"
] |
BoundedSemaphore hangs in threads on KeyboardInterrupt | 936,933 | <p>If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely.</p>
<p>Code:</p>
<pre><code>import threading
import time
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
sema = threading.BoundedSemaphore(value=5)
threads = []
for x in xrange(100):
sema.acquire()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
threads.append(t)
</code></pre>
<p>Start this up and then ^C as it is running. It will hang and never exit.</p>
<pre><code>0 finished
3 finished
1 finished
2 finished
4 finished
^C5 finished
Traceback (most recent call last):
File "/tmp/proof.py", line 15, in <module>
sema.acquire()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 290, in acquire
self.__cond.wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 214, in wait
waiter.acquire()
KeyboardInterrupt
6 finished
7 finished
8 finished
9 finished
</code></pre>
<p>How can I get it to let the last few threads die natural deaths and then exit normally? (which it does if you don't try to interrupt it)</p>
| 2 | 2009-06-01T21:40:35Z | 26,026,791 | <pre><code># importing modules
import threading
import time
# defining our worker and pass a counter and the semaphore to it
def worker(i, sema):
time.sleep(2)
print i, "finished"
# releasing the thread increments the sema value
sema.release()
# creating the semaphore object
sema = threading.BoundedSemaphore(value=5)
# a list to store the created threads
threads = []
for x in xrange(100):
try:
sema.acquire()
t = threading.Thread(target=worker, args=(x, sema))
t.start()
threads.append(t)
# exit once the user hit CTRL+c
# or you can make the thead as daemon t.setdaemon(True)
except KeyboardInterrupt:
exit()
</code></pre>
| 0 | 2014-09-24T21:25:42Z | [
"python",
"multithreading"
] |
Python recursion and return statements | 937,000 | <p>I'm fairly new to Python and recursive functions as a whole, so pardon my ignorance.</p>
<p>I am trying to implement a binary search tree in Python and have the following insert method (taken out of a class):</p>
<pre><code>def insert(self, key, root=None):
'''Inserts a node in the tree'''
if root == None:
root = self.root
if root.key == None:
self._update(root, key)
return 0
else:
tmp = root
if key > tmp.key: # we work with the right subtree
self.insert(key, root=tmp.right)
elif key < tmp.key: # we work with the left subtree
self.insert(key, root=tmp.left)
else: # key already exists
return 0
</code></pre>
<p>I'm not sure if this is legible, but it traverses the tree until it gets to a None value and updates the node with the key to insert.</p>
<p>Now, the method works nicely and correctly creates a BST from scratch. But there's a problem with the return statements, as it only returns 0 if there is no recursion performed.</p>
<pre><code>>>> bst.insert(10)
0
>>> bst.insert(15)
>>> bst.root.right.key
15
>>>
</code></pre>
<p>"Inserting" the root key again returns 0 (from line 15) the way it should.</p>
<pre><code>>>> bst.insert(10)
0
</code></pre>
<p>I can't figure out why this happens. If I put a print statement in line 6, it executes correctly, yet it just won't return anything past the first insertion. Why is this? (I'm pretty sure I'm missing some basic information regarding Python and recursion)</p>
<p>Thanks for your help,</p>
<p>Ivan</p>
<p>P.S.: I've read that recursion is not the best way to implement a BST, so I'll look into other solutions, but I'd like to know the answer to this before moving on.</p>
| 15 | 2009-06-01T21:55:29Z | 937,011 | <p>On your recursive lines, you do not return anything. If you want it to return 0, you should replace them with lines like:</p>
<pre><code>return self.insert(key, root=tmp.left)
</code></pre>
<p>instead of just</p>
<pre><code>self.insert(key, root=tmp.left)
</code></pre>
| 23 | 2009-06-01T21:58:31Z | [
"python",
"recursion"
] |
Python recursion and return statements | 937,000 | <p>I'm fairly new to Python and recursive functions as a whole, so pardon my ignorance.</p>
<p>I am trying to implement a binary search tree in Python and have the following insert method (taken out of a class):</p>
<pre><code>def insert(self, key, root=None):
'''Inserts a node in the tree'''
if root == None:
root = self.root
if root.key == None:
self._update(root, key)
return 0
else:
tmp = root
if key > tmp.key: # we work with the right subtree
self.insert(key, root=tmp.right)
elif key < tmp.key: # we work with the left subtree
self.insert(key, root=tmp.left)
else: # key already exists
return 0
</code></pre>
<p>I'm not sure if this is legible, but it traverses the tree until it gets to a None value and updates the node with the key to insert.</p>
<p>Now, the method works nicely and correctly creates a BST from scratch. But there's a problem with the return statements, as it only returns 0 if there is no recursion performed.</p>
<pre><code>>>> bst.insert(10)
0
>>> bst.insert(15)
>>> bst.root.right.key
15
>>>
</code></pre>
<p>"Inserting" the root key again returns 0 (from line 15) the way it should.</p>
<pre><code>>>> bst.insert(10)
0
</code></pre>
<p>I can't figure out why this happens. If I put a print statement in line 6, it executes correctly, yet it just won't return anything past the first insertion. Why is this? (I'm pretty sure I'm missing some basic information regarding Python and recursion)</p>
<p>Thanks for your help,</p>
<p>Ivan</p>
<p>P.S.: I've read that recursion is not the best way to implement a BST, so I'll look into other solutions, but I'd like to know the answer to this before moving on.</p>
| 15 | 2009-06-01T21:55:29Z | 937,057 | <p>You are inside a function and want to return a value, what do you do? You write</p>
<pre><code>def function():
return value
</code></pre>
<p>In your case you want to return the value returned by a function call, so you have to do.</p>
<pre><code>def function():
return another_function()
</code></pre>
<p>However you do</p>
<pre><code>def function():
another_function()
</code></pre>
<p>Why do you think that should work? Of course you use recursion but in such a case you should remember the Zen of Python which simply says:</p>
<blockquote>
<p>Special cases aren't special enough to break the rules.</p>
</blockquote>
| 18 | 2009-06-01T22:09:20Z | [
"python",
"recursion"
] |
Keep code from running during syncdb | 937,316 | <p>I have some code that throws causes syncdb to throw an error (because it tries to access the model before the tables are created).</p>
<p>Is there a way to keep the code from running on syncdb? something like:</p>
<pre><code>if not syncdb:
run_some_code()
</code></pre>
<p>Thanks :)</p>
<p><del><strong>edit</strong>: PS - I thought about using the post_init signal... for the code that accesses the db, is that a good idea?</del></p>
<h2>More info</h2>
<p>Here is some more info as requested :)</p>
<p>I've run into this a couple times, for instance... I was hacking on django-cron and determined it necessary to make sure there are not existing jobs when you load django (because it searches all the installed apps for jobs and adds them on load anyway).</p>
<p>So I added the following code to the top of the <code>__init__.py</code> file:</p>
<pre><code>import sqlite3
try:
# Delete all the old jobs from the database so they don't interfere with this instance of django
oldJobs = models.Job.objects.all()
for oldJob in oldJobs:
oldJob.delete()
except sqlite3.OperationalError:
# When you do syncdb for the first time, the table isn't
# there yet and throws a nasty error... until now
pass
</code></pre>
<p>For obvious reasons this is crap. it's tied to sqlite and I'm there are better places to put this code (this is just how I happened upon the issue) but it works.</p>
<p>As you can see the error you get is Operational Error (in sqlite) and the stack trace says something along the lines of "table django_cron_job not found"</p>
<h1>Solution</h1>
<p>In the end, the goal was to <strong>run some code before any pages were loaded</strong>.</p>
<p>This can be accomplished by executing it in the urls.py file, since it has to be imported before a page can be served (obviously).</p>
<p>And I was able to remove that ugly try/except block :) Thank god (and S. Lott)</p>
| 1 | 2009-06-01T23:36:12Z | 937,559 | <p>Code that tries to access the models before they're created can pretty much exist only at the module level; it would have to be executable code run when the module is imported, as your example indicates. This is, as you've guessed, the reason by syncdb fails. It tries to import the module, but the act of importing the module causes application-level code to execute; a "side-effect" if you will.</p>
<p>The desire to avoid module imports that cause side-effects is so strong in Python that the <code>if __name__ == '__main__':</code> convention for executable python scripts has become commonplace. When just loading a code library causes an application to start executing, headaches ensue :-)</p>
<p>For Django apps, this becomes more than a headache. Consider the effect of having <code>oldJob.delete()</code> executed every time the module is imported. It may seem like it's executing only once when you run with the Django development server, but in a production environment it will get executed quite often. If you use Apache, for example, Apache will frequently fire up several child processes waiting around to handle requests. As a long-running server progresses, your Django app will get bootstrapped every time a handler is forked for your web server, meaning that the module will be imported and <code>delete()</code> will be called several times, often unpredictably. A signal won't help, unfortunately, as the signal could be fired every time an Apache process is initialized as well.</p>
<p>It isn't, btw, just a webserver that could cause your code to execute inadvertently. If you use tools like epydoc, for example they will import your code to generate API documentation. This in turn would cause your application logic to start executing, which is obviously an undesired side-effect of just running a documentation parser. </p>
<p>For this reason, cleanup code like this is either best handled by a cron job, which looks for stale jobs on a periodic basis and cleans up the DB. This custom script can also be run manually, or by any process (for example during a deployment, or as part of your unit test <code>setUp()</code> function to ensure a clean test run). No matter how you do it, the important point is that code like this should always be executed <em>explicitly</em>, rather than <em>implicitly</em> as a result of opening the source file.</p>
<p>I hope that helps. I know it doesn't provide a way to determine if syncdb is running, but the syncdb issue will magically vanish if you design your Django app with production deployment in mind.</p>
| 2 | 2009-06-02T01:21:25Z | [
"python",
"django",
"django-models",
"django-syncdb",
"syncdb"
] |
Keep code from running during syncdb | 937,316 | <p>I have some code that throws causes syncdb to throw an error (because it tries to access the model before the tables are created).</p>
<p>Is there a way to keep the code from running on syncdb? something like:</p>
<pre><code>if not syncdb:
run_some_code()
</code></pre>
<p>Thanks :)</p>
<p><del><strong>edit</strong>: PS - I thought about using the post_init signal... for the code that accesses the db, is that a good idea?</del></p>
<h2>More info</h2>
<p>Here is some more info as requested :)</p>
<p>I've run into this a couple times, for instance... I was hacking on django-cron and determined it necessary to make sure there are not existing jobs when you load django (because it searches all the installed apps for jobs and adds them on load anyway).</p>
<p>So I added the following code to the top of the <code>__init__.py</code> file:</p>
<pre><code>import sqlite3
try:
# Delete all the old jobs from the database so they don't interfere with this instance of django
oldJobs = models.Job.objects.all()
for oldJob in oldJobs:
oldJob.delete()
except sqlite3.OperationalError:
# When you do syncdb for the first time, the table isn't
# there yet and throws a nasty error... until now
pass
</code></pre>
<p>For obvious reasons this is crap. it's tied to sqlite and I'm there are better places to put this code (this is just how I happened upon the issue) but it works.</p>
<p>As you can see the error you get is Operational Error (in sqlite) and the stack trace says something along the lines of "table django_cron_job not found"</p>
<h1>Solution</h1>
<p>In the end, the goal was to <strong>run some code before any pages were loaded</strong>.</p>
<p>This can be accomplished by executing it in the urls.py file, since it has to be imported before a page can be served (obviously).</p>
<p>And I was able to remove that ugly try/except block :) Thank god (and S. Lott)</p>
| 1 | 2009-06-01T23:36:12Z | 937,602 | <p>"edit: PS - I thought about using the post_init signal... for the code that accesses the db, is that a good idea?"</p>
<p>Never.</p>
<p>If you have code that's accessing the model before the tables are created, you have big, big problems. You're probably doing something seriously wrong.</p>
<p>Normally, you run syncdb approximately once. The database is created. And your web application uses the database.</p>
<p>Sometimes, you made a design change, drop and recreate the database. And then your web application uses that database for a long time.</p>
<p>You (generally) don't need code in an <code>__init__.py</code> module. You should (almost) never have executable code that does real work in an <code>__init__.py</code> module. It's very, very rare, and inappropriate for Django.</p>
<p>I'm not sure why you're messing with <code>__init__.py</code> when <a href="http://code.google.com/p/django-cron/" rel="nofollow">Django Cron</a> says that you make your scheduling arrangements in <code>urls.py</code>.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>Clearing records is one thing.</p>
<p>Messing around with <code>__init__.py</code> and Django-cron's <code>base.py</code> are clearly completely wrong ways to do this. If it's that complicated, you're doing it wrong.</p>
<p>It's impossible to tell what you're trying to do, but it should be trivial.</p>
<p>Your <code>urls.py</code> can only run after syncdb and after all of the ORM material has been configured and bound correctly.</p>
<p>Your <code>urls.py</code> could, for example, delete some rows and then add some rows to a table. At this point, all syncdb issues are out of the way.</p>
<p>Why don't you have your logic in <code>urls.py</code>?</p>
| 4 | 2009-06-02T01:40:02Z | [
"python",
"django",
"django-models",
"django-syncdb",
"syncdb"
] |
Can you pass a dictionary when replacing strings in Python? | 937,697 | <p>In PHP, you have <code>preg_replace($patterns, $replacements, $string)</code>, where you can make all your substitutions at once by passing in an array of patterns and replacements.</p>
<p>What is the equivalent in Python?</p>
<p>I noticed that the string and re functions <code>replace()</code> and <code>sub()</code> don't take dictionaries...</p>
<p>Edited to clarify based on a comment by rick:
the idea is to have a dict with keys to be taken as regular expression patterns, such as <code>'\d+S'</code>, and (hopefully) constant string values (hopefully w/o backreferences). Now editing my answer accordingly (i.e. to answer the actual question).</p>
| 6 | 2009-06-02T02:37:59Z | 937,739 | <p>closest is probably:</p>
<pre><code>somere.sub(lambda m: replacements[m.group()], text)
</code></pre>
<p>for example:</p>
<pre><code>>>> za = re.compile('z\w')
>>> za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu')
'fa BLU BLA bu'
</code></pre>
<p>with a <code>.get</code> instead of <code>[]</code>-indexing if you want to supply a default for matches that are missing in <code>replacements</code>.</p>
<p>Edit: what rick really wants is to have a dict with keys to be taken as regular expression patterns, such as <code>'\d+S'</code>, and (hopefully) constant string values (hopefully w/o backreferences). The cookbook recipe can be adapted for this purpose:</p>
<pre><code>def dict_sub(d, text):
""" Replace in 'text' non-overlapping occurences of REs whose patterns are keys
in dictionary 'd' by corresponding values (which must be constant strings: may
have named backreferences but not numeric ones). The keys must not contain
anonymous matching-groups.
Returns the new string."""
# Create a regular expression from the dictionary keys
regex = re.compile("|".join("(%s)" % k for k in d))
# Facilitate lookup from group number to value
lookup = dict((i+1, v) for i, v in enumerate(d.itervalues()))
# For each match, find which group matched and expand its value
return regex.sub(lambda mo: mo.expand(lookup[mo.lastindex]), text)
</code></pre>
<p>Example use:</p>
<pre><code> d={'\d+S': 'wot', '\d+T': 'zap'}
t='And 23S, and 45T, and 66T but always 029S!'
print dict_sub(d, t)
</code></pre>
<p>emits:</p>
<pre><code>And wot, and zap, and zap but always wot!
</code></pre>
<p>You could avoid building <code>lookup</code> and just use <code>mo.expand(d.values()[mo.lastindex-1])</code>, but that might be a tad slow if <code>d</code> is very large and there are many matches (sorry, haven't precisely measured/benchmarked both approaches, so this is just a guess;-).</p>
| 10 | 2009-06-02T02:56:43Z | [
"php",
"python",
"regex",
"string"
] |
Can you pass a dictionary when replacing strings in Python? | 937,697 | <p>In PHP, you have <code>preg_replace($patterns, $replacements, $string)</code>, where you can make all your substitutions at once by passing in an array of patterns and replacements.</p>
<p>What is the equivalent in Python?</p>
<p>I noticed that the string and re functions <code>replace()</code> and <code>sub()</code> don't take dictionaries...</p>
<p>Edited to clarify based on a comment by rick:
the idea is to have a dict with keys to be taken as regular expression patterns, such as <code>'\d+S'</code>, and (hopefully) constant string values (hopefully w/o backreferences). Now editing my answer accordingly (i.e. to answer the actual question).</p>
| 6 | 2009-06-02T02:37:59Z | 937,868 | <p>It's easy enough to do this:</p>
<pre><code>replacements = dict(hello='goodbye', good='bad')
s = "hello, good morning";
for old, new in replacements.items():
s = s.replace(old, new)
</code></pre>
<p>You will find many places where PHP functions accept an array of values and there is no direct Python equivalent, but it is much easier to work with arrays (lists) in Python so it is less of an issue.</p>
| -1 | 2009-06-02T04:11:41Z | [
"php",
"python",
"regex",
"string"
] |
Can you pass a dictionary when replacing strings in Python? | 937,697 | <p>In PHP, you have <code>preg_replace($patterns, $replacements, $string)</code>, where you can make all your substitutions at once by passing in an array of patterns and replacements.</p>
<p>What is the equivalent in Python?</p>
<p>I noticed that the string and re functions <code>replace()</code> and <code>sub()</code> don't take dictionaries...</p>
<p>Edited to clarify based on a comment by rick:
the idea is to have a dict with keys to be taken as regular expression patterns, such as <code>'\d+S'</code>, and (hopefully) constant string values (hopefully w/o backreferences). Now editing my answer accordingly (i.e. to answer the actual question).</p>
| 6 | 2009-06-02T02:37:59Z | 6,439,505 | <p>Here is a simple way using reduce</p>
<pre><code>mynewstring=reduce(lambda a,(b,c): a.replace(b, c), mydict.items(), mystring)
</code></pre>
| -1 | 2011-06-22T12:05:15Z | [
"php",
"python",
"regex",
"string"
] |
Can you pass a dictionary when replacing strings in Python? | 937,697 | <p>In PHP, you have <code>preg_replace($patterns, $replacements, $string)</code>, where you can make all your substitutions at once by passing in an array of patterns and replacements.</p>
<p>What is the equivalent in Python?</p>
<p>I noticed that the string and re functions <code>replace()</code> and <code>sub()</code> don't take dictionaries...</p>
<p>Edited to clarify based on a comment by rick:
the idea is to have a dict with keys to be taken as regular expression patterns, such as <code>'\d+S'</code>, and (hopefully) constant string values (hopefully w/o backreferences). Now editing my answer accordingly (i.e. to answer the actual question).</p>
| 6 | 2009-06-02T02:37:59Z | 11,558,364 | <p>You can pass the dictionary while replacing string in python.
Consider the above example:</p>
<pre><code>replacement = {'hello' : 'goodbye', 'good' : 'bad' }
</code></pre>
<p>you have write the string in this format</p>
<pre><code>s = "%(hello)s, %(good)s morning"
changed_s = s%replacement
</code></pre>
<p>the output of changed_s will be </p>
<pre><code>"goodbye, bad morning"
</code></pre>
| -2 | 2012-07-19T10:00:49Z | [
"php",
"python",
"regex",
"string"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 938,162 | <p>If you are using the development version of Django, you can implement the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield%5Ffor%5Fforeignkey" rel="nofollow"><code>formfield_for_foreignkey()</code></a> method on your <code>AdminModel</code> to set a default value.</p>
| 4 | 2009-06-02T06:28:02Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 938,205 | <p>See this <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">blog post</a>. Your question isn't clear as to whether you want the user to be able to override the default selection - if you do, then this might not be of much use.</p>
<p>There's also this <a href="http://www.b-list.org/weblog/2006/nov/02/django-tips-auto-populated-fields/">blog post</a>, which talks about auto-populating foreign key fields, but again, this is talking about non-overridable methods for setting the value of a foreign key field.</p>
| 5 | 2009-06-02T06:43:40Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 10,044,623 | <p>Just add the user id to the default parameter. In our case, we want to get request.user as default user, then we use simply</p>
<p><code>created_by = models.ForeignKey(User, default=request.user.pk)</code></p>
| -8 | 2012-04-06T14:05:52Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 13,562,197 | <pre><code>class Foo(models.Model):
a = models.CharField(max_length=42)
class Bar(models.Model):
b = models.CharField(max_length=42)
a = models.ForeignKey(Foo, default=lambda: Foo.objects.get(id=1) )
</code></pre>
| 23 | 2012-11-26T09:46:25Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 29,203,265 | <p>As for me, for Django 1.7 its work, just pk:</p>
<p><code>category = models.ForeignKey(Category, editable=False, default=1)</code></p>
<p>but remember, that migration looks like</p>
<pre><code>migrations.AlterField(
model_name='item',
name='category',
field=models.ForeignKey(default=1, editable=False, to='item.Category'),
preserve_default=True,
),
</code></pre>
<p>so, i don't think it's to be working with dynamic user pk.</p>
| 1 | 2015-03-23T04:26:23Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 32,868,301 | <pre><code>class table1(models.Model):
id = models.AutoField(primary_key=True)
agentname = models.CharField(max_length=20)
class table1(models.Model):
id = models.AutoField(primary_key=True)
lastname = models.CharField(max_length=20)
table1 = models.ForeignKey(Property)
</code></pre>
| -1 | 2015-09-30T14:09:23Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 35,822,874 | <pre><code>def get_user_default_id():
return 1
created_by = models.ForeignKey(User, default=get_user_default_id)
</code></pre>
| 0 | 2016-03-06T03:46:27Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 35,927,879 | <p>Here's a solution that will work in Django 1.7.
Instead of providing the default at the field definition, set it as null-able, but overide the 'save' function to fill it on the first time (while it's null):</p>
<pre><code>class Foo(models.Model):
a = models.CharField(max_length=42)
class Bar(models.Model):
b = models.CharField(max_length=42)
a = models.ForeignKey(Foo, null=True)
def save(self, *args, **kwargs):
if self.a is None: # Set default reference
self.a = Foo.objects.get(id=1)
super(Bar, self).save(*args, **kwargs)
</code></pre>
| 3 | 2016-03-10T21:41:57Z | [
"python",
"django-models",
"django-admin"
] |
How do you specify a default for a Django ForeignKey Model or AdminModel field? | 937,954 | <p>How can I set a default value on a ForeignKey field in a django Model or AdminModel?</p>
<p>Something like this (but of course this doesn't work)...</p>
<pre><code>created_by = models.ForeignKey(User, default=request.user)
</code></pre>
<p>I know I can 'trick' it in the view, but in terms of the AdminModel it doesn't seem possible.</p>
| 14 | 2009-06-02T04:56:29Z | 39,676,455 | <p>I've done this similarly to @o_c, but I'd rather use <code>get_or_create</code> than just plain <code>pk</code>.</p>
<pre><code>class UserSettings(models.Model):
name = models.CharField(max_length=64, unique=True)
# ... some other fields
@staticmethod
def get_default_user_settings():
user_settings, created = UserSettings.objects.get_or_create(
name = 'Default settings'
)
return user_settings
class SiteUser(...):
# ... some other fields
user_settings = models.ForeignKey(
to=UserSettings,
on_delete=models.SET_NULL,
null=True
)
def save(self, *args, **kwargs):
if self.user_settings is None:
self.user_settings = UserSettings.get_default_params()
super(SiteUser, self).save(*args, **kwargs)
</code></pre>
| 0 | 2016-09-24T12:41:06Z | [
"python",
"django-models",
"django-admin"
] |
Python Tkinter Tk/Tcl usage Problem | 937,979 | <p>I am using Tcl from Python Tkinter Module like below </p>
<pre><code>from Tkinter import *
Tcl = Tcl().eval
Tcl("info patchlevel")
'8.3.5'
</code></pre>
<p>You can see Tcl version 8.3 is selected by python.</p>
<p>But i also have tcl8.4 in my system.
Now,how do i make python select tcl8.4 in Tkinter module.</p>
<p>Tcl8.3 does not have Expect package,so i can not use Expect package in Python Tcl/Tk.</p>
<p>Thanks</p>
| 1 | 2009-06-02T05:10:06Z | 938,099 | <p>I think the version of Tcl/Tk is used by python is determined at compiling time. So you need to look at the code, recompile python against the version of Tcl/Tk you want to use. Maybe recompiling the _tkinter.so library is enough too, since it's loaded dynamically.</p>
| 2 | 2009-06-02T06:09:35Z | [
"python",
"tkinter",
"tcl",
"expect"
] |
Recursive Relationship with Google App Engine and BigTable | 938,035 | <p>In a classic relational database, I have the following table:</p>
<pre><code>CREATE TABLE Person(
Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
MotherId int NOT NULL REFERENCES Person(Id),
FatherId int NOT NULL REFERENCES Person(Id),
FirstName nvarchar(255))
</code></pre>
<p>I am trying to convert this table into a Google App Engine table. My issue is with the fields MotherId and FatherId. I tried the code below, but no chance. Python says that it doesn't know the object type Person.</p>
<pre><code>class Person(db.Model):
mother = db.ReferenceProperty(Person)
father = db.ReferenceProperty(Person)
firstName = db.StringProperty()
</code></pre>
<p>Does someone know how we can model a recursive relationship in a Google App Engine table? How could I work around the limitation of App Engine?</p>
<p><strong>UPDATE</strong>
I want to expand the problem a little bit... What if I wanted to add a collection of children?</p>
<pre><code>children = db.SelfReferenceProperty(collection_name='children_set')
dad.children.append(childrenOne)
</code></pre>
<p>I tried this and it doesn't work. Any idea what I am doing wrong?</p>
<p>Thanks!</p>
| 5 | 2009-06-02T05:38:04Z | 938,106 | <p>I think that you want SelfReferenceProperty here</p>
<pre><code>class Person(db.Model):
mother = db.SelfReferenceProperty(collection_name='mother_set')
father = db.SelfReferenceProperty(collection_name='father_set')
firstName = db.StringProperty()
</code></pre>
<p>Alternatively, you can put the Mother and Father relations in separate classes.</p>
| 10 | 2009-06-02T06:12:46Z | [
"python",
"database-design",
"google-app-engine",
"bigtable"
] |
How to match a string of a certain length with a regex | 938,065 | <p>For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found <a href="http://www.bittorrent.org/beps/bep%5F0003.html" rel="nofollow">here</a>. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows:</p>
<pre><code>8:a string => "a string"
i1234e => 1234
l1:a1:be => ['a', 'b']
d1:a1:b3:one3:twoe => {'a':'b', 'one':two}
</code></pre>
<p>The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is:</p>
<pre><code>(?P<length>\d+):(?P<contents>.{\1})
</code></pre>
<p>However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?</p>
| 4 | 2009-06-02T05:55:06Z | 938,158 | <p>You can do it if you parse the string twice. Apply the first regex to get the length. Concatenate the length in your second regex to form a valid expression.</p>
<p>Not sure how that can be done in python, but a sample in C# would be:</p>
<pre><code>string regex = "^[A-Za-z0-9_]{1," + length + "}$"
</code></pre>
<p>To match 1 to length no of chars which can be alpanumeric or _ where length is determined from a previous regex that retrieves only the length.</p>
<p>Hope this helps :)</p>
| 2 | 2009-06-02T06:27:42Z | [
"python",
"regex"
] |
How to match a string of a certain length with a regex | 938,065 | <p>For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found <a href="http://www.bittorrent.org/beps/bep%5F0003.html" rel="nofollow">here</a>. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows:</p>
<pre><code>8:a string => "a string"
i1234e => 1234
l1:a1:be => ['a', 'b']
d1:a1:b3:one3:twoe => {'a':'b', 'one':two}
</code></pre>
<p>The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is:</p>
<pre><code>(?P<length>\d+):(?P<contents>.{\1})
</code></pre>
<p>However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?</p>
| 4 | 2009-06-02T05:55:06Z | 938,161 | <p>Any parser you use for this is going to need to be stateful (i.e. remember stuff), and regexes are, by and large, not stateful. They're the wrong tool for this job.</p>
<p>If those are the only data types you have to worry about, I think I'd just write custom parsers for each data type, passing control to the appropriate parser after reading the first character.</p>
<p><strike>I'd actually implement one now, but it's late.</strike></p>
<p><strong>Alright I decided to write an implementation:</strong></p>
<pre><code>from StringIO import StringIO
import string
inputs = ["10:a stringly",
"i1234e" ,
"l1:a1:be",
"d1:a1:b3:one3:twoe"]
# Constants
DICT_TYPE = 'd'
LIST_TYPE = 'l'
INT_TYPE = 'i'
TOKEN_EOF = ''
TOKEN_END = 'e'
COLON = ':'
class BadTypeIndicatorException(Exception):pass
def read_int(stream):
s = ""
while True:
ch = stream.read(1)
if ch not in [TOKEN_EOF, TOKEN_END, COLON]:
s += ch
else:
break
return s
def tokenize(stream):
s = ""
while True:
ch = stream.read(1)
if ch == TOKEN_END or ch == TOKEN_EOF:
return
if ch == COLON:
length = int(s)
yield stream.read(length)
s = ""
else:
s += ch
def parse(stream):
TYPE = stream.read(1)
if TYPE in string.digits:
length = int( TYPE + read_int(stream) )
return stream.read(length)
elif TYPE is INT_TYPE:
return int( read_int(stream) )
elif TYPE is LIST_TYPE:
return list(tokenize(stream))
elif TYPE is DICT_TYPE:
tokens = list(tokenize(stream))
return dict(zip(tokens[0::2], tokens[1::2]))
else:
raise BadTypeIndicatorException
for input in inputs:
stream = StringIO(input)
print parse(stream)
</code></pre>
| 8 | 2009-06-02T06:27:52Z | [
"python",
"regex"
] |
How to match a string of a certain length with a regex | 938,065 | <p>For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found <a href="http://www.bittorrent.org/beps/bep%5F0003.html" rel="nofollow">here</a>. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows:</p>
<pre><code>8:a string => "a string"
i1234e => 1234
l1:a1:be => ['a', 'b']
d1:a1:b3:one3:twoe => {'a':'b', 'one':two}
</code></pre>
<p>The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is:</p>
<pre><code>(?P<length>\d+):(?P<contents>.{\1})
</code></pre>
<p>However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?</p>
| 4 | 2009-06-02T05:55:06Z | 938,221 | <p>You are using the wrong tool for the job... This requires some sort of state keeping, and generally speaking, regular expressions are stateless.</p>
<p><hr /></p>
<p>An example implementation of bdecoding (and bencoding) in PERL that I did can be found <a href="http://perlmonks.com/?node%5Fid=461506" rel="nofollow">here</a>.</p>
<p>An explanation of how that function works (since I never did get to comment it [oops]):</p>
<p>Basically what you need to do is setup a recursive function. This function takes a string reference (so it can be modified) and returns "something" (the nature of this means it could be an array, a hashtable, an int, or a string).</p>
<p>The function itself just checks the first character in the string and decides what to do based of that:</p>
<ul>
<li>If it is an <code>i</code>, then parse out all the text between the <strong>i</strong> and the first <strong>e</strong>, and try to parse it as an int according to the rules of what is allowed.</li>
<li>If it is a digit, then read all the digits up to <strong>:</strong>, then read that many characters off the string.</li>
</ul>
<p>Lists and dictionaries are where things start to get interesting... if there is an <strong>l</strong> or <strong>d</strong> as the first character, then you need to strip off the <code>l</code>/<code>d</code>, then pass the current string back into the function, so that it can start parsing elements in the list or dictionary. Then just store the returned values in the appropriate places in an appropriate structure till you hit an <strong><code>e</code></strong>, and return the structure you're left with.</p>
<p>Remember, the function as I implemented it was DESTRUCTIVE. The string passed in is empty when the function returns due to it being passed by reference, or more accurately, it will be devoid of anything it parsed and returned (which is why it can be used recursively: anything it doesn't process is left untouched). In most cases of the initial call though, this should process everything unless you've been doing something odd, so the above holds.</p>
| 1 | 2009-06-02T06:51:32Z | [
"python",
"regex"
] |
How to match a string of a certain length with a regex | 938,065 | <p>For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found <a href="http://www.bittorrent.org/beps/bep%5F0003.html" rel="nofollow">here</a>. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows:</p>
<pre><code>8:a string => "a string"
i1234e => 1234
l1:a1:be => ['a', 'b']
d1:a1:b3:one3:twoe => {'a':'b', 'one':two}
</code></pre>
<p>The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is:</p>
<pre><code>(?P<length>\d+):(?P<contents>.{\1})
</code></pre>
<p>However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?</p>
| 4 | 2009-06-02T05:55:06Z | 938,226 | <p>You'll want to do this in two steps. Regular expressions are actually a little overkill for such simple parsing problems as this. Here's how I'd do it:</p>
<pre><code>def read_string(stream):
pos = stream.index(':')
length = int(stream[0:pos])
string = stream[pos+1:pos+1+length]
return string, stream[pos+1+length:]
</code></pre>
<p>It's a functional-style way of parsing, it returns the value parsed and the rest of the stream.</p>
<p>For lists, maybe:</p>
<pre><code>def read_list(stream):
stream = stream[1:]
result = []
while stream[0] != 'e':
obj, stream = read_object(stream)
result.append(obj)
stream = stream[1:]
return result
</code></pre>
<p>And then you'd define a read_object that checks the first character of the stream and dispatches appropriately.</p>
| 2 | 2009-06-02T06:52:50Z | [
"python",
"regex"
] |
How to match a string of a certain length with a regex | 938,065 | <p>For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found <a href="http://www.bittorrent.org/beps/bep%5F0003.html" rel="nofollow">here</a>. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows:</p>
<pre><code>8:a string => "a string"
i1234e => 1234
l1:a1:be => ['a', 'b']
d1:a1:b3:one3:twoe => {'a':'b', 'one':two}
</code></pre>
<p>The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including <a href="http://pyparsing.wikispaces.com/" rel="nofollow">PyParsing</a> and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is:</p>
<pre><code>(?P<length>\d+):(?P<contents>.{\1})
</code></pre>
<p>However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?</p>
| 4 | 2009-06-02T05:55:06Z | 939,254 | <p>Pseudo-code, without syntax checks:</p>
<pre><code>define read-integer (stream):
let number 0, sign 1:
if string-equal ('-', (c <- read-char (stream))):
sign <- -1
else:
number <- parse-integer (c)
while number? (c <- read-char (stream)):
number <- (number * 10) + parse-integer (c)
return sign * number
define bdecode-string (stream):
let count read-integer (stream):
return read-n-chars (stream, count)
define bdecode-integer (stream):
ignore read-char (stream)
return read-integer (stream)
define bdecode-list (stream):
ignore read-char (stream)
let list []:
while not string-equal ('e', peek-char (stream)):
append (list, bdecode (stream))
return list
define bdecode-dictionary (stream):
let list bdecode-list stream:
return dictionarify (list)
define bdecode (stream):
case peek-char (stream):
number? => bdecode-string (stream)
'i' => bdecode-integer (stream)
'l' => bdecode-list (stream)
'd' => bdecode-dictionary (stream)
</code></pre>
| 1 | 2009-06-02T12:32:02Z | [
"python",
"regex"
] |
Install CherryPy on Linux hosting provider without command line access | 938,185 | <p>I have a linux based web hosting provider (fatcow.com) that doesn't give any command line access and won't run the setup script for CherryPy (python web server) for me.</p>
<p>Is there any way to run get around this limitation so that I have a working install of CherryPy?</p>
<p>This might be more or a serverfault.com question, but maybe someone here has dealt with this before.</p>
| 0 | 2009-06-02T06:34:46Z | 938,199 | <p>If CherryPy is pure Python, then you may be able to simply put the <code>cherrypy</code> folder in the same place your project resides. This will enable you to <code>import</code> the necessary things from CherryPy without needing to copy it to the official install directory. I've personally never used CherryPy, so I don't know precisely what's being installed and how it's used, but I've done this same thing with Django without a hitch.</p>
<p>OK, I just downloaded CherryPy 3.1.2, unzipped it, and copied the contents of <code>./cherrypy/tutorial</code> to <code>.</code>, ran the <a href="http://www.cherrypy.org/wiki/CherryPyInstall" rel="nofollow">suggested</a> tut101_helloworld.py and it seems to work. </p>
<p>As far as hooking it up to Apache, it depends on what's available on your host. I think the most common Python interface is <a href="http://www.cherrypy.org/wiki/ModPython" rel="nofollow"><code>mod_python</code></a>. When following these instructions, it's important to set the <code>sys.path</code> right in order for <code>mod_python</code> to be able to see <code>cherrypy</code>.</p>
| 2 | 2009-06-02T06:40:49Z | [
"python",
"linux",
"cherrypy"
] |
Install CherryPy on Linux hosting provider without command line access | 938,185 | <p>I have a linux based web hosting provider (fatcow.com) that doesn't give any command line access and won't run the setup script for CherryPy (python web server) for me.</p>
<p>Is there any way to run get around this limitation so that I have a working install of CherryPy?</p>
<p>This might be more or a serverfault.com question, but maybe someone here has dealt with this before.</p>
| 0 | 2009-06-02T06:34:46Z | 1,476,225 | <p>An alternative to mod_python is mod_wsgi - <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithCherryPy" rel="nofollow">http://code.google.com/p/modwsgi/wiki/IntegrationWithCherryPy</a></p>
<p>But as Kyle mentioned, youll need to be able to edit your apache conf.</p>
| 0 | 2009-09-25T09:01:15Z | [
"python",
"linux",
"cherrypy"
] |
Preprocessing route parameters in Python Routes | 938,293 | <p>I'm using Routes for doing all the URL mapping job. Here's a typical route in my application:</p>
<pre><code>map.routes('route', '/show/{title:[^/]+}', controller='generator', filter_=postprocess_title)
</code></pre>
<p>Quite often I have to strip some characters (like whitespace and underscore) from the {title} parameter. Currently there's one call per method in the controller to a function that does this conversion. It's not terribly convenient and I'd like Routes to do this job. Is it possible?</p>
| 1 | 2009-06-02T07:17:33Z | 938,866 | <p>I am not familiar with Routes, and therefore I do not know if what you're after is possible with Routes.</p>
<p>But perhaps you could decorate your controller methods with a decorator that strips characters from parameters as needed?</p>
<p>Not sure if this would be more convenient. But to me, using a decorator has a different 'feel' than doing the same thing inline inside the controller method.</p>
<p>For instance:</p>
<pre><code>
@remove_spaces_from('title')
def my_controller(...):
...
</code></pre>
<p>If you are not familiar with decorators, a google search for "python decorators" will get you started. A key point to remember: When arguments are needed for a decorator, you need two levels of wrapping in the decorator.</p>
| 0 | 2009-06-02T10:40:10Z | [
"python",
"parameters",
"routes"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,433 | <p>I'm not a Python developer, but in general, it's best to avoid complex/error-prone operations in your constructor. One way around this would be to put a "LoadFromFile" or "Init" method in your class to populate the object from an external source. This load/init method must then be called separately after constructing the object.</p>
| 5 | 2009-06-02T08:08:39Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,450 | <p>One common pattern is two-phase construction, also suggested by Andy White.</p>
<p>First phase: Regular constructor.</p>
<p>Second phase: Operations that can fail.</p>
<p>Integration of the two: Add a factory method to do both phases and make the constructor protected/private to prevent instantation outside the factory method.</p>
<p>Oh, and I'm neither a Python developer.</p>
| 3 | 2009-06-02T08:12:52Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,453 | <p>In C++ at least, there is nothing wrong with putting failure-prone code in the constructor - you simply throw an exception if an error occurs. If the code is needed to properly construct the object, there reallyb is no alternative (although you can abstract the code into subfunctions, or better into the constructors of subobjects). Worst practice is to half-construct the object and then expect the user to call other functions to complete the construction somehow.</p>
| 20 | 2009-06-02T08:13:14Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,502 | <p>If the code to initialise the various values is really extensive enough that copying it is undesirable (which it sounds like it is in your case) I would personally opt for putting the required initialisation into a private method, adding a flag to indicate whether the initialisation has taken place, and making all accessors call the initialisation method if it has not initialised yet.</p>
<p>In threaded scenarios you may have to add extra protection in case initialisation is only allowed to occur once for valid semantics (which may or may not be the case since you are dealing with a file).</p>
| 0 | 2009-06-02T08:30:39Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,546 | <p>Again, I've got little experience with Python, however in C# its better to try and avoid having a constructor that throws an exception. An example of why that springs to mind is if you want to place your constructor at a point where its not possible to surround it with a try {} catch {} block, for example initialisation of a field in a class:</p>
<pre><code>class MyClass
{
MySecondClass = new MySecondClass();
// Rest of class
}
</code></pre>
<p>If the constructor of MySecondClass throws an exception that you wish to handle inside MyClass then you need to refactor the above - its certainly not the end of the world, but a nice-to-have.</p>
<p>In this case my approach would probably be to move the failure-prone initialisation logic into an initialisation method, and have the getters call that initialisation method before returning any values.</p>
<p>As an optimisation you should have the getter (or the initialisation method) set some sort of "IsInitialised" boolean to true, to indicate that the (potentially costly) initialisation does not need to be done again.</p>
<p>In pseudo-code (C# because I'll just mess up the syntax of Python):</p>
<pre><code>class MyClass
{
private bool IsInitialised = false;
private string myString;
public void Init()
{
// Put initialisation code here
this.IsInitialised = true;
}
public string MyString
{
get
{
if (!this.IsInitialised)
{
this.Init();
}
return myString;
}
}
}
</code></pre>
<p>This is of course not thread-safe, but I don't think multithreading is used that commonly in python so this is probably a non-issue for you.</p>
| 0 | 2009-06-02T08:45:05Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,641 | <p>It is not bad practice per se.</p>
<p>But I think you may be after a something different here. In your example the doSomething() method will not be called when the MyClass constructor fails. Try the following code:</p>
<pre><code>class MyClass:
def __init__(self, s):
print s
raise Exception("Exception")
def doSomething(self):
print "doSomething"
try:
someInstance = MyClass("test123")
someInstance.doSomething()
except:
print "except"
</code></pre>
<p>It should print:</p>
<pre><code>test123
except
</code></pre>
<p>For your software design you could ask the following questions:</p>
<ul>
<li><p>What should the scope of the someInstance variable be? Who are its users? What are their requirements?</p></li>
<li><p>Where and how should the error be handled for the case that one of your 10 values is not available?</p></li>
<li><p>Should all 10 values be cached at construction time or cached one-by-one when they are needed the first time?</p></li>
<li><p>Can the I/O code be refactored into a helper method, so that doing something similiar 10 times does not result in code repetition?</p></li>
<li><p>...</p></li>
</ul>
| 3 | 2009-06-02T09:27:38Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,677 | <p>There is a difference between a constructor in C++ and an <code>__init__</code> method
in Python. In C++, the task of a constructor is to construct an object. If it fails,
no destructor is called. Therefore if any resources were acquired before an
exception was thrown, the cleanup should be done before exiting the constructor.
Thus, some prefer two-phase construction with most of the construction done
outside the constructor (ugh).</p>
<p>Python has a much cleaner two-phase construction (construct, then
initialize). However, many people confuse an <code>__init__</code> method (initializer)
with a constructor. The actual constructor in Python is called <code>__new__</code>.
Unlike in C++, it does not take an instance, but
returns one. The task of <code>__init__</code> is to initialize the created instance.
If an exception is raised in <code>__init__</code>, the destructor <code>__del__</code> (if any)
will be called as expected, because the object was already created (even though it was not properly initialized) by the time <code>__init__</code> was called.</p>
<p>Answering your question:</p>
<blockquote>
<p>In Python, if code in your
"constructor" fails, the object ends
up not being defined.</p>
</blockquote>
<p>That's not precisely true. If <code>__init__</code> raises an exception, the object is
created but not initialized properly (e.g., some attributes are not
assigned). But at the time that it's raised, you probably don't have any references to
this object, so the fact that the attributes are not assigned doesn't matter. Only the destructor (if any) needs to check whether the attributes actually exist.</p>
<blockquote>
<p>Whats a proper way of doing this?</p>
</blockquote>
<p>In Python, initialize objects in <code>__init__</code> and don't worry about exceptions.
In C++, use <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow">RAII</a>.</p>
<hr>
<p><strong>Update</strong> [about resource management]:</p>
<p>In garbage collected languages, if you are dealing with resources, especially limited ones such as database connections, it's better not to release them in the destructor.
This is because objects are destroyed in a non-deterministic way, and if you happen
to have a loop of references (which is not always easy to tell), and at least one of the objects in the loop has a destructor defined, they will never be destroyed.
Garbage collected languages have other means of dealing with resources. In Python, it's a <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">with statement</a>.</p>
| 26 | 2009-06-02T09:35:25Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
Bad Practice to run code in constructor thats likely to fail? | 938,426 | <p>my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:</p>
<pre><code>someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
</code></pre>
<p>I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :</p>
<ol>
<li>is attribute really set?</li>
<li>do some IO actions to fill the attribute</li>
<li>return the contents of the variable in question</li>
</ol>
<p>I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.</p>
<p>Whats a proper way of doing this?</p>
| 12 | 2009-06-02T08:05:55Z | 938,720 | <p>seems Neil had a good point: my friend just pointed me to this:</p>
<p><a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow">http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization</a></p>
<p>which is basically what Neil said...</p>
| 0 | 2009-06-02T09:46:49Z | [
"python",
"oop",
"exception-handling",
"constructor"
] |
django Authentication using auth.views | 938,427 | <p>User should be redirected to the Login page after registration and after logout. In both cases there must be a message displayed indicating relevant messages.</p>
<p>Using the <code>django.contrib.auth.views.login</code> how do I send these {{ info }} messages.</p>
<p>A possible option would be to copy the <code>auth.views</code> to new registration module and include all essential stuff. But that doesn't seem DRY enough.</p>
<p>What is the best approach.</p>
<h3>Update: Question elaboration:</h3>
<p>For normal cases when you want to indicate to some user the response of an action you can use</p>
<pre><code>request.user.message_set.create()
</code></pre>
<p>This creates a message that is displayed in one of the templates and automatically deletes.</p>
<p>However this message system only works for logged in users who continue to have same session id. In the case of registration, the user is not authenticated and in the case of logout since the session changes, this system cannot be used.</p>
<p>Add to that, the built in <code>login</code> and <code>logout</code> functions from <code>django.contrib.auth.views</code> return a 'HttpResponseRedirect' which make it impossible to add another variable to the template. </p>
<p>I tried setting things on the request object itself </p>
<pre><code>request.info='Registered'
</code></pre>
<p>and check this in a <strong>different view</strong></p>
<pre><code>try:
info = request.info:
del request.info
except:
info = ''
#later
render_to_response('app/file',{'info':info})
</code></pre>
<p>Even this didn't work.</p>
<p>Clearly I can define a registered.html and add this static message there, but I was being lazy to write another template and trying to implement it DRY.</p>
<p>I realized that the cases were different for "registered" message and "logged out" message. And the DRY approach I used, I shall write as an answer.</p>
| 2 | 2009-06-02T08:06:53Z | 938,478 | <p>If the messages are static you can use your own templates for those views:</p>
<pre><code>(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}
</code></pre>
<p>From the <a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="nofollow">docs</a>.</p>
| 3 | 2009-06-02T08:22:24Z | [
"python",
"django",
"authentication",
"django-authentication"
] |
django Authentication using auth.views | 938,427 | <p>User should be redirected to the Login page after registration and after logout. In both cases there must be a message displayed indicating relevant messages.</p>
<p>Using the <code>django.contrib.auth.views.login</code> how do I send these {{ info }} messages.</p>
<p>A possible option would be to copy the <code>auth.views</code> to new registration module and include all essential stuff. But that doesn't seem DRY enough.</p>
<p>What is the best approach.</p>
<h3>Update: Question elaboration:</h3>
<p>For normal cases when you want to indicate to some user the response of an action you can use</p>
<pre><code>request.user.message_set.create()
</code></pre>
<p>This creates a message that is displayed in one of the templates and automatically deletes.</p>
<p>However this message system only works for logged in users who continue to have same session id. In the case of registration, the user is not authenticated and in the case of logout since the session changes, this system cannot be used.</p>
<p>Add to that, the built in <code>login</code> and <code>logout</code> functions from <code>django.contrib.auth.views</code> return a 'HttpResponseRedirect' which make it impossible to add another variable to the template. </p>
<p>I tried setting things on the request object itself </p>
<pre><code>request.info='Registered'
</code></pre>
<p>and check this in a <strong>different view</strong></p>
<pre><code>try:
info = request.info:
del request.info
except:
info = ''
#later
render_to_response('app/file',{'info':info})
</code></pre>
<p>Even this didn't work.</p>
<p>Clearly I can define a registered.html and add this static message there, but I was being lazy to write another template and trying to implement it DRY.</p>
<p>I realized that the cases were different for "registered" message and "logged out" message. And the DRY approach I used, I shall write as an answer.</p>
| 2 | 2009-06-02T08:06:53Z | 938,799 | <p>You have Request Context Processors to add this kind of information to the context of every template that gets rendered.</p>
<p>This is the "zero impact" way to do this kind of thing. You don't update any view functions, so it meets some definitions of DRY.</p>
<p>See <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#id1" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/templates/api/#id1</a></p>
<p>First, write your own login.html template.</p>
<p>Second, write your own context function to provide any additional information that must be inserted into the template.</p>
<p>Third, update settings to addy your context processor to the <code>TEMPLATE_CONTEXT_PROCESSORS</code> setting.</p>
| 0 | 2009-06-02T10:13:34Z | [
"python",
"django",
"authentication",
"django-authentication"
] |
django Authentication using auth.views | 938,427 | <p>User should be redirected to the Login page after registration and after logout. In both cases there must be a message displayed indicating relevant messages.</p>
<p>Using the <code>django.contrib.auth.views.login</code> how do I send these {{ info }} messages.</p>
<p>A possible option would be to copy the <code>auth.views</code> to new registration module and include all essential stuff. But that doesn't seem DRY enough.</p>
<p>What is the best approach.</p>
<h3>Update: Question elaboration:</h3>
<p>For normal cases when you want to indicate to some user the response of an action you can use</p>
<pre><code>request.user.message_set.create()
</code></pre>
<p>This creates a message that is displayed in one of the templates and automatically deletes.</p>
<p>However this message system only works for logged in users who continue to have same session id. In the case of registration, the user is not authenticated and in the case of logout since the session changes, this system cannot be used.</p>
<p>Add to that, the built in <code>login</code> and <code>logout</code> functions from <code>django.contrib.auth.views</code> return a 'HttpResponseRedirect' which make it impossible to add another variable to the template. </p>
<p>I tried setting things on the request object itself </p>
<pre><code>request.info='Registered'
</code></pre>
<p>and check this in a <strong>different view</strong></p>
<pre><code>try:
info = request.info:
del request.info
except:
info = ''
#later
render_to_response('app/file',{'info':info})
</code></pre>
<p>Even this didn't work.</p>
<p>Clearly I can define a registered.html and add this static message there, but I was being lazy to write another template and trying to implement it DRY.</p>
<p>I realized that the cases were different for "registered" message and "logged out" message. And the DRY approach I used, I shall write as an answer.</p>
| 2 | 2009-06-02T08:06:53Z | 946,776 | <p>I think the best solution to this problem is to use a "flash"-type session-based messaging system. There are several floating around: <a href="http://djangoflash.destaquenet.com/" rel="nofollow">django-flash</a> seems really nice, I use <a href="http://code.google.com/p/django-session-messages/" rel="nofollow">django-session-messages</a> which is very simple. Hopefully by the time we get to Django 1.2 this'll be baked-in.</p>
| 1 | 2009-06-03T19:46:44Z | [
"python",
"django",
"authentication",
"django-authentication"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,457 | <p>The problem here is the <code>m</code> variable (a reference) being taken from the surrounding scope.
Only parameters are held in the lambda scope.</p>
<p>To solve this you have to create another scope for lambda:</p>
<pre><code>def callback(msg):
print msg
def callback_factory(m):
return lambda: callback(m)
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(callback_factory(m))
for f in funcList:
f()
</code></pre>
<p>In the example above, lambda also uses the surounding scope to find <code>m</code>, but this
time it's <code>callback_factory</code> scope which is created once per every <code>callback_factory</code>
call.</p>
<p>Or with <a href="http://docs.python.org/library/functools.html#functools.partial">functools.partial</a>:</p>
<pre><code>from functools import partial
def callback(msg):
print msg
funcList=[partial(callback, m) for m in ('do', 're', 'mi')]
for f in funcList:
f()
</code></pre>
| 49 | 2009-06-02T08:14:33Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,472 | <p>First, what you are seeing is not a problem, and not related to call-by-reference or by-value.</p>
<p>The lambda syntax you defined has no parameters, and as such, the scope you are seeing with parameter <code>m</code> is external to the lambda function. This is why you are seeing these results.</p>
<p>Lambda syntax, in your example is not necessary, and you would rather be using a simple function call:</p>
<pre><code>for m in ('do', 're', 'mi'):
callback(m)
</code></pre>
<p>Again, you should be very precise about what lambda parameters you are using and where exactly their scope begins and ends.</p>
<p>As a side note, regarding parameter passing. Parameters in python are always references to objects. To quote Alex Martelli:</p>
<blockquote>
<p>The terminology problem may be due to
the fact that, in python, the value of
a name is a reference to an object.
So, you always pass the value (no
implicit copying), and that value is
always a reference. [...] Now if you
want to coin a name for that, such as
"by object reference", "by uncopied
value", or whatever, be my guest.
Trying to reuse terminology that is
more generally applied to languages
where "variables are boxes" to a
language where "variables are post-it
tags" is, IMHO, more likely to confuse
than to help.</p>
</blockquote>
| 0 | 2009-06-02T08:20:56Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,479 | <p>The variable <code>m</code> is being captured, so your lambda expression always sees its "current" value.</p>
<p>If you need to effectively capture the value at a moment in time, write a function takes the value you want as a parameter, and returns a lambda expression. At that point, the lambda will capture the <em>parameter's</em> value, which won't change when you call the function multiple times:</p>
<pre><code>def callback(msg):
print msg
def createCallback(msg):
return lambda: callback(msg)
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(createCallback(m))
for f in funcList:
f()
</code></pre>
<p>Output:</p>
<pre><code>do
re
mi
</code></pre>
| 0 | 2009-06-02T08:22:27Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,489 | <p>Yes, that's a problem of scope, it binds to the outer m, whether you are using a lambda or a local function. Instead, use a functor:</p>
<pre><code>class Func1(object):
def __init__(self, callback, message):
self.callback = callback
self.message = message
def __call__(self):
return self.callback(self.message)
funcList.append(Func1(callback, m))
</code></pre>
| 0 | 2009-06-02T08:25:41Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,493 | <p>When a lambda is created, it doesn't make a copy of the variables in the enclosing scope that it uses. It maintains a reference to the environment so that it can look up the value of the variable later. There is just one <code>m</code>. It gets assigned to every time through the loop. After the loop, the variable <code>m</code> has value <code>'mi'</code>. So when you actually run the function you created later, it will look up the value of <code>m</code> in the environment that created it, which will by then have value <code>'mi'</code>.</p>
<p>One common and idiomatic solution to this problem is to capture the value of <code>m</code> at the time that the lambda is created by using it as the default argument of an optional parameter. You usually use a parameter of the same name so you don't have to change the body of the code:</p>
<pre><code>for m in ('do', 're', 'mi'):
funcList.append(lambda m=m: callback(m))
</code></pre>
| 92 | 2009-06-02T08:27:06Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,496 | <p>Python does uses references of course, but it does not matter in this context.</p>
<p>When you define a lambda (or a function, since this is the exact same behavior), it does not evaluate the lambda expression before runtime:</p>
<pre><code># defining that function is perfectly fine
def broken():
print undefined_var
broken() # but calling it will raise a NameError
</code></pre>
<p>Even more surprising than your lambda example:</p>
<pre><code>i = 'bar'
def foo():
print i
foo() # bar
i = 'banana'
foo() # you would expect 'bar' here? well it prints 'banana'
</code></pre>
<p>In short, think dynamic: nothing is evaluated before interpretation, that's why your code uses the latest value of m.</p>
<p>When it looks for m in the lambda execution, m is taken from the topmost scope, which means that, as others pointed out; you can circumvent that problem by adding another scope:</p>
<pre><code>def factory(x):
return lambda: callback(x)
for m in ('do', 're', 'mi'):
funcList.append(factory(m))
</code></pre>
<p>Here, when the lambda is called, it looks in the lambda' definition scope for a x. This x is a local variable defined in factory's body. Because of this, the value used on lambda execution will be the value that was passed as a parameter during the call to factory. And doremi!</p>
<p>As a note, I could have defined factory as factory(m) [replace x by m], the behavior is the same. I used a different name for clarity :)</p>
<p>You might find that <a href="http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/" rel="nofollow">Andrej Bauer</a> got similar lambda problems. What's interesting on that blog is the comments, where you'll learn more about python closure :)</p>
| 4 | 2009-06-02T08:27:52Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 938,522 | <p>there are actually no variables in the classic sense in Python, just names that have been bound by references to the applicable object. Even functions are some sort of object in Python, and lambdas do not make an exception to the rule :)</p>
| 0 | 2009-06-02T08:37:56Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 953,778 | <p>Not directly related to the issue at hand, but an invaluable piece of wisdom nevertheless: <a href="http://www.effbot.org/zone/python-objects.htm" rel="nofollow">Python Objects</a> by Fredrik Lundh. </p>
| 1 | 2009-06-05T00:37:42Z | [
"python",
"lexical-closures"
] |
Scope of python lambda functions and their parameters | 938,429 | <p>I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.</p>
<p>So I have the following simplified code below:</p>
<pre><code>def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
</code></pre>
<p>The output of this code is:</p>
<pre>
mi
mi
mi
do
re
mi
</pre>
<p>I expected:</p>
<pre>
do
re
mi
do
re
mi
</pre>
<p>Why has using an iterator messed things up?</p>
<p>I've tried using a deepcopy:</p>
<pre><code>import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
</code></pre>
<p>But this has the same problem. Thanks for helping me understand python better! I'm sure this will make sense once you help me figure it out! :)</p>
| 54 | 2009-06-02T08:07:04Z | 12,315,344 | <p>As a side note, <code>map</code>, although despised by some well known Python figure, forces a construction which prevents this pitfall.</p>
<pre><code>fs = map (lambda i: lambda: callback (i), ['do', 're', 'mi'])
</code></pre>
<p>NB : the first <code>lambda i</code> acts like the factory in other answers.</p>
| 0 | 2012-09-07T09:26:57Z | [
"python",
"lexical-closures"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 938,746 | <p><a href="http://guppy-pe.sourceforge.net/#Heapy">Heapy</a> (and friends) may be what you're looking for.</p>
<p>Also, caches typically have a fixed upper limit on their size to solve the sort of problem you're talking about. For instance, check out this <a href="http://code.activestate.com/recipes/498245/">LRU cache decorator</a>.</p>
| 6 | 2009-06-02T09:55:47Z | [
"python",
"memory-management"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 938,754 | <p>On unix, you can use the <code>ps</code> tool to monitor it:</p>
<pre><code>$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'
</code></pre>
<p>where 1347 is some process id. Also, the result is in MB.</p>
| 14 | 2009-06-02T09:59:10Z | [
"python",
"memory-management"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 938,800 | <p>On Windows, you can use WMI (<a href="http://timgolden.me.uk/python/wmi.html">home page</a>, <a href="http://pypi.python.org/pypi/WMI/1.3.2">cheeseshop</a>):</p>
<pre><code>
def memory():
import os
from wmi import WMI
w = WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
return int(result[0].WorkingSet)
</code></pre>
<p>On Linux (from python cookbook <a href="http://code.activestate.com/recipes/286222/">http://code.activestate.com/recipes/286222/</a>:</p>
<pre><code>import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
def stacksize(since=0.0):
'''Return stack size in bytes.
'''
return _VmB('VmStk:') - since
</code></pre>
| 45 | 2009-06-02T10:13:40Z | [
"python",
"memory-management"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 7,669,482 | <p>For Unixes (Linux, Mac OS X, Solaris) you could also use the <code>getrusage()</code> function from the standard library module <code>resource</code>. The resulting object has the attribute <code>ru_maxrss</code>, which gives <em>peak</em> memory usage for the calling process:</p>
<pre><code>>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656 # peak memory usage (bytes on OS X, kilobytes on Linux)
</code></pre>
<p>The <a href="http://docs.python.org/library/resource.html#resource-usage">Python docs</a> aren't clear on what the units are exactly, but the <a href="http://developer.apple.com/library/mac/#documentation/darwin/reference/manpages/man2/getrusage.2.html">Mac OS X man page</a> for <code>getrusage(2)</code> describes the units as <em>bytes</em>. The Linux man page isn't clear, but it seems to be equivalent to the information from <code>/proc/self/status</code>, which is in <em>kilobytes</em>.</p>
<p>The <code>getrusage()</code> function can also be given <code>resource.RUSAGE_CHILDREN</code> to get the usage for child processes, and (on some systems) <code>resource.RUSAGE_BOTH</code> for total (self and child) process usage.</p>
<p><code>resource</code> is a standard library module.</p>
<p>If you only care about Linux, you can just check the <code>/proc/self/status</code> file as described in a <a href="http://stackoverflow.com/questions/897941/python-equivalent-of-phps-memory-get-usage">similar question</a>.</p>
| 105 | 2011-10-06T01:23:56Z | [
"python",
"memory-management"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 16,576,018 | <p>Using sh and os to get into python bayer's answer.</p>
<pre><code>float(sh.awk(sh.ps('u','-p',os.getpid()),'{sum=sum+$6}; END {print sum/1024}'))
</code></pre>
<p>Answer is in megabytes.</p>
| 0 | 2013-05-15T22:25:44Z | [
"python",
"memory-management"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 21,632,554 | <p><a href="http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/">Here</a> is a useful solution that works for various operating systems, including Windows 7 x64:</p>
<pre><code>import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss)
</code></pre>
| 53 | 2014-02-07T16:11:44Z | [
"python",
"memory-management"
] |
Total memory used by Python process? | 938,733 | <p>Is there a way for a Python program to determine how much memory it's currently using? I've seen discussions about memory usage for a single object, but what I need is total memory usage for the process, so that I can determine when it's necessary to start discarding cached data.</p>
| 99 | 2009-06-02T09:50:40Z | 27,129,692 | <pre><code>han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])
</code></pre>
| 1 | 2014-11-25T14:46:28Z | [
"python",
"memory-management"
] |
Extracting YouTube Video's author using Python and YouTubeAPI | 938,742 | <p>how do I get the author/username from an object using:</p>
<pre><code>GetYouTubeVideoEntry(video_id=youtube_video_id_to_output)
</code></pre>
<p>I'm using Google's gdata.youtube.service Python library</p>
<p>Thanks in advance! :)</p>
| 5 | 2009-06-02T09:54:32Z | 938,774 | <p>Have you tried something like this?</p>
<pre><code>foo = GetYouTubeVideoEntry(video_id=youtube_video_id_to_output)
foo.author
</code></pre>
<p>The <a href="http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.youtube.html#YouTubeVideoEntry" rel="nofollow">docs for YouTubeVideoEntry</a> aren't great, but the <code>__init__</code> method seems to accept an author.</p>
| 0 | 2009-06-02T10:04:13Z | [
"python",
"youtube",
"youtube-api"
] |
Extracting YouTube Video's author using Python and YouTubeAPI | 938,742 | <p>how do I get the author/username from an object using:</p>
<pre><code>GetYouTubeVideoEntry(video_id=youtube_video_id_to_output)
</code></pre>
<p>I'm using Google's gdata.youtube.service Python library</p>
<p>Thanks in advance! :)</p>
| 5 | 2009-06-02T09:54:32Z | 943,084 | <p>So because YouTube's API is based on GData, which is based on Atom, the 'author' object is an array with name objects, which can contain names, URLs, etc.</p>
<p>This is what you want:</p>
<pre><code>>>> client = gdata.youtube.service.YouTubeService()
>>> video = client.GetYouTubeVideoEntry(video_id='CoYBkXD0QeU')
>>> video.author[0].name.text
'GoogleDevelopers'
</code></pre>
| 6 | 2009-06-03T04:40:34Z | [
"python",
"youtube",
"youtube-api"
] |
Python IRC bot and encoding issue | 938,870 | <p>Currently I have a simple IRC bot written in python.</p>
<p>Since I migrated it to python 3.0 which differentiates between bytes and unicode strings I started having encoding issues. Specifically, with others not sending UTF-8.</p>
<p>Now, I could just tell everyone to send UTF-8 (which they should regardless) but an even better solution would be try to get python to default to some other encoding or such.</p>
<p>So far the code looks like this:</p>
<pre><code>data = str(irc.recv(4096),"UTF-8", "replace")
</code></pre>
<p>Which at least doesn't throw exceptions. However, I want to go past it: I want my bot to default to another encoding, or try to detect "troublesome characters" somehow.</p>
<p>Additionally, I need to figure out what this mysterious encoding that mIRC uses actually is - as other clients appear to work fine and send UTF-8 like they should.</p>
<p>How should I go about doing those things?</p>
| 3 | 2009-06-02T10:41:48Z | 938,880 | <p><a href="https://pypi.python.org/pypi/chardet" rel="nofollow">chardet</a> should help - it's the canonical Python library for detecting unknown encodings.</p>
| 3 | 2009-06-02T10:45:28Z | [
"python",
"unicode",
"encoding",
"irc"
] |
Python IRC bot and encoding issue | 938,870 | <p>Currently I have a simple IRC bot written in python.</p>
<p>Since I migrated it to python 3.0 which differentiates between bytes and unicode strings I started having encoding issues. Specifically, with others not sending UTF-8.</p>
<p>Now, I could just tell everyone to send UTF-8 (which they should regardless) but an even better solution would be try to get python to default to some other encoding or such.</p>
<p>So far the code looks like this:</p>
<pre><code>data = str(irc.recv(4096),"UTF-8", "replace")
</code></pre>
<p>Which at least doesn't throw exceptions. However, I want to go past it: I want my bot to default to another encoding, or try to detect "troublesome characters" somehow.</p>
<p>Additionally, I need to figure out what this mysterious encoding that mIRC uses actually is - as other clients appear to work fine and send UTF-8 like they should.</p>
<p>How should I go about doing those things?</p>
| 3 | 2009-06-02T10:41:48Z | 939,125 | <p>Ok, after some research turns out chardet is having troubles with python 3. The solution as it turns out is simpler than I thought. I chose to fall back on CP1252 if UTF-8 doesn't cut it:</p>
<pre><code>data = irc.recv ( 4096 )
try: data = str(data,"UTF-8")
except UnicodeDecodeError: data = str(data,"CP1252")
</code></pre>
<p>Which seems to be working. Though it doesn't detect the encoding, and so if somebody came in with an encoding that is neither UTF-8 nor CP1252 I will again have a problem.</p>
<p>This is really just a temporary solution.</p>
| -1 | 2009-06-02T11:59:04Z | [
"python",
"unicode",
"encoding",
"irc"
] |
Python IRC bot and encoding issue | 938,870 | <p>Currently I have a simple IRC bot written in python.</p>
<p>Since I migrated it to python 3.0 which differentiates between bytes and unicode strings I started having encoding issues. Specifically, with others not sending UTF-8.</p>
<p>Now, I could just tell everyone to send UTF-8 (which they should regardless) but an even better solution would be try to get python to default to some other encoding or such.</p>
<p>So far the code looks like this:</p>
<pre><code>data = str(irc.recv(4096),"UTF-8", "replace")
</code></pre>
<p>Which at least doesn't throw exceptions. However, I want to go past it: I want my bot to default to another encoding, or try to detect "troublesome characters" somehow.</p>
<p>Additionally, I need to figure out what this mysterious encoding that mIRC uses actually is - as other clients appear to work fine and send UTF-8 like they should.</p>
<p>How should I go about doing those things?</p>
| 3 | 2009-06-02T10:41:48Z | 10,255,103 | <p>The chardet will probably be your best solution as RichieHindle mentioned. However, if you want to cover about 90% of the text you'll see you can use what I use:</p>
<pre><code>def decode(bytes):
try:
text = bytes.decode('utf-8')
except UnicodeDecodeError:
try:
text = bytes.decode('iso-8859-1')
except UnicodeDecodeError:
text = bytes.decode('cp1252')
return text
def encode(bytes):
try:
text = bytes.encode('utf-8')
except UnicodeEncodeError:
try:
text = bytes.encode('iso-8859-1')
except UnicodeEncodeError:
text = bytes.encode('cp1252')
return text
</code></pre>
| 0 | 2012-04-21T00:29:07Z | [
"python",
"unicode",
"encoding",
"irc"
] |
Python IRC bot and encoding issue | 938,870 | <p>Currently I have a simple IRC bot written in python.</p>
<p>Since I migrated it to python 3.0 which differentiates between bytes and unicode strings I started having encoding issues. Specifically, with others not sending UTF-8.</p>
<p>Now, I could just tell everyone to send UTF-8 (which they should regardless) but an even better solution would be try to get python to default to some other encoding or such.</p>
<p>So far the code looks like this:</p>
<pre><code>data = str(irc.recv(4096),"UTF-8", "replace")
</code></pre>
<p>Which at least doesn't throw exceptions. However, I want to go past it: I want my bot to default to another encoding, or try to detect "troublesome characters" somehow.</p>
<p>Additionally, I need to figure out what this mysterious encoding that mIRC uses actually is - as other clients appear to work fine and send UTF-8 like they should.</p>
<p>How should I go about doing those things?</p>
| 3 | 2009-06-02T10:41:48Z | 11,435,607 | <p>Using only chardet leads to poor results for situations where messages are short (which is the case in IRC).</p>
<p>Chardet combined with remembering the encoding for specific user throughout the messages could make sense. However, for simplicity I'd use some presumable encodings (encodings depend on culture and epoch, see <a href="http://en.wikipedia.org/wiki/Internet_Relay_Chat#Character_encoding" rel="nofollow">http://en.wikipedia.org/wiki/Internet_Relay_Chat#Character_encoding</a>) and if they fail, I'd go to chardet (if someone uses some of Eastern Asian encodings, this will help us out).</p>
<p>For example:</p>
<pre><code>def decode_irc(raw, preferred_encs = ["UTF-8", "CP1252", "ISO-8859-1"]):
changed = False
for enc in preferred_encs:
try:
res = raw.decode(enc)
changed = True
break
except:
pass
if not changed:
try:
enc = chardet.detect(raw)['encoding']
res = raw.decode(enc)
except:
res = raw.decode(enc, 'ignore')
return res
</code></pre>
| 0 | 2012-07-11T15:03:06Z | [
"python",
"unicode",
"encoding",
"irc"
] |
Pygtk graphics contexts and allocating colors | 938,921 | <p>I've searched on this, but nothing has what I'm looking for. </p>
<p><a href="http://www.mail-archive.com/pygtk@daa.com.au/msg10529.html" rel="nofollow">http://www.mail-archive.com/pygtk@daa.com.au/msg10529.html</a> -- Nobody answered him. This is exactly what I'm experiencing. When I set the foreground on a graphics context, it doesn't seem to actually change.</p>
<p>I've been through the tutorial and FAQ, but neither say much. They either just use the black and white contexts or they give you broken links. I'm left thinking maybe it's a bug. But the kid in me says I'm just missing something and I keep ignoring the fact I have a working alternative. This would be better though. And the further I get into this, the more I'm going to need these contexts and colors. </p>
<p>Here's my code snippet.</p>
<pre><code>def CreatePixmapFromLCDdata(lcdP, ch, widget):
width = lcdP.get_char_width()
height = lcdP.get_char_height()
# Create pixmap
pixmap = gtk.gdk.Pixmap(widget.window, width, height)
# Working graphics contexts, wrong color
black_gc = widget.get_style().black_gc
white_gc = widget.get_style().white_gc
char_gc = widget.window.new_gc()
colormap = char_gc.get_colormap()
bg_color = NewColor(text="#78a878", colormap=colormap)
print "Before", char_gc.foreground.red, char_gc.foreground.green, char_gc.foreground.blue
char_gc.set_foreground(bg_color)
print "AFter", char_gc.foreground.red, char_gc.foreground.green, char_gc.foreground.blue
fg_color = NewColor(text="#113311", colormap=colormap)
pixmap.draw_rectangle(char_gc, True, 0, 0, width, height)
char_gc.foreground = fg_color
for j in range(lcdP.dots['y']):
k = lcdP.pixels['y']*j
for i in range(lcdP.dots['x']):
if 1<<(lcdP.dots['x']-1-i) & ch[j] == 0: continue
m = i*lcdP.pixels['y']
for jj in range(k, k+lcdP.pixels['y']-1):
for ii in range(m+1, m+lcdP.pixels['x']):
pixmap.draw_point(char_gc, ii, jj)
return pixmap
</code></pre>
<p>I thought maybe it was the way I was allocating the colors. As you see in the snippet, I've used the graphic context's own colormap. I've tried different colormaps, this being the latest. I've even tried an unallocated color. Notice the white_gc and black_gc graphics contexts. When I use those I'm able to draw black on a white background fine. Otherwise (with a created context) everything's black, fg and bg. When I change white's foreground color, it always comes out black.</p>
<p>Here's the output. Notice the color doesn't change very much. I'd say it didn't change, or at least not enough to matter visually.</p>
<pre><code>Before 6 174 60340
After 5 174 60340
</code></pre>
<p>Here's how I allocate the colors. </p>
<pre><code>def NewColor(red=0, green=0, blue=0, text=None, colormap=None):
if text == None:
c = gtk.gdk.Color(red, green, blue)
else:
c = gtk.gdk.color_parse(text)
if colormap == None:
colormap = gtk.gdk.colormap_get_system()
colormap.alloc_color(c)
return c
</code></pre>
| 2 | 2009-06-02T11:00:21Z | 939,195 | <p>I've had some trouble with <a href="http://www.pygtk.org/pygtk2reference/class-gdkdrawable.html" rel="nofollow">Drawable</a> and <a href="http://www.pygtk.org/pygtk2reference/class-gdkgc.html" rel="nofollow">GC</a> in the past. <a href="http://stackoverflow.com/questions/326300/python-best-library-for-drawing/326548#326548">This answer</a> got me started on the way to a solution. Here's a quick example that uses a custom colour gc to draw some squares:</p>
<pre><code>import gtk
square_sz = 20
pixmap = None
colour = "#FF0000"
gc = None
def configure_event( widget, event):
global pixmap
x, y, width, height = widget.get_allocation()
pixmap = gtk.gdk.Pixmap(widget.window, width, height)
white_gc = widget.get_style().white_gc
pixmap.draw_rectangle(white_gc, True, 0, 0, width, height)
return True
def expose_event(widget, event):
global pixmap
if pixmap:
x , y, w, h = event.area
drawable_gc = widget.get_style().fg_gc[gtk.STATE_NORMAL]
widget.window.draw_drawable(drawable_gc, pixmap, x, y, x, y, w, h)
return False
def button_press_event(widget, event):
global pixmap, square_sz, gc, colour
if event.button == 1 and pixmap:
x = int(event.x / square_sz) * square_sz
y = int(event.y / square_sz) * square_sz
if not gc:
gc = widget.window.new_gc()
gc.set_rgb_fg_color(gtk.gdk.color_parse(colour))
pixmap.draw_rectangle(gc, True, x, y, square_sz, square_sz)
widget.queue_draw_area(x, y, square_sz, square_sz)
return True
if __name__ == "__main__":
da = gtk.DrawingArea()
da.set_size_request(square_sz*20, square_sz*20)
da.connect("expose_event", expose_event)
da.connect("configure_event", configure_event)
da.connect("button_press_event", button_press_event)
da.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.BUTTON_PRESS_MASK)
w = gtk.Window()
w.add(da)
w.show_all()
w.connect("destroy", lambda w: gtk.main_quit())
gtk.main()
</code></pre>
<p>Hope it helps.</p>
| 2 | 2009-06-02T12:14:38Z | [
"python",
"pygtk",
"drawing2d"
] |
Pygtk graphics contexts and allocating colors | 938,921 | <p>I've searched on this, but nothing has what I'm looking for. </p>
<p><a href="http://www.mail-archive.com/pygtk@daa.com.au/msg10529.html" rel="nofollow">http://www.mail-archive.com/pygtk@daa.com.au/msg10529.html</a> -- Nobody answered him. This is exactly what I'm experiencing. When I set the foreground on a graphics context, it doesn't seem to actually change.</p>
<p>I've been through the tutorial and FAQ, but neither say much. They either just use the black and white contexts or they give you broken links. I'm left thinking maybe it's a bug. But the kid in me says I'm just missing something and I keep ignoring the fact I have a working alternative. This would be better though. And the further I get into this, the more I'm going to need these contexts and colors. </p>
<p>Here's my code snippet.</p>
<pre><code>def CreatePixmapFromLCDdata(lcdP, ch, widget):
width = lcdP.get_char_width()
height = lcdP.get_char_height()
# Create pixmap
pixmap = gtk.gdk.Pixmap(widget.window, width, height)
# Working graphics contexts, wrong color
black_gc = widget.get_style().black_gc
white_gc = widget.get_style().white_gc
char_gc = widget.window.new_gc()
colormap = char_gc.get_colormap()
bg_color = NewColor(text="#78a878", colormap=colormap)
print "Before", char_gc.foreground.red, char_gc.foreground.green, char_gc.foreground.blue
char_gc.set_foreground(bg_color)
print "AFter", char_gc.foreground.red, char_gc.foreground.green, char_gc.foreground.blue
fg_color = NewColor(text="#113311", colormap=colormap)
pixmap.draw_rectangle(char_gc, True, 0, 0, width, height)
char_gc.foreground = fg_color
for j in range(lcdP.dots['y']):
k = lcdP.pixels['y']*j
for i in range(lcdP.dots['x']):
if 1<<(lcdP.dots['x']-1-i) & ch[j] == 0: continue
m = i*lcdP.pixels['y']
for jj in range(k, k+lcdP.pixels['y']-1):
for ii in range(m+1, m+lcdP.pixels['x']):
pixmap.draw_point(char_gc, ii, jj)
return pixmap
</code></pre>
<p>I thought maybe it was the way I was allocating the colors. As you see in the snippet, I've used the graphic context's own colormap. I've tried different colormaps, this being the latest. I've even tried an unallocated color. Notice the white_gc and black_gc graphics contexts. When I use those I'm able to draw black on a white background fine. Otherwise (with a created context) everything's black, fg and bg. When I change white's foreground color, it always comes out black.</p>
<p>Here's the output. Notice the color doesn't change very much. I'd say it didn't change, or at least not enough to matter visually.</p>
<pre><code>Before 6 174 60340
After 5 174 60340
</code></pre>
<p>Here's how I allocate the colors. </p>
<pre><code>def NewColor(red=0, green=0, blue=0, text=None, colormap=None):
if text == None:
c = gtk.gdk.Color(red, green, blue)
else:
c = gtk.gdk.color_parse(text)
if colormap == None:
colormap = gtk.gdk.colormap_get_system()
colormap.alloc_color(c)
return c
</code></pre>
| 2 | 2009-06-02T11:00:21Z | 1,965,532 | <p>The problem is that the <code>NewColor()</code> function is returning an unallocated color <code>c</code>. <code>colormap.alloc_color()</code> returns a <code>gtk.gdk.Color</code> which is the allocated color. To fix things the last line in <code>NewColor()</code> should be:</p>
<pre><code>return colormap.alloc_color(c)
</code></pre>
| 1 | 2009-12-27T08:47:45Z | [
"python",
"pygtk",
"drawing2d"
] |
Printed representation of list | 939,243 | <p>I want to format a list into a string in this way:
<code>[1,2,3] => '1 2 3'</code>. How to do this?
Is there any customizable formatter in Python as Common Lisp format?</p>
| 0 | 2009-06-02T12:28:59Z | 939,249 | <pre><code>' '.join(str(i) for i in your_list)
</code></pre>
| 11 | 2009-06-02T12:31:11Z | [
"python"
] |
Printed representation of list | 939,243 | <p>I want to format a list into a string in this way:
<code>[1,2,3] => '1 2 3'</code>. How to do this?
Is there any customizable formatter in Python as Common Lisp format?</p>
| 0 | 2009-06-02T12:28:59Z | 939,363 | <pre><code>' '.join(str(i) for i in your_list)
</code></pre>
<p>First, convert any element into a string, then join them into a unique string.</p>
| 7 | 2009-06-02T13:01:16Z | [
"python"
] |
Purpose of @ symbols in Python? | 939,426 | <p>I've noticed in several examples i see things such as this:</p>
<pre><code># Comments explaining code i think
@innerclass
</code></pre>
<p>or:</p>
<pre><code>def foo():
"""
Basic Doc String
"""
@classmethod
</code></pre>
<p>Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentation.</p>
<p>What do these do?</p>
| 9 | 2009-06-02T13:13:22Z | 939,443 | <p>it is a <a href="http://docs.python.org/glossary.html#term-decorator" rel="nofollow"><code>decorator</code></a> syntax.</p>
| 1 | 2009-06-02T13:15:51Z | [
"python"
] |
Purpose of @ symbols in Python? | 939,426 | <p>I've noticed in several examples i see things such as this:</p>
<pre><code># Comments explaining code i think
@innerclass
</code></pre>
<p>or:</p>
<pre><code>def foo():
"""
Basic Doc String
"""
@classmethod
</code></pre>
<p>Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentation.</p>
<p>What do these do?</p>
| 9 | 2009-06-02T13:13:22Z | 939,447 | <p>They're decorators.</p>
<p><code><shameless plug></code>
I have a <a href="http://jasonmbaker.wordpress.com/2009/04/25/the-magic-of-python-decorators/">blog post</a> on the subject.
<code></shameless plug></code></p>
| 9 | 2009-06-02T13:16:22Z | [
"python"
] |
Purpose of @ symbols in Python? | 939,426 | <p>I've noticed in several examples i see things such as this:</p>
<pre><code># Comments explaining code i think
@innerclass
</code></pre>
<p>or:</p>
<pre><code>def foo():
"""
Basic Doc String
"""
@classmethod
</code></pre>
<p>Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentation.</p>
<p>What do these do?</p>
| 9 | 2009-06-02T13:13:22Z | 939,453 | <p>With </p>
<pre><code>@function
def f():
pass
</code></pre>
<p>you simply wrap <code>function</code> around <code>f()</code>. <code>function</code> is called a decorator. </p>
<p>It is just syntactic sugar for the following:</p>
<pre><code>def f():
pass
f=function(f)
</code></pre>
| 3 | 2009-06-02T13:17:15Z | [
"python"
] |
Purpose of @ symbols in Python? | 939,426 | <p>I've noticed in several examples i see things such as this:</p>
<pre><code># Comments explaining code i think
@innerclass
</code></pre>
<p>or:</p>
<pre><code>def foo():
"""
Basic Doc String
"""
@classmethod
</code></pre>
<p>Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentation.</p>
<p>What do these do?</p>
| 9 | 2009-06-02T13:13:22Z | 939,459 | <p>They are called decorators. They are functions applied to other functions. Here is a copy of my answer to a similar question.</p>
<p>Python decorators add extra functionality to another function.
An italics decorator could be like</p>
<pre><code>def makeitalic(fn):
def newFunc():
return "<i>" + fn() + "</i>"
return newFunc
</code></pre>
<p>Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class</p>
<pre><code>class foo:
def bar(self):
print "hi"
def foobar(self):
print "hi again"
</code></pre>
<p>Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator</p>
<pre><code>def addDashes(fn): # notice it takes a function as an argument
def newFunction(self): # define a new function
print "---"
fn(self) # call the original function
print "---"
return newFunction
# Return the newly defined function - it will "replace" the original
</code></pre>
<p>So now I can change my class to </p>
<pre><code>class foo:
@addDashes
def bar(self):
print "hi"
@addDashes
def foobar(self):
print "hi again"
</code></pre>
<p>For more on decorators, check <a href="http://www.ibm.com/developerworks/linux/library/l-cpdecor.html">http://www.ibm.com/developerworks/linux/library/l-cpdecor.html</a></p>
| 18 | 2009-06-02T13:17:30Z | [
"python"
] |
How i can send the commands from keyboards using python. I am trying to automate mac app (GUI) | 939,746 | <p>I am trying to automate a app using python. I need help to send keyboard commands through python. I am using powerBook G4.</p>
| 1 | 2009-06-02T14:02:16Z | 947,222 | <p>To the best of my knowledge, python does not contain the ability to simulate keystrokes. You can however use python to call a program which has the functionality that you need for OS X. You could also write said program using Objective C most likely.</p>
<p>Or you could save yourself the pain and use Automator. Perhaps if you posted more details about what you were automating, I could add something further.</p>
| 0 | 2009-06-03T21:00:12Z | [
"python"
] |
How i can send the commands from keyboards using python. I am trying to automate mac app (GUI) | 939,746 | <p>I am trying to automate a app using python. I need help to send keyboard commands through python. I am using powerBook G4.</p>
| 1 | 2009-06-02T14:02:16Z | 949,897 | <p>You could call AppleScript from your python script with osascript tool:</p>
<pre><code>import os
cmd = """
osascript -e 'tell application "System Events" to keystroke "m" using {command down}'
"""
# minimize active window
os.system(cmd)
</code></pre>
| 2 | 2009-06-04T11:10:02Z | [
"python"
] |
Threading In Python | 939,754 | <p>I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?</p>
| 6 | 2009-06-02T14:03:16Z | 939,815 | <p>It depends on the platform. </p>
<p>Windows threads have to commit around 1MB of memory when created. It's better to have some kind of threadpool than spawning threads like a madman, to make sure you never allocate more than a fixed amount of threads. Also, when you work in Python, you're subject to the Global Interpreter Lock which hinders code that rely on lots of concurrent threads.</p>
<p>On Unix, you may consider using different processes instead of threads, or look at other asynchronous way of doing things (the Twisted server framework has interesting ways of handling asynchronous network tasks, and if you feel really adventurous you can take a look at stackless Python, a continuation framework which don't really use kernel threads at all).</p>
| 4 | 2009-06-02T14:11:54Z | [
"python",
"multithreading"
] |
Threading In Python | 939,754 | <p>I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?</p>
| 6 | 2009-06-02T14:03:16Z | 939,827 | <p>You have to consider multiple things if you want to use multiple threads:</p>
<ol>
<li>You can only run #processors threads simultaneously. (Obvious)</li>
<li>In Python each thread is a 'kernel thread' which normally takes a non-trivial amount of resources (8 mb stack by default on linux)</li>
<li>Python has a global interpreter lock, which means only one python instructions can be processed at once independently of the number of processors. This lock is however released if one of your threads waits on IO.</li>
</ol>
<p>The conclusion I take from that:</p>
<ol>
<li>If you are doing IO (Turbogears, Twisted) or are using properly coded extension modules (numpy) use threads.</li>
<li>If you want to execute python code concurrently use processes (easiest with multiprocess module)</li>
</ol>
| 18 | 2009-06-02T14:15:42Z | [
"python",
"multithreading"
] |
Threading In Python | 939,754 | <p>I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?</p>
| 6 | 2009-06-02T14:03:16Z | 939,839 | <p>Threads do have some CPU and memory overhead but unless you spawn hundreds or thousands of them, it usually isn't all that significant. The more important issue is that threads make correct programming a lot more difficult if you share any writable datastructures between concurrent threads. See the paper <a href="http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdf" rel="nofollow">The Problem with Threads</a> for an explanation why they aren't a good abstraction for concurrent programming.</p>
| 1 | 2009-06-02T14:18:48Z | [
"python",
"multithreading"
] |
Threading In Python | 939,754 | <p>I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?</p>
| 6 | 2009-06-02T14:03:16Z | 939,849 | <p>You might consider using microthreads if you need concurrency. There's a good article on the subject <a href="http://www.ibm.com/developerworks/library/l-pythrd.html" rel="nofollow">here</a>. The advantage is that you're not creating "real" threads that eat up resources and cause context switching. Of course the downside is that you're not taking advantage of multicore technology.</p>
<p>This is the approach <a href="http://www.kamaelia.org/Home" rel="nofollow">Kamaelia</a> and <a href="http://www.stackless.com/" rel="nofollow">stackless</a> take.</p>
<p>If you're doing I/O, you might consider using asynchronous I/O as well. This can be a real pain to program, but it prevents you from having threads fight over CPU time. Unfortunately, I don't know of any platform independent way to do this in Python.</p>
| 2 | 2009-06-02T14:20:53Z | [
"python",
"multithreading"
] |
Threading In Python | 939,754 | <p>I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?</p>
| 6 | 2009-06-02T14:03:16Z | 940,379 | <p>Excellent answers all around! I just wanted to add that, if you decide to go with a thread pool (generally advisable if you decide that threads are suitable for your app), you would be well advised to reuse (and possibly adapt) an existing general-purpose implementation, such as <a href="http://chrisarndt.de/projects/threadpool/" rel="nofollow">Christopher Arndt's</a>, rather than roll your own from scratch (which is always an instructive undertaking, to be sure, but less productive in terms of time it takes to get you properly working and debugged code;-).</p>
| 1 | 2009-06-02T16:05:38Z | [
"python",
"multithreading"
] |
Threading In Python | 939,754 | <p>I'm new to threading and was wondering if it's bad to spawn a lot of threads for various tasks (in a server environment). Do threads take up a lot more memory/cpu compared to more linear programming?</p>
| 6 | 2009-06-02T14:03:16Z | 941,253 | <p>Since you're new to threading, there's something else worth bearing in mind - which I prefer to view as parallel scoping of values.</p>
<p>With traditional linear/sequential programming for any given object you only have one thread accessing and changing a piece of data. This is generally made safe due to having lexical scope. Specifically one function can operate on a variable's value without affect a global value. If you don't have lexical scope, or poor lexical scoping, then changing the value of a variable named "foo" in one function affects another called "foo". It's less commonly a problem these days, but still common enough to be alluding to.</p>
<p>With threading, you have the same issue, in more subtle ways. Whilst you still have lexical scoping helping you - in that a local value "X" inside one function is independent of another local value called "X" in another, the fact that data structures are mutable is a major source of bugs in threading.</p>
<p>Specifically, if a function is passed a mutable value, then in a threaded environment unless you have taken care, that function cannot guarantee that the value is not being changed by anything else.</p>
<p>This shared state is the source of probably 90-99% of bugs in threaded systems, and can be very hard to debug. As a result, if you're going to write a threaded system you should try to bear in mind the distance that your shared values will travel - ie the scope of parallel access.</p>
<p>In order to limit bugs you have a handful of options which are known to work:</p>
<ol>
<li>Use no shared state - pass shared data using thread safe queues</li>
<li>Place locks around all shared data, and ensure this is used religiously throughout your code. This can be far harder sometimes than people think. The problem comes from when you "forget" to lock an object - something which is remarkably easy for people to do.</li>
<li>Have a single object - an owner - in charge of shared state. Allow client threads to ask it for copies of values in the shared state, which are accompanied by a token. When they want to update the shared state, they pass back messages to the single object, along with the token they had. The owner can then determine whether an update clash has occured.</li>
</ol>
<p>1 is most equivalent to unix pipelines. 3 is logically equivalent to version control, and is normally referred to as software transactional memory.</p>
<p>1 & 3 are modes of concurrency supported in Kamaelia which aims to eliminate bugs caused by class 2. (disclosure, I run the Kamaelia project) 2 isn't supported because it relies on "always getting everything right".</p>
<p>No matter which approach you use to solve your problem though, bearing in mind this issue, and the ways of dealing with it, and planning upfront how you intend to deal with it will save you no end of headaches later on.</p>
| 5 | 2009-06-02T18:51:34Z | [
"python",
"multithreading"
] |
print vs stderr | 939,866 | <p>Are there any specific advantages or disadvantages to either <code>print</code> or <code>stderr</code>?</p>
| 23 | 2009-06-02T14:25:54Z | 939,887 | <p>They're just two different things. <code>print</code> generally goes to <code>sys.stdout</code>. It's worth knowing the difference between <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow"><code>stdin</code>, <code>stdout</code>, and <code>stderr</code></a> - they all have their uses.</p>
<p>In particular, <code>stdout</code> should be used for normal program output, whereas <code>stderr</code> should be reserved only for error messages (abnormal program execution). There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors.</p>
| 30 | 2009-06-02T14:29:35Z | [
"python",
"printing",
"stderr"
] |
print vs stderr | 939,866 | <p>Are there any specific advantages or disadvantages to either <code>print</code> or <code>stderr</code>?</p>
| 23 | 2009-06-02T14:25:54Z | 939,902 | <p><code>print</code> can print on any file-like object, including <code>sys.stderr</code>.</p>
<pre><code>print >> sys.stderr, 'Text'
</code></pre>
<p>The advantages of using <code>sys.stderr</code> for errors instead of <code>sys.stdout</code> are:</p>
<ul>
<li>If the user redirected stdout to a file, she still sees errors on the screen.</li>
<li>It's not buffered, so if <code>sys.stderr</code> is redirected to a log file there are less chance that the program may crash before the error was logged.</li>
</ul>
<hr>
<p>This answer written with Python 2 in mind.
For Python 3, use <code>print('Text', file=sys.stderr)</code> instead.</p>
| 74 | 2009-06-02T14:31:45Z | [
"python",
"printing",
"stderr"
] |
print vs stderr | 939,866 | <p>Are there any specific advantages or disadvantages to either <code>print</code> or <code>stderr</code>?</p>
| 23 | 2009-06-02T14:25:54Z | 2,411,107 | <p>Be careful: there are some subtleties here, including whether or not the streams are going to interactive devices. The biggest surprise is that in Python 3 stderr is line buffered (at least in Unix). For example, in a terminal window, the following prints a number every two seconds in Python 2:</p>
<pre><code>for n in range(5):
print >> sys.stderr, n, # final comma to squelch newline character
time.sleep(2)
</code></pre>
<p>whereas in Python 3, the following prints the numbers all together when the loop finishes:</p>
<pre><code>for n in range(5):
print(n, file=sys.stderr, end='') # print n to sys.stderr with no newline char
time.sleep(2)
</code></pre>
| 28 | 2010-03-09T17:33:44Z | [
"python",
"printing",
"stderr"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.