title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
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, &amp;ifreq) // C version ...
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 Tr...
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 s...
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'...
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_...
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 mai...
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 bu...
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> ...
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 bu...
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></l...
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 bu...
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 ...
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 bu...
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 ...
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 bu...
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 insta...
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 bu...
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...
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 stil...
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 t...
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 stil...
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 a...
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>&gt;&gt;&gt; -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 lan...
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>&gt;&gt;&gt; -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 lan...
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 lik...
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>&gt;&gt;&gt; -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 lan...
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...
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>&gt;&gt;&gt; -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 lan...
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>&gt;&gt;&gt; -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 lan...
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.Boun...
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() s...
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.Boun...
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) t...
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.Boun...
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.Boun...
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 t...
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.Boun...
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.BoundedSem...
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:...
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:...
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>...
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</...
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 t...
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</...
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 ...
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()</co...
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>&gt;&gt;&gt; za = re.compile('z\w') &gt;&gt;&gt; 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> inst...
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()</co...
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...
-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()</co...
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()</co...
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 o...
-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 doe...
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 v...
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 doe...
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-...
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 doe...
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 doe...
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 doe...
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(de...
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 doe...
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 doe...
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 doe...
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): ...
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 doe...
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_...
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> ...
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 thi...
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 ...
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 for...
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> ...
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 for...
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 appr...
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 for...
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...
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 for...
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, str...
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 for...
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 &lt;- read-char (stream))): sign &lt;- -1 else: number &lt;- parse-integer (c) while number? (c &lt;- read-char (stream)): ...
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...
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 ...
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...
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} 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 ha...
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> <...
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 construct...
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> <...
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 f...
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> <...
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...
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> <...
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 a...
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> <...
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 initialisa...
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> <...
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") d...
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> <...
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 th...
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> <...
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>a...
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>a...
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...
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>a...
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">djan...
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...
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...
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...
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 synt...
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...
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...
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...
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 s...
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...
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 <c...
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...
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 undefin...
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...
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...
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...
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 cach...
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_P...
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>&gt;&gt;&gt; resource.g...
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...
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, bu...
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>&gt;&gt;&gt; client = gdata.youtube.service.YouTubeService() &gt;&gt;&gt; video = client.GetYouTubeVideoEntry(video...
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...
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...
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") </cod...
-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...
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.decod...
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...
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 ep...
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 graphi...
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...
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 graphi...
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_col...
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] =&gt; '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] =&gt; '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 ...
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 ...
9
2009-06-02T13:13:22Z
939,447
<p>They're decorators.</p> <p><code>&lt;shameless plug&gt;</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>&lt;/shameless plug&gt;</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 ...
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 ...
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 "&lt;i&gt;" + f...
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. ...
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 Inte...
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 glob...
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="ht...
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 ...
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/project...
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 le...
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...
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 &gt;&gt; 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 st...
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...
28
2010-03-09T17:33:44Z
[ "python", "printing", "stderr" ]