title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
6
2009-02-17T18:22:07Z
558,392
13
2009-02-17T19:32:42Z
[ "regex", "string", "format", "python" ]
I have a string in the format: ``` t='@abc @def Hello this part is text' ``` I want to get this: ``` l=["abc", "def"] s='Hello this part is text' ``` I did this: ``` a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] ``` It works for the most...
Building unashamedly on MrTopf's effort: ``` import re rx = re.compile("((?:@\w+ +)+)(.*)") t='@abc @def @xyz Hello this part is text and my email is foo@ba.r' a,s = rx.match(t).groups() l = re.split('[@ ]+',a)[1:-1] print l print s ``` prints: > ['abc', 'def', 'xyz'] > Hello this part is text and my email is f...
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
6
2009-02-17T18:22:07Z
558,393
7
2009-02-17T19:32:42Z
[ "regex", "string", "format", "python" ]
I have a string in the format: ``` t='@abc @def Hello this part is text' ``` I want to get this: ``` l=["abc", "def"] s='Hello this part is text' ``` I did this: ``` a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] ``` It works for the most...
``` t='@abc @def Hello this part is text' words = t.split(' ') names = [] while words: w = words.pop(0) if w.startswith('@'): names.append(w[1:]) else: break text = ' '.join(words) print names print text ```
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
13
2009-02-17T18:49:20Z
558,289
8
2009-02-17T19:07:04Z
[ "python", "math", "floating-point", "numpy" ]
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to *n* significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results: ``` def nearlyequal( a, b, sigfig=5 ): ``` The purpose of this function is to deter...
Here's a take. ``` def nearly_equal(a,b,sig_fig=5): return ( a==b or int(a*10**sig_fig) == int(b*10**sig_fig) ) ```
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
13
2009-02-17T18:49:20Z
558,322
16
2009-02-17T19:16:25Z
[ "python", "math", "floating-point", "numpy" ]
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to *n* significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results: ``` def nearlyequal( a, b, sigfig=5 ): ``` The purpose of this function is to deter...
There is a function `assert_approx_equal` in `numpy.testing` (source [here)](https://github.com/numpy/numpy/blob/1225aef37298ec82048d0828f6cb7e0be8ed58cc/numpy/testing/utils.py#L513) which may be a good starting point. ``` def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): """ Raise...
Bayesian spam filtering library for Python
558,219
19
2009-02-17T18:50:18Z
558,405
11
2009-02-17T19:35:52Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong). Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering? Thanks in advance. **Clarification**:...
Do you want spam filtering or Bayesian classification? For Bayesian classification there are a number of Python modules. I was just recently reviewing [Orange](http://www.ailab.si/orange/) which looks very impressive. R has a number of Bayesian modules. You can use [Rpy](http://rpy.sourceforge.net/) to hook into R.
Bayesian spam filtering library for Python
558,219
19
2009-02-17T18:50:18Z
561,654
12
2009-02-18T15:50:37Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong). Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering? Thanks in advance. **Clarification**:...
Try [Reverend](http://bazaar.launchpad.net/~divmod-dev/divmod.org/trunk/files/head:/Reverend/). It's a spam filtering module.
Bayesian spam filtering library for Python
558,219
19
2009-02-17T18:50:18Z
11,917,279
8
2012-08-11T20:11:51Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong). Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering? Thanks in advance. **Clarification**:...
RedisBayes looks good to me: <http://pypi.python.org/pypi/redisbayes/0.1.3> In my experience Redis is an awesome addition to your stack and can help process data at blazing fast speeds compared to MySQL, PostgreSQL or any other RDBMS. ``` import redis, redisbayes rb = redisbayes.RedisBayes(redis=redis.Redis()) rb.t...
Check whether a PDF-File is valid (Python)
559,096
10
2009-02-17T22:53:27Z
559,176
7
2009-02-17T23:19:52Z
[ "python", "file", "pdf" ]
**I get a File via a HTTP-Upload and need to be sure its a pdf-file.** Programing Language is Python, but this should not matter. I thought of the following solutions: 1. Check if the first bytes of the string are "%PDF". *This is not a good check but prevents the use from uploading other files accidentally.* 2. Try ...
In a project if mine I need to check for the mime type of some uploaded file. I simply use the file command like this: ``` from subprocess import Popen, PIPE filetype = Popen("/usr/bin/file -b --mime -", shell=True, stdout=PIPE, stdin=PIPE).communicate(file.read(1024))[0].strip() ``` You of course might want to move ...
Check whether a PDF-File is valid (Python)
559,096
10
2009-02-17T22:53:27Z
559,442
9
2009-02-18T01:10:35Z
[ "python", "file", "pdf" ]
**I get a File via a HTTP-Upload and need to be sure its a pdf-file.** Programing Language is Python, but this should not matter. I thought of the following solutions: 1. Check if the first bytes of the string are "%PDF". *This is not a good check but prevents the use from uploading other files accidentally.* 2. Try ...
The two most commonly used PDF libraries for Python are: * [pyPdf](http://pybrary.net/pyPdf/) * [ReportLab](http://www.reportlab.org/downloads.html) Both are pure python so should be easy to install as well be cross-platform. With pyPdf it would probably be as simple as doing: ``` from pyPdf import PdfFileReader do...
How do I validate the MX record for a domain in python?
559,436
13
2009-02-18T01:06:20Z
559,479
16
2009-02-18T01:25:06Z
[ "python", "email", "dns" ]
I have a large number of email addresses to validate. Initially I parse them with a regexp to throw out the completely crazy ones. I'm left with the ones that look sensible but still might contain errors. I want to find which addresses have valid domains, so given me@abcxyz.com I want to know if it's even possible to ...
There is no DNS interface in the standard library so you will either have to roll your own or use a third party library. This is not a fast-changing concept though, so the external libraries are stable and well tested. The one I've used successful for the same task as your question is [PyDNS](http://pydns.sourceforge...
Django - queries made repeat/inefficient
559,701
2
2009-02-18T03:12:29Z
559,708
7
2009-02-18T03:18:27Z
[ "python", "django" ]
Alright, I have a Django view, like this: ``` @render_to('home/main.html') def login(request): # also tried Client.objects.select_related().all() clients = Client.objects.all() return {'clients':clients} ``` And I have a template, `main.html`, like this: ``` <ul> {% for client in clients %} <li>{{ client...
Django uses a cache. The RDBMS uses a cache. Don't prematurely optimize the queries. You can play with bulk queries in your view function instead of one-at-a-time queries in your template. ``` @render_to('home/main.html') def login(request): # Query all clients clients = Client.objects.all() # Assemble a...
Conditional compilation in Python
560,040
10
2009-02-18T06:26:54Z
560,044
21
2009-02-18T06:30:22Z
[ "python", "conditional-compilation" ]
How to do conditional compilation in Python ? Is it using DEF ?
Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.1 You can do something equivalent to conditional compile by just using an if statement. For example: ``` if FLAG: def f(): ...
Conditional compilation in Python
560,040
10
2009-02-18T06:26:54Z
561,338
15
2009-02-18T14:47:12Z
[ "python", "conditional-compilation" ]
How to do conditional compilation in Python ? Is it using DEF ?
There is actually a way to get conditional compilation, but it's very limited. ``` if __debug__: doSomething() ``` The `__debug__` flag is a special case. When calling python with the `-O` or `-OO` options, `__debug__` will be false, and the compiler will ignore that statement. This is used primarily with asserts...
Implementing chat in an application?
561,301
3
2009-02-18T14:38:01Z
561,313
10
2009-02-18T14:40:42Z
[ "python", "chat" ]
I'm making a game and I am using Python for the server side. It would be fairly trivial to implement chat myself using Python - that's not my question. **My question is** I was just wondering if there were any pre-made chat servers or some kind of service that I would be able to implement inside of my game instead...
I recommend using XMPP/Jabber. There are a lot of libraries for clients and servers in different languages. It's free/open source. <http://en.wikipedia.org/wiki/XMPP>
How to convert an integer to the shortest url-safe string in Python?
561,486
60
2009-02-18T15:25:25Z
561,630
7
2009-02-18T15:48:31Z
[ "python", "url", "base64" ]
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the ...
You don't want base64 encoding, you want to represent a base 10 numeral in numeral base X. If you want your base 10 numeral represented in the 26 letters available you could use: <http://en.wikipedia.org/wiki/Hexavigesimal>. (You can extend that example for a much larger base by using all the legal url characters) Yo...
How to convert an integer to the shortest url-safe string in Python?
561,486
60
2009-02-18T15:25:25Z
561,631
8
2009-02-18T15:48:31Z
[ "python", "url", "base64" ]
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the ...
The easy bit is converting the byte string to web-safe base64: ``` import base64 output = base64.urlsafe_b64encode(s) ``` The tricky bit is the first step - convert the integer to a byte string. If your integers are small you're better off hex encoding them - see [saua](http://stackoverflow.com/questions/561486/how-...
How to convert an integer to the shortest url-safe string in Python?
561,486
60
2009-02-18T15:25:25Z
561,704
54
2009-02-18T16:00:18Z
[ "python", "url", "base64" ]
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the ...
This answer is similar in spirit to Douglas Leeder's, with the following changes: * It doesn't use actual Base64, so there's no padding characters * Instead of converting the number first to a byte-string (base 256), it converts it directly to base 64, which has the advantage of letting you represent negative numbers ...
How to convert an integer to the shortest url-safe string in Python?
561,486
60
2009-02-18T15:25:25Z
561,809
9
2009-02-18T16:22:44Z
[ "python", "url", "base64" ]
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the ...
To encode `n`: ``` data = '' while n > 0: data = chr(n & 255) + data n = n >> 8 encoded = base64.urlsafe_b64encode(data).rstrip('=') ``` To decode `s`: ``` data = base64.urlsafe_b64decode(s + '===') decoded = 0 while len(data) > 0: decoded = (decoded << 8) | ord(data[0]) data = data[1:] ``` In the s...
How to convert an integer to the shortest url-safe string in Python?
561,486
60
2009-02-18T15:25:25Z
561,875
13
2009-02-18T16:40:37Z
[ "python", "url", "base64" ]
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the ...
You probably do not want real base64 encoding for this - it will add padding etc, potentially even resulting in larger strings than hex would for small numbers. If there's no need to interoperate with anything else, just use your own encoding. Eg. here's a function that will encode to any base (note the digits are actu...
How to convert an integer to the shortest url-safe string in Python?
561,486
60
2009-02-18T15:25:25Z
18,001,426
18
2013-08-01T18:08:21Z
[ "python", "url", "base64" ]
I want the shortest possible way of representing an integer in a URL. For example, 11234 can be shortened to '2be2' using hexadecimal. Since base64 uses is a 64 character encoding, it should be possible to represent an integer in base64 using even less characters than hexadecimal. The problem is I can't figure out the ...
All the answers given regarding Base64 are very reasonable solutions. But they're technically incorrect. To convert an integer to the *shortest URL safe string* possible, what you want is base 66 (there are [66 URL safe characters](http://tools.ietf.org/html/rfc3986#section-2.3)). That code looks like this: ``` from ...
Python Imaging Library save function syntax
562,519
11
2009-02-18T19:38:57Z
562,530
15
2009-02-18T19:43:19Z
[ "python", "python-imaging-library" ]
Simple one I think but essentially I need to know what the syntax is for the save function on the PIL. The help is really vague and I can't find anything online. Any help'd be great, thanks :).
From the [PIL Handbook](http://effbot.org/imagingbook/image.htm#tag-Image.Image.save): ``` im.save(outfile, options...) im.save(outfile, format, options...) ``` Simplest case: ``` im.save('my_image.png') ``` or whatever. In this case, the type of the image will be determined from the extension. Is there a particul...
What's Python good practice for importing and offering optional features?
563,022
12
2009-02-18T21:58:01Z
563,060
25
2009-02-18T22:05:59Z
[ "python", "python-import" ]
I'm writing a piece of software over on github. It's basically a tray icon with some extra features. I want to provide a working piece of code without actually having to make the user install what are essentially dependencies for optional features and I don't actually want to import things I'm not going to use so I tho...
The `try:` method does not need to be global — it can be used in any scope and so modules can be "lazy-loaded" at runtime. For example: ``` def foo(): try: import external_module except ImportError: pass if external_module: external_module.some_whizzy_feature() else: ...
What's Python good practice for importing and offering optional features?
563,022
12
2009-02-18T21:58:01Z
563,075
7
2009-02-18T22:09:38Z
[ "python", "python-import" ]
I'm writing a piece of software over on github. It's basically a tray icon with some extra features. I want to provide a working piece of code without actually having to make the user install what are essentially dependencies for optional features and I don't actually want to import things I'm not going to use so I tho...
You might want to have a look at the [imp module](http://docs.python.org/library/imp.html), which basically does what you do manually above. So you can first look for a module with find\_module() and then load it via load\_module() or by simply importing it (after checking the config). And btw, if using except: I alwa...
Getting return values from a MySQL stored procedure in Python, using MySQLdb
563,182
6
2009-02-18T22:42:25Z
566,260
9
2009-02-19T17:11:44Z
[ "python", "mysql" ]
I've got a stored procedure in a MySQL database that simply updates a date column and returns the previous date. If I call this stored procedure from the MySQL client, it works fine, but when I try to call the stored procedure from Python using MySQLdb I can't seem to get it to give me the return value. Here's the cod...
What I had to do is modify the Python code to use execute() instead of callproc(), and then use the fetchone() to get the results. I'm answering it myself since mluebke's answer wasn't entirely complete (even though it was helpful!). ``` mysql_cursor.execute( "call get_lastpoll();" ) results=mysql_cursor.fetchone() pr...
What's the fastest way to test the validity of a large number of well-formed URLs
563,384
2
2009-02-18T23:46:48Z
563,412
7
2009-02-18T23:59:04Z
[ "python", "http" ]
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs I want to be able to filter these URLs quickly ...
To really make this fast you might also use [eventlet](http://pypi.python.org/pypi/eventlet) which uses non-blocking IO to speed things up. You can use a head request like this: ``` from eventlet import httpc try: res = httpc.head(url) except httpc.NotFound: # handle 404 ``` You can then put this into some s...
How to stop Tkinter Frame from shrinking to fit its contents?
563,827
27
2009-02-19T03:21:07Z
566,840
37
2009-02-19T19:42:43Z
[ "python", "label", "tkinter", "frame" ]
This is the code that's giving me trouble. ``` f = Frame(root, width=1000, bg="blue") f.pack(fill=X, expand=True) l = Label(f, text="hi", width=10, bg="red", fg="white") l.pack() ``` If I comment out the lines with the Label, the Frame displays with the right width. However, adding the Label seems to shrink the Fram...
By default, tk frames *shrink or grow to fit their contents*, which is what you want 99% of the time. The term that describes this feature is "geometry propagation". There is a [command](http://effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack_propagate-method) to turn geometry propagation on or off. Since you are usi...
How can I check the memory usage of objects in iPython?
563,840
15
2009-02-19T03:27:34Z
563,921
13
2009-02-19T04:07:23Z
[ "python", "memory", "ipython" ]
I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance: ``` In [1]: a = range(10000) In [2]: %memusage a Out[2]: 1MB ``` Something like `%memusage <object>` and return the memory used by the object. **Duplicate** > [Fin...
UPDATE: Here is [another](http://code.activestate.com/recipes/544288/), maybe more thorough recipe for estimating the size of a python object. Here is a [thread](http://mail.python.org/pipermail/python-list/2008-January/472683.html) addressing a similar question The solution proposed is to write your own... using som...
How can I check the memory usage of objects in iPython?
563,840
15
2009-02-19T03:27:34Z
565,382
22
2009-02-19T13:50:09Z
[ "python", "memory", "ipython" ]
I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance: ``` In [1]: a = range(10000) In [2]: %memusage a Out[2]: 1MB ``` Something like `%memusage <object>` and return the memory used by the object. **Duplicate** > [Fin...
Unfortunately this is not possible, but there are a number of ways of approximating the answer: 1. for very simple objects (e.g. ints, strings, floats, doubles) which are represented more or less as simple C-language types you can simply calculate the number of bytes as with [John Mulder's solution](http://stackoverfl...
How can I check the memory usage of objects in iPython?
563,840
15
2009-02-19T03:27:34Z
15,591,157
11
2013-03-23T19:30:46Z
[ "python", "memory", "ipython" ]
I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance: ``` In [1]: a = range(10000) In [2]: %memusage a Out[2]: 1MB ``` Something like `%memusage <object>` and return the memory used by the object. **Duplicate** > [Fin...
If you are using a [numpy array](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html), then you can use the attribute `ndarray.nbytes` to evaluate its size in memory: ``` from pylab import * d = array([2,3,4,5]) d.nbytes #Output: 32 ```
Is there a way to change effective process name in Python?
564,695
50
2009-02-19T10:37:12Z
565,071
9
2009-02-19T12:26:14Z
[ "python", "process", "arguments", "hide", "ps" ]
Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set ``` strcpy(argv[0],"othername"); ``` But in Python ``` argv[0] = "othername" ``` doesn't seem to work. When i get process list (with `ps ...
Simply put, there's no portable way. You'll have to test for the system and use the preferred method for that system. Further, I'm confused about what you mean by process names on Windows. Do you mean a service name? I presume so, because nothing else really makes any sense (at least to my non-Windows using brain). ...
Is there a way to change effective process name in Python?
564,695
50
2009-02-19T10:37:12Z
923,034
37
2009-05-28T20:39:05Z
[ "python", "process", "arguments", "hide", "ps" ]
Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set ``` strcpy(argv[0],"othername"); ``` But in Python ``` argv[0] = "othername" ``` doesn't seem to work. When i get process list (with `ps ...
actually you need 2 things on linux: modify `argv[0]` from `C` (for `ps auxf` and friends) and call `prctl` with `PR_SET_NAME` flag. There is absolutely no way to do first piece from python itself. Although, you can just change process name by calling prctl. ``` def set_proc_name(newname): from ctypes import cdll...
Is there a way to change effective process name in Python?
564,695
50
2009-02-19T10:37:12Z
1,866,700
62
2009-12-08T12:40:46Z
[ "python", "process", "arguments", "hide", "ps" ]
Can I change effective process name of a Python script? I want to show a different name instead of the real name of the process when I get the system process list. In C I can set ``` strcpy(argv[0],"othername"); ``` But in Python ``` argv[0] = "othername" ``` doesn't seem to work. When i get process list (with `ps ...
I've recently written a Python module to change the process title in a portable way: check <https://github.com/dvarrazzo/py-setproctitle> It is a wrapper around the code used by PostgreSQL to perform the title change. It is currently tested against Linux and Mac OS X: Windows (with limited functionality) and BSD porti...
How can I make this one-liner work in DOS?
566,559
5
2009-02-19T18:29:30Z
566,563
12
2009-02-19T18:31:50Z
[ "python", "command-line" ]
``` python -c "for x in range(1,10) print x" ``` I enjoy python one liners with -c, but it is limited when indentation is needed. Any ideas?
``` python -c "for x in range(1,10): print x" ``` Just add the colon. To address the question in the comments: > How can I make this work though? python -c "import calendar;print calendar.prcal(2009);for x in range(1,10): print x" ``` python -c "for x in range(1,10): x==1 and __import__('calendar').prcal(2009); pri...
How to get console window width in python
566,746
151
2009-02-19T19:17:19Z
566,752
63
2009-02-19T19:18:11Z
[ "python", "linux", "console", "terminal", "width" ]
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. **Edit** Looking for a solution that works on Linux
use ``` import console (width, height) = console.getTerminalSize() print "Your terminal's width is: %d" % width ``` **EDIT**: oh, I'm sorry. That's not a python standard lib one, here's the source of console.py (I don't know where it's from). The module seems to work like that: It checks if `termcap` is available, ...
How to get console window width in python
566,746
151
2009-02-19T19:17:19Z
943,921
175
2009-06-03T09:59:34Z
[ "python", "linux", "console", "terminal", "width" ]
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. **Edit** Looking for a solution that works on Linux
``` import os rows, columns = os.popen('stty size', 'r').read().split() ``` uses the 'stty size' command which according to [a thread on the python mailing list](http://mail.python.org/pipermail/python-list/2000-May/033312.html) is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from...
How to get console window width in python
566,746
151
2009-02-19T19:17:19Z
3,010,495
39
2010-06-09T22:36:38Z
[ "python", "linux", "console", "terminal", "width" ]
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. **Edit** Looking for a solution that works on Linux
Code above didn't return correct result on my linux because winsize-struct has 4 unsigned shorts, not 2 signed shorts: ``` def terminal_size(): import fcntl, termios, struct h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))) return w, h...
How to get console window width in python
566,746
151
2009-02-19T19:17:19Z
6,550,596
32
2011-07-01T16:23:02Z
[ "python", "linux", "console", "terminal", "width" ]
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. **Edit** Looking for a solution that works on Linux
I searched around and found a solution for windows at : <http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/> and a solution for linux here. So here is a version which works both on linux, os x and windows/cygwin : ``` """ getTerminalSize() - get width and height of console - w...
How to get console window width in python
566,746
151
2009-02-19T19:17:19Z
14,422,538
93
2013-01-20T07:25:34Z
[ "python", "linux", "console", "terminal", "width" ]
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. **Edit** Looking for a solution that works on Linux
Not sure why it is in the module `shutil`, but it landed there in Python 3.3, [Querying the size of the output terminal](http://docs.python.org/3/library/shutil.html#querying-the-size-of-the-output-terminal): ``` >>> import shutil >>> shutil.get_terminal_size((80, 20)) # pass fallback os.terminal_size(columns=87, lin...
How to get console window width in python
566,746
151
2009-02-19T19:17:19Z
23,330,276
10
2014-04-27T23:24:31Z
[ "python", "linux", "console", "terminal", "width" ]
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. **Edit** Looking for a solution that works on Linux
Starting at Python 3.3 it is straight forward: <https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal> ``` >>> import os >>> ts = os.get_terminal_size() >>> ts.lines 24 >>> ts.columns 80 ```
Simple Prime Generator in Python
567,222
21
2009-02-19T21:22:24Z
568,618
108
2009-02-20T07:42:03Z
[ "python", "primes" ]
could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln. ``` import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if ...
There are some problems: * Why do you print out count when it didn't divide by x? It doesn't mean it's prime, it means only that this particular x doesn't divide it * `continue` moves to the next loop iteration - but you really want to stop it using `break` Here's your code with a few fixes, it prints out only primes...
Simple Prime Generator in Python
567,222
21
2009-02-19T21:22:24Z
568,684
8
2009-02-20T08:13:32Z
[ "python", "primes" ]
could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln. ``` import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if ...
``` def is_prime(num): """Returns True if the number is prime else False.""" if num == 0 or num == 1: return False for x in range(2, num): if num % x == 0: return False else: return True >> filter(is_prime, range(1, 20)) [2, 3, 5, 7, 11, 13, 17, 19] ``` We wil...
Simple Prime Generator in Python
567,222
21
2009-02-19T21:22:24Z
2,624,386
7
2010-04-12T18:28:58Z
[ "python", "primes" ]
could someone please tell me what I'm doing wrong with this code. It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy). Thanks a lot. lincoln. ``` import math def main(): count = 3 one = 1 while one == 1: for x in range(2, int(math.sqrt(count) + 1)): if ...
``` print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]] ```
Is it safe to use Python UUID module generated values in URL's of a webpage?
567,324
2
2009-02-19T21:47:29Z
567,347
7
2009-02-19T21:51:42Z
[ "python", "url", "uuid" ]
Is it safe to use Python UUID module generated values in URL's of a webpage? Wnat to use those ID's as part of URL's. Are there any non-safe characters ever generated by Python UUID that shouldn't be in URL's?
It is good practice to **always** urlencode data that will be placed into URLs. Then you need not be concerned with the specifics of UUID or if it will change in the future.
running a command as a super user from a python script
567,542
19
2009-02-19T22:33:16Z
567,599
11
2009-02-19T22:46:38Z
[ "python", "subprocess", "sudo" ]
So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like ``` proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ...
Try giving the full path to apache2ctl.
running a command as a super user from a python script
567,542
19
2009-02-19T22:33:16Z
567,687
14
2009-02-19T23:11:30Z
[ "python", "subprocess", "sudo" ]
So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like ``` proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ...
Try: `subprocess.call(['sudo', 'apach2ctl', 'restart'])` The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself. If you don't define them, then it grabs sys.stdout, etc...
is there a pythonic way to try something up to a maximum number of times?
567,622
59
2009-02-19T22:52:01Z
567,645
55
2009-02-19T23:00:09Z
[ "python", "exception-handling" ]
I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error: ``` _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') ``` If you try the query again immediately afterwards, it usually succeeds. So, I'...
How about: ``` conn = MySQLdb.connect(host, user, password, database) cursor = conn.cursor() attempts = 0 while attempts < 3: try: cursor.execute(query) rows = cursor.fetchall() for row in rows: # do something with the data break except MySQLdb.Error, e: att...
is there a pythonic way to try something up to a maximum number of times?
567,622
59
2009-02-19T22:52:01Z
567,697
65
2009-02-19T23:16:22Z
[ "python", "exception-handling" ]
I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error: ``` _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') ``` If you try the query again immediately afterwards, it usually succeeds. So, I'...
Building on Dana's answer, you might want to do this as a decorator: ``` def retry(howmany): def tryIt(func): def f(): attempts = 0 while attempts < howmany: try: return func() except: attempts += 1 retu...
How can I process command line arguments in Python?
567,879
18
2009-02-20T00:41:02Z
567,899
15
2009-02-20T00:51:36Z
[ "python", "command-line", "command-line-arguments" ]
What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected? I understand if for example I need to find out if "debug" was passed among p...
Have a look at the [optparse](http://docs.python.org/library/optparse.html) module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly. Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace `debug` with `--debug` and `xl...
How can I process command line arguments in Python?
567,879
18
2009-02-20T00:41:02Z
567,923
25
2009-02-20T01:02:40Z
[ "python", "command-line", "command-line-arguments" ]
What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected? I understand if for example I need to find out if "debug" was passed among p...
As others answered, optparse is the best option, but if you just want quick code try something like this: ``` import sys, re first_re = re.compile(r'^\d{3}$') if len(sys.argv) > 1: if first_re.match(sys.argv[1]): print "Primary argument is : ", sys.argv[1] else: raise ValueError("First argum...
How to check if there exists a process with a given pid?
568,271
53
2009-02-20T04:22:43Z
568,285
90
2009-02-20T04:31:14Z
[ "python", "process", "pid" ]
Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from `os.getpid()` and I need to check to see if a process with that pid doesn't exist on the machine. I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT i...
Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise. ``` import os def check_pid(pid): """ Check For the existence of a unix pid. """ try: os.kill(pid, 0) except OSError: return False else: return True ```
How to check if there exists a process with a given pid?
568,271
53
2009-02-20T04:22:43Z
6,940,314
38
2011-08-04T11:08:51Z
[ "python", "process", "pid" ]
Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from `os.getpid()` and I need to check to see if a process with that pid doesn't exist on the machine. I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT i...
mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work: (edited as per Jason R. Coombs comments) ``` import errno import os import sys def pid_exists(pid): """Check whether pid exists in the current process table...
How to check if there exists a process with a given pid?
568,271
53
2009-02-20T04:22:43Z
17,622,447
28
2013-07-12T19:16:25Z
[ "python", "process", "pid" ]
Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from `os.getpid()` and I need to check to see if a process with that pid doesn't exist on the machine. I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT i...
Have a look at the [`psutil`](https://pypi.python.org/pypi/psutil) module: > **psutil** (python system and process utilities) is a cross-platform library for retrieving information on **running processes** and **system utilization** (CPU, memory, disks, network) in Python. [...] It currently supports **Linux**, **Wind...
How do I create an empty array/matrix in NumPy?
568,962
103
2009-02-20T09:58:11Z
569,063
162
2009-02-20T10:36:46Z
[ "python", "arrays", "numpy" ]
I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time. At the moment the only way I can find to do this is like: ``` mat = None for col in columns: if mat is None: mat = col...
You have the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. If you want to add rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored. This is very inefficient if done re...
How do I create an empty array/matrix in NumPy?
568,962
103
2009-02-20T09:58:11Z
569,090
42
2009-02-20T10:44:19Z
[ "python", "arrays", "numpy" ]
I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time. At the moment the only way I can find to do this is like: ``` mat = None for col in columns: if mat is None: mat = col...
A NumPy array is a very different data structure from a list and is designed to be used in different ways. Your use of `hstack` is potentially very inefficient... every time you call it, all the data in the existing array is copied into a new one. (The `append` function will have the same issue.) If you want to build u...
How do I create an empty array/matrix in NumPy?
568,962
103
2009-02-20T09:58:11Z
15,926,110
8
2013-04-10T12:39:58Z
[ "python", "arrays", "numpy" ]
I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time. At the moment the only way I can find to do this is like: ``` mat = None for col in columns: if mat is None: mat = col...
I looked into this a lot because I needed to use a numpy.array as a set in one of my school projects and I needed to be initialized empty... I didn't found any relevant answer here on Stack Overflow, so I started doodling something. ``` # Initialize your variable as an empty list first In [32]: x=[] # and now cast it ...
How do I create an empty array/matrix in NumPy?
568,962
103
2009-02-20T09:58:11Z
22,978,734
13
2014-04-10T04:34:58Z
[ "python", "arrays", "numpy" ]
I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time. At the moment the only way I can find to do this is like: ``` mat = None for col in columns: if mat is None: mat = col...
To create an empty multidimensional array in NumPy (e.g. a 2D array `m*n` to store your matrix), in case you don't know `m` how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 the dimension to which yo...
How to programmatically insert comments into a Microsoft Word document?
568,972
9
2009-02-20T10:02:47Z
569,092
7
2009-02-20T10:44:49Z
[ "python", "ms-word", "common-lisp", "openxml" ]
Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and implementable in a non-Windows environment (ideally using Python and/or Common Lisp)...
Here is what I did: 1. Create a simple document with word (i.e. a very small one) 2. Add a comment in Word 3. Save as docx. 4. Use the zip module of python to access the archive (docx files are ZIP archives). 5. Dump the content of the entry "word/document.xml" in the archive. This is the XML of the document itself. ...
Django: multiple models in one template using forms
569,468
85
2009-02-20T12:50:26Z
575,133
56
2009-02-22T16:09:05Z
[ "python", "django", "design", "django-forms" ]
I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creat...
This really isn't too hard to implement with [ModelForms](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms). So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST. ``` if request.POST(): a_valid = formA.is_valid...
Django: multiple models in one template using forms
569,468
85
2009-02-20T12:50:26Z
606,318
19
2009-03-03T13:05:53Z
[ "python", "django", "design", "django-forms" ]
I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creat...
I very recently had the some problem and just figured out how to do this. Assuming you have three classes, Primary, B, C and that B,C have a foreign key to primary ``` class PrimaryForm(ModelForm): class Meta: model = Primary class BForm(ModelForm): class Meta: model = ...
Django: multiple models in one template using forms
569,468
85
2009-02-20T12:50:26Z
985,901
60
2009-06-12T09:50:28Z
[ "python", "django", "design", "django-forms" ]
I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creat...
I just was in about the same situation a day ago, and here are my 2 cents: 1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: <http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/> . In a nutshell: Make a form for each ...
How to keep track of thread progress in Python without freezing the PyQt GUI?
569,650
18
2009-02-20T14:00:06Z
574,130
10
2009-02-22T01:33:00Z
[ "python", "multithreading", "user-interface", "pyqt" ]
## **Questions:** 1. What is the best practice for keeping track of a tread's progress without locking the GUI ("Not Responding")? 2. Generally, what are the best practices for threading as it applies to GUI development? ## **Question Background:** * I have a PyQt GUI for Windows. * It is used to proc...
If you want to use signals to indicate progress to the main thread then you should really be using PyQt's QThread class instead of the Thread class from Python's threading module. A simple example which uses QThread, signals and slots can be found on the PyQt Wiki: <https://wiki.python.org/moin/PyQt/Threading,_Signal...
Lazy choices in Django form
569,696
16
2009-02-20T14:18:37Z
569,748
16
2009-02-20T14:33:58Z
[ "python", "django", "forms", "lazy-evaluation" ]
I have a Django my\_forms.py like this: ``` class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=bodystyle_choices()) ``` Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function. ``` def bodystyle_choices(): return ...
Try using a ModelChoiceField instead of a simple ChoiceField. I think you will be able to achieve what you want by tweaking your models a bit. Take a look at the [docs](http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield) for more. I would also add that ModelChoiceFields are `lazy` by default :)
Lazy choices in Django form
569,696
16
2009-02-20T14:18:37Z
845,140
39
2009-05-10T11:21:16Z
[ "python", "django", "forms", "lazy-evaluation" ]
I have a Django my\_forms.py like this: ``` class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=bodystyle_choices()) ``` Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function. ``` def bodystyle_choices(): return ...
You can use the "lazy" function :) ``` from django.utils.functional import lazy class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)()) ``` very nice util function !
How to tell for which object attribute pickle fails?
569,754
28
2009-02-20T14:36:09Z
570,910
14
2009-02-20T19:30:46Z
[ "python", "serialization" ]
When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like: ``` PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed ``` Is there any way to tell which attribute caused the exception? I am using Python 2....
You could file a bug against Python for not including more helpful error messages. In the meantime, modify the `_reduce_ex()` function in `copy_reg.py`. ``` if base is self.__class__: print self # new raise TypeError, "can't pickle %s objects" % base.__name__ ``` Output: ``` <bound method ?.test_func of <...
How to tell for which object attribute pickle fails?
569,754
28
2009-02-20T14:36:09Z
7,218,986
7
2011-08-28T04:04:50Z
[ "python", "serialization" ]
When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like: ``` PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed ``` Is there any way to tell which attribute caused the exception? I am using Python 2....
I had the same problem as you, but my classes were a bit more complicated (i.e. a large tree of similar objects) so the printing didn't help much so I hacked together a helper function. It is not complete and is only intended for use with pickling protocol 2: It was enough so I could locate my problems. If you want to ...
How do I add plain text info to forms in a formset in Django?
570,522
3
2009-02-20T17:30:00Z
571,334
8
2009-02-20T21:39:03Z
[ "python", "django", "django-forms" ]
I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text. sample template code: ``` {% for form, data in zipped_data %} <div class="row"> <div class="first_col"> <span class="title">{{ data.0 }}</span> ...
Instead of zipping your forms with the additional data, you can override the constructor on your form and hold your title/description as *instance-level* member variables. This is a bit more object-oriented and learning how to do this will help you solve other problems down the road such as dynamic choice fields. ``` ...
Detect when a Python module unloads
570,636
7
2009-02-20T18:00:23Z
570,704
12
2009-02-20T18:19:37Z
[ "python" ]
I have a module that uses ctypes to wrap some functionality from a static library into a class. When the module loads, it calls an initialize function in the static library. When the module is unloaded (presumably when the interpreter exits), there's an unload function in the library that I'd like to be called. How can...
Use the [atexit](http://docs.python.org/library/atexit.html) module: ``` import mymodule import atexit # call mymodule.unload('param1', 'param2') when the interpreter exits: atexit.register(mymodule.unload, 'param1', 'param2') ``` Another simple example from the docs, using [`register`](http://docs.python.org/librar...
Split tags in python
571,186
3
2009-02-20T20:50:04Z
571,238
7
2009-02-20T21:09:48Z
[ "python", "split", "template-engine" ]
I have a file that contains this: ``` <html> <head> <title> Hello! - {{ today }}</title> </head> <body> {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} </body> </html> ``` What is the best or most Pythonic way to extract the `{{today}}`, `{{runner_up}}`, etc.? ...
Mmkay, well here's a generator solution that seems to work well for me. You can also provide different open and close tags if you like. ``` def get_tags(s, open_delim ='{{', close_delim ='}}' ): while True: # Search for the next two delimiters in the source text start = s.find(open_d...
triangle numbers in python
571,488
10
2009-02-20T22:27:36Z
571,526
27
2009-02-20T22:39:49Z
[ "python" ]
I'm trying to solve the problem: > What is the value of the first triangle number to have over five hundred divisors? *A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...* I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate ...
Hints: * what is the formula for `n`-th triangular number? * `n` and `n+1` have no common factors (except `1`). Question: given number of factors in `n` and `n+1` how to calculate number of factors in `n*(n+1)`? What about `n/2` and `(n+1)` (or `n` and `(n+1)/2`)? * if you know all prime factors of `n` how to calculat...
Are there any declaration keywords in Python?
571,514
9
2009-02-20T22:34:34Z
571,546
14
2009-02-20T22:46:25Z
[ "python", "variables" ]
Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement: ``` x = 5; ``` * Creates a new variable. or * Sets an existing one.
An important thing to understand about Python is there are no variables, only "names". In your example, you have an object "5" and you are creating a name "x" that references the object "5". If later you do: ``` x = "Some string" ``` that is still perfectly valid. Name "x" is now pointing to object "Some string". ...
Are there any declaration keywords in Python?
571,514
9
2009-02-20T22:34:34Z
571,610
11
2009-02-20T23:09:54Z
[ "python", "variables" ]
Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement: ``` x = 5; ``` * Creates a new variable. or * Sets an existing one.
It's worth mentioning that there is a global keyword, so if you want to refer to the global x: ``` x = 4 def foo(): x = 7 # x is local to your function ``` You need to do this: ``` x = 4 def foo(): global x # let python know you want to use the top-level x x = 7 ```
Are there any declaration keywords in Python?
571,514
9
2009-02-20T22:34:34Z
571,757
11
2009-02-21T00:21:28Z
[ "python", "variables" ]
Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement: ``` x = 5; ``` * Creates a new variable. or * Sets an existing one.
I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, "how do you know if this statement: creates a new variable or sets an existing variable?" If you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid global varia...
Adding elements to python generators
571,850
15
2009-02-21T01:11:36Z
571,888
13
2009-02-21T01:31:45Z
[ "python", "append", "generator" ]
Is it possible to append elements to a python generator? I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I ...
You are looking for [`itertools.chain`](http://docs.python.org/library/itertools.html). It will combine multiple iterables into a single one, like this: ``` >>> for i in itertools.chain([1,2,3], [4,5,6]): ... print i ... 1 2 3 4 5 6 ```
Adding elements to python generators
571,850
15
2009-02-21T01:11:36Z
571,928
13
2009-02-21T01:54:52Z
[ "python", "append", "generator" ]
Is it possible to append elements to a python generator? I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I ...
This should do it, where `directories` is your list of directories: ``` import os import itertools generators = [os.walk(d) for d in directories] for root, dirs, files in itertools.chain(*generators): print root, dirs, files ```
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
28
2009-02-21T04:18:17Z
2,045,308
30
2010-01-11T22:06:27Z
[ "python", "django", "checkbox" ]
When I define a Django form class similar to this: ``` def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") ``` It expands to HTML that looks like this: ``` <form action="." id="form" method=POST> <p><label for="check">Check this:</label> <input type="checkbox" name="check"...
Here's a solution I've come up with (Django v1.1): ``` {% load myfilters %} [...] {% for field in form %} [...] {% if field.field.widget|is_checkbox %} {{ field }}{{ field.label_tag }} {% else %} {{ field.label_tag }}{{ field }} {% endif %} [...] {% endfor %} ``` You'll need to creat...
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
28
2009-02-21T04:18:17Z
2,308,693
13
2010-02-22T03:52:58Z
[ "python", "django", "checkbox" ]
When I define a Django form class similar to this: ``` def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") ``` It expands to HTML that looks like this: ``` <form action="." id="form" method=POST> <p><label for="check">Check this:</label> <input type="checkbox" name="check"...
I took the answer from romkyns and made it a little more general ``` def field_type(field, ftype): try: t = field.field.widget.__class__.__name__ return t.lower() == ftype except: pass return False ``` This way you can check the widget type directly with a string ``` {% if field|f...
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
28
2009-02-21T04:18:17Z
15,308,315
10
2013-03-09T07:18:55Z
[ "python", "django", "checkbox" ]
When I define a Django form class similar to this: ``` def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") ``` It expands to HTML that looks like this: ``` <form action="." id="form" method=POST> <p><label for="check">Check this:</label> <input type="checkbox" name="check"...
All presented solutions involve template modifications, which are in general rather inefficient concerning performance. Here's a custom widget that does the job: ``` from django import forms from django.forms.fields import BooleanField from django.forms.util import flatatt from django.utils.encoding import force_text ...
CPython internal structures
572,780
3
2009-02-21T10:41:40Z
573,021
8
2009-02-21T13:43:26Z
[ "python", "google-app-engine", "data-structures", "internals", "cpython" ]
GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element poin...
On a 32-bit system, each of the 8000000 lists you create will allocate 20 bytes for the list object itself, plus 16 bytes for a vector of list elements. So you are trying to allocate at least (20+16) \* 8000000 = 20168000000 bytes, about 20 GB. And that's in the best case, if the system malloc only allocates exactly as...
Python C-API Object Allocation‏
573,275
5
2009-02-21T16:01:45Z
573,424
10
2009-02-21T17:25:29Z
[ "c++", "python", "c", "python-3.x", "python-c-api" ]
I want to use the new and delete operators for creating and destroying my objects. The problem is python seems to break it into several stages. tp\_new, tp\_init and tp\_alloc for creation and tp\_del, tp\_free and tp\_dealloc for destruction. However c++ just has new which allocates and fully constructs the object an...
The documentation for these is at <http://docs.python.org/3.0/c-api/typeobj.html> and <http://docs.python.org/3.0/extending/newtypes.html> describes how to make your own type. tp\_alloc does the low-level memory allocation for the instance. This is equivalent to malloc(), plus initialize the refcnt to 1. Python has it...
Python serialize lexical closures?
573,569
18
2009-02-21T19:03:12Z
574,789
12
2009-02-22T11:42:04Z
[ "python", "serialization", "closures" ]
Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example: ``` def foo(bar, baz) : def closure(waldo) : ret...
If you simply use a class with a `__call__` method to begin with, it should all work smoothly with `pickle`. ``` class foo(object): def __init__(self, bar, baz): self.baz = baz def __call__(self,waldo): return self.baz * waldo ``` On the other hand, a hack which converted a closure into an ins...
Python serialize lexical closures?
573,569
18
2009-02-21T19:03:12Z
4,124,868
16
2010-11-08T14:46:46Z
[ "python", "serialization", "closures" ]
Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example: ``` def foo(bar, baz) : def closure(waldo) : ret...
PiCloud has released an open-source (LGPL) pickler which can handle function closure and a whole lot more useful stuff. It can be used independently of their cloud computing infrastructure - it's just a normal pickler. The whole shebang is documented [here](http://docs.picloud.com/), and you can download the code via '...
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
573,656
24
2009-02-21T20:04:40Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
If you're using a standard POSIX OS, you use [cron](http://linux.die.net/man/8/cron). If you're using Windows, you use [at](http://technet.microsoft.com/en-us/library/cc755618.aspx). Write a Django management command to 1. Figure out what platform they're on. 2. Either execute the appropriate "AT" command for your u...
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
573,659
219
2009-02-21T20:06:38Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
One solution that I have employed is to do this: 1) Create a [custom management command](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands), e.g. ``` python manage.py my_cool_command ``` 2) Use `cron` (on Linux) or `at` (on Windows) to run my command at the requi...
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
573,685
12
2009-02-21T20:29:47Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
Look at Django Poor Man's Cron which is a Django app that makes use of spambots, search engine indexing robots and alike to run scheduled tasks in approximately regular intervals See: <http://code.google.com/p/django-poormanscron/>
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
574,245
8
2009-02-22T03:18:07Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
I personally use cron, but the [Jobs Scheduling](http://code.google.com/p/django-command-extensions/wiki/JobsScheduling) parts of [django-extensions](https://github.com/django-extensions/django-extensions) looks interesting.
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
621,538
20
2009-03-07T08:32:30Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
Interesting new pluggable Django app: [django-chronograph](http://code.google.com/p/django-chronograph/) You only have to add one cron entry which acts as a timer, and you have a very nice Django admin interface into the scripts to run.
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
1,057,920
92
2009-06-29T11:56:47Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
[Celery](http://celeryproject.org/) is a distributed task queue, built on AMQP (RabbitMQ). It also handles periodic tasks in a cron-like fashion. Depending on your app, it might be worth a gander.
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
8,575,485
7
2011-12-20T12:30:42Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
Brian Neal's suggestion of running management commands via cron works well, but if you're looking for something a little more robust (yet not as elaborate as Celery) I'd look into a library like [Kronos](https://github.com/jgorset/django-kronos): ``` # app/cron.py import kronos @kronos.register('0 * * * *') def task...
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
9,071,268
26
2012-01-30T21:47:06Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
We've open-sourced what I think is a structured app. that Brian's solution above alludes too. Would love any / all feedback! <https://github.com/tivix/django-cron> It comes with one management command: ``` ./manage.py runcrons ``` That does the job. Each cron is modeled as a class (so its all OO) and each cron runs...
Django - Set Up A Scheduled Job?
573,618
299
2009-02-21T19:39:59Z
9,995,875
7
2012-04-03T14:54:18Z
[ "python", "django", "web-applications", "scheduled-tasks" ]
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this. Does anyone know how to s...
RabbitMQ and Celery have more features and task handling capabilities than Cron. If task failure isn't an issue, and you think you will handle broken tasks in the next call, then Cron is sufficient. Celery & [AMQP](https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol) will let you handle the broken task, an...
Docs for the internals of CPython Implementation
574,004
8
2009-02-22T00:16:52Z
574,393
8
2009-02-22T05:14:50Z
[ "python", "cpython" ]
I am currently in the process of making an embedded system port of the CPython 3.0 Python interpreter and I'm particularly interested in any references or documentation that provides details about the design and structure of code for Release 3.0 or even about any of the 2.x releases. One useful document I have found s...
There's the documentation for the C API, which is essentially the API for the internals of Python. It won't cover porting details, though. The code itself is fairly well documented. You might try reading in and around the area you'll need to modify.
How do YOU deploy your WSGI application? (and why it is the best way)
574,068
42
2009-02-22T00:58:37Z
574,135
25
2009-02-22T01:39:56Z
[ "python", "deployment", "wsgi" ]
Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? 1. Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) 2. Pure Python web server eg paste, cherrypy, Spawning, Twisted.web ...
As always: It depends ;-) When I don't need any apache features I am going with a pure python webserver like paste etc. Which one exactly depends on your application I guess and can be decided by doing some benchmarks. I always wanted to do some but never came to it. I guess Spawning might have some advantages in usin...
How do YOU deploy your WSGI application? (and why it is the best way)
574,068
42
2009-02-22T00:58:37Z
575,737
13
2009-02-22T20:36:33Z
[ "python", "deployment", "wsgi" ]
Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? 1. Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) 2. Pure Python web server eg paste, cherrypy, Spawning, Twisted.web ...
The absolute easiest thing to deploy is CherryPy. Your web application can also become a standalone webserver. CherryPy is also a fairly fast server considering that it's written in pure Python. With that said, it's not Apache. Thus, I find that CherryPy is a good choice for lower volume webapps. Other than that, I do...
How do YOU deploy your WSGI application? (and why it is the best way)
574,068
42
2009-02-22T00:58:37Z
622,597
13
2009-03-07T22:15:27Z
[ "python", "deployment", "wsgi" ]
Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? 1. Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) 2. Pure Python web server eg paste, cherrypy, Spawning, Twisted.web ...
> I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc Ho. Well you asked for it! Like Daniel I personally use Apache with mod\_wsgi. It is still new enough that deploying it in some environments can be a struggle, but if you're compiling everything yoursel...
How to determine number of files on a drive with Python?
574,236
5
2009-02-22T03:12:46Z
574,270
7
2009-02-22T03:37:47Z
[ "python", "osx", "filesystems", "hard-drive" ]
I have been trying to figure out how to retrieve (quickly) the number of files on a given HFS+ drive with python. I have been playing with os.statvfs and such, but can't quite get anything (that seems helpful to me). Any ideas? **Edit:** Let me be a bit more specific. =] I am writing a timemachine-like wrapper arou...
The right answer for your purpose is to live without a progress bar once, store the number rsync came up with and assume you have the same number of files as last time for each successive backup. I didn't believe it, but this seems to work on Linux: ``` os.statvfs('/').f_files - os.statvfs('/').f_ffree ``` This comp...
Has anyone used SciPy with IronPython?
574,604
16
2009-02-22T08:57:53Z
574,623
8
2009-02-22T09:13:41Z
[ "python", "scipy", "ironpython", "python.net" ]
I've been able to use the standard Python modules from IronPython, but I haven't gotten SciPy to work yet. Has anyone been able to use SciPy from IronPython? What did you have to do to make it work? Update: See [Numerical computing in IronPython with Ironclad](http://www.johndcook.com/blog/2009/03/19/ironclad-ironpyth...
Anything with components written in C (for example NumPy, which is a component of SciPy) will not work on IronPython as the external language interface works differently. Any C language component will probably not work unless it has been explicitly ported to work with IronPython. You might have to dig into the individ...
Has anyone used SciPy with IronPython?
574,604
16
2009-02-22T08:57:53Z
574,919
12
2009-02-22T13:21:58Z
[ "python", "scipy", "ironpython", "python.net" ]
I've been able to use the standard Python modules from IronPython, but I haven't gotten SciPy to work yet. Has anyone been able to use SciPy from IronPython? What did you have to do to make it work? Update: See [Numerical computing in IronPython with Ironclad](http://www.johndcook.com/blog/2009/03/19/ironclad-ironpyth...
Some of my workmates are working on [Ironclad](http://code.google.com/p/ironclad/), a project that will make extension modules for CPython work in IronPython. It's still in development, but parts of numpy, scipy and some other modules already work. You should try it out to see whether the parts of scipy you need are su...
Generating unique, ordered Pythagorean triplets
575,117
17
2009-02-22T16:00:34Z
575,134
12
2009-02-22T16:09:18Z
[ "python", "math" ]
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks. ``` import math def main(): for x in range (1, 1000): for y in ran...
You should define x < y < z. ``` for x in range (1, 1000): for y in range (x + 1, 1000): for z in range(y + 1, 1000): ``` Another good optimization would be to only use x and y and calculate zsqr = x \* x + y \* y. If zsqr is a square number (or z = sqrt(zsqr) is a whole number), it is a triplet, else...
Generating unique, ordered Pythagorean triplets
575,117
17
2009-02-22T16:00:34Z
575,849
7
2009-02-22T21:31:53Z
[ "python", "math" ]
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks. ``` import math def main(): for x in range (1, 1000): for y in ran...
Algorithms can be tuned for speed, memory usage, simplicity, and other things. Here is a `pythagore_triplets` algorithm tuned for speed, at the cost of memory usage and simplicity. If all you want is speed, this could be the way to go. Calculation of `list(pythagore_triplets(10000))` takes 40 seconds on my computer, ...
Generating unique, ordered Pythagorean triplets
575,117
17
2009-02-22T16:00:34Z
576,405
59
2009-02-23T03:00:32Z
[ "python", "math" ]
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks. ``` import math def main(): for x in range (1, 1000): for y in ran...
Pythagorean Triples make a good example for claiming "**`for` loops considered harmful**", because `for` loops seduce us into thinking about counting, often the most irrelevant part of a task. (I'm going to stick with pseudo-code to avoid language biases, and to keep the pseudo-code streamlined, I'll not optimize away...