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
How to find elements by class
5,041,008
99
2011-02-18T11:58:10Z
5,041,056
188
2011-02-18T12:04:10Z
[ "python", "html", "beautifulsoup" ]
I'm having trouble parsing html elements with "class" attribute using Beautifulsoup. The code looks like this ``` soup = BeautifulSoup(sdata) mydivs = soup.findAll('div') for div in mydivs: if (div["class"]=="stylelistrow"): print div ``` I get an error on the same line "after" the script finishes. ``` ...
You can refine your search to only find those divs with a given class: ``` mydivs = soup.findAll("div", { "class" : "stylelistrow" }) ```
How to find elements by class
5,041,008
99
2011-02-18T11:58:10Z
15,919,953
8
2013-04-10T07:48:46Z
[ "python", "html", "beautifulsoup" ]
I'm having trouble parsing html elements with "class" attribute using Beautifulsoup. The code looks like this ``` soup = BeautifulSoup(sdata) mydivs = soup.findAll('div') for div in mydivs: if (div["class"]=="stylelistrow"): print div ``` I get an error on the same line "after" the script finishes. ``` ...
A straight forward way would be : ``` soup = BeautifulSoup(sdata) for each_div in soup.findAll('div',{'class':'stylelist'}): print each_div ``` Make sure you take of the casing of **findAll**, its not **findall**
How to find elements by class
5,041,008
99
2011-02-18T11:58:10Z
22,284,921
62
2014-03-09T16:40:05Z
[ "python", "html", "beautifulsoup" ]
I'm having trouble parsing html elements with "class" attribute using Beautifulsoup. The code looks like this ``` soup = BeautifulSoup(sdata) mydivs = soup.findAll('div') for div in mydivs: if (div["class"]=="stylelistrow"): print div ``` I get an error on the same line "after" the script finishes. ``` ...
From the documentation: [As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class\_:](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class) ``` soup.find_all("a", class_="sister") ``` Which in this case would be: ``` soup.find_all("div", class_="stylelistrow")...
How to find elements by class
5,041,008
99
2011-02-18T11:58:10Z
27,389,481
9
2014-12-09T21:48:51Z
[ "python", "html", "beautifulsoup" ]
I'm having trouble parsing html elements with "class" attribute using Beautifulsoup. The code looks like this ``` soup = BeautifulSoup(sdata) mydivs = soup.findAll('div') for div in mydivs: if (div["class"]=="stylelistrow"): print div ``` I get an error on the same line "after" the script finishes. ``` ...
Specific to BeautifulSoup 3: ``` soup.findAll('div', {'class': lambda x: x and 'stylelistrow' in x.split() } ) ``` Will find all of these: ``` <div class="stylelistrow"> <div class="stylelistrow button"> <div class="button stylelistrow"> ```
ImportError: dynamic module does not define init function, but it does
5,041,861
5
2011-02-18T13:29:56Z
6,002,941
7
2011-05-14T15:49:23Z
[ "c++", "python" ]
I'm trying to write a binding for a vendor C++ library. I've successfully used snippets such as the below to define init functions in the other modules, but in this one it doesn't seem to work: it compiles fine, but throws the ImportError as soon as I try to import it into a test script. What could be wrong here? ``` ...
I had the same issue. At compile time: * path to the Python header: OK * path to the Python library: OK * link against the Python library: OK * link against needed third parties libraries/object files: OK I just forgot to compile the C file that defines my module... Sigh... So yeah, first thing to check: your makefi...
(Django) Trim whitespaces from charField
5,043,012
12
2011-02-18T15:19:04Z
5,043,046
10
2011-02-18T15:21:51Z
[ "python", "django", "django-models", "removing-whitespace" ]
How do I strip whitespaces (trim) from the end of a charField in Django? Here is my Model, as you can see I've tried putting in clean methods but these never get run. I've also tried doing `name.strip()`, `models.charField().strip()` but these do not work either. Is there a way to force the charField to trim automat...
Model cleaning has to be called (it's not automatic) so place some `self.full_clean()` in your save method. <http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean> As for your form, you need to return the stripped cleaned data. ``` return self.cleaned_data['name'].strip() ``` ...
(Django) Trim whitespaces from charField
5,043,012
12
2011-02-18T15:19:04Z
6,338,383
15
2011-06-14T02:07:35Z
[ "python", "django", "django-models", "removing-whitespace" ]
How do I strip whitespaces (trim) from the end of a charField in Django? Here is my Model, as you can see I've tried putting in clean methods but these never get run. I've also tried doing `name.strip()`, `models.charField().strip()` but these do not work either. Is there a way to force the charField to trim automat...
When you're using a ModelForm instance to create/edit a model, the model's clean() method is guaranteed to be called. So, if you want to strip whitespace from a field, you just add a clean() method to your model (no need to edit the ModelForm class): ``` class Employee(models.Model): """(Workers, Staff, etc)""" ...
Python / Django - If statement in template around extends
5,043,117
20
2011-02-18T15:27:18Z
5,043,183
21
2011-02-18T15:32:32Z
[ "python", "django", "django-templates" ]
I would like to have a template that extends another conditionally. Basically, when a variable called "ajax" is true I DO NOT want to have the template extend another. ``` {% if not ajax %} {% extends "/base.html" %} {% endif %} ``` Any clues?
You cannot do it like that. You can however set a variable and use that to choose the template to extend: ``` {% extends my_template %} ``` Then in python code you write something like: ``` if ajax: template_values['my_template'] = 'base_ajax.html' else: template_values['my_template'] = 'base.html' ``` You ...
Python / Django - If statement in template around extends
5,043,117
20
2011-02-18T15:27:18Z
19,234,016
20
2013-10-07T20:21:51Z
[ "python", "django", "django-templates" ]
I would like to have a template that extends another conditionally. Basically, when a variable called "ajax" is true I DO NOT want to have the template extend another. ``` {% if not ajax %} {% extends "/base.html" %} {% endif %} ``` Any clues?
While you may not wrap `extends` in logic blocks, since it must be the first tag if used, it can still accept variables, including filters. This should fit your purpose nicely: ``` {% extends ajax|yesno:"base_ajax.html,base.html" %} {# stuff #} ``` Note: the `yesno` filter also accepts null values (`None`) as the thi...
Is it more efficient to create a dictionary in python using zip or a list comprehension?
5,043,912
2
2011-02-18T16:32:08Z
5,043,970
7
2011-02-18T16:36:49Z
[ "python", "optimization", "dictionary", "zip", "list-comprehension" ]
Lets say I want to set up a basic text encoding using a dictionary in python. Two ways of doing this come to mind immediately - using zip, and using list comprehension. ``` characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .,!;" dict_a = dict((x, characters[x]) for x in xrange(0, 31)) dict_b = dict(zip(xrange(0, 31), characte...
The [`enumerate` function](http://docs.python.org/library/functions.html#enumerate) is probably the easiest way to create your `dict`: ``` dict_c = dict(enumerate(characters)) ``` However, I'm not sure what that gives you that you can't do with the string. The following seem equivalent to me: ``` >>> dict_c[3] 'D' >...
Python string.split more than one value in for loop
5,044,181
2
2011-02-18T16:59:57Z
5,044,384
8
2011-02-18T17:17:26Z
[ "python", "string", "split" ]
Basically this works fine: ``` >>> x,y = "x=y".split("=") >>> print x x ``` But this gives an error: ``` >>> for x, y in "x=y".split("="): ... print x ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 1 value to unpack ``` I am wondering what the difference...
Split on "=" gives you two values: ``` "x", "y" ``` The fact that those values match your variable names is incidental. You could also do: ``` x,xx = "x=y".split("=") ``` I suspect what you are likely planning is to take a list: ``` "foo=bar,blah=boo,etc=something" ``` And split it, for which you could do: ``` f...
Qt Designer for PyQt on OSX 10.6
5,044,353
6
2011-02-18T17:14:32Z
5,044,911
11
2011-02-18T18:07:37Z
[ "python", "osx", "qt", "pyqt" ]
I liked Qt Designer on Windows so much for making GUIs for Python applications (using PyQt4) that I went and tried to install it on my Mac (under OSX 10.6.6). At this point, I have successfully installed SIP, Qt4, and PyQt4. The PyQt binary installers (for Windows) include a version of Qt Designer that works with PyQ...
If you've installed Qt4, then you have Qt Designer. If you used the installer from qt.nokia.com, it should be in /Developer/Applications/Qt. Qt Designer itself works just fine with PyQt. Qt designer just spits out XML describing the UI structure. If you were using standard Qt with C++, you would have to run the `uic` ...
profiling fuse-python
5,044,375
3
2011-02-18T17:17:11Z
5,044,703
8
2011-02-18T17:46:20Z
[ "python", "profiling", "signals", "fuse" ]
I am currently writing a fuse using fuse-python. It's already doing what it should. However, after it's mounted for a few weeks, it's becoming noticeably slow. So I wanted to profile it. I know about a few point where it could be optimized. But these should not be the culprits. However, fuse-python hangs in an infinit...
Python [installs a handler that raises `KeyboardInterrupt` on `SIGINT`](http://docs.python.org/library/signal.html#module-signal). If a non-default signal handler is detected when fuse's main is called, it will [not replace the handler with its own](http://fuse.git.sourceforge.net/git/gitweb.cgi?p=fuse/fuse;a=blob;f=li...
Django Storage Backend for S3
5,044,982
27
2011-02-18T18:13:56Z
5,046,870
32
2011-02-18T21:37:58Z
[ "python", "django", "amazon-s3", "boto" ]
I'm looking for a good Django custom storage backend for use with Amazon S3. I've been googling around and found a lot of blog posts with code snippets or half-baked gist.github.com one-off jobs. But I can't seem to find a solid, well-tested one. Is there a widely accepted standard Amazon S3 Django custom storage bac...
Have you checked out [django-storages](https://bitbucket.org/david/django-storages/)? I would lean towards the boto library as I have had good experiences with boto.
How to remove unconverted data from a Python datetime object
5,045,210
10
2011-02-18T18:37:05Z
5,045,374
8
2011-02-18T18:56:27Z
[ "python", "datetime", "strptime" ]
I have a database of mostly correct datetimes but a few are broke like so: `Sat Dec 22 12:34:08 PST 20102015` Without the invalid year, this was working for me: ``` end_date = soup('tr')[4].contents[1].renderContents() end_date = time.strptime(end_date,"%a %b %d %H:%M:%S %Z %Y") end_date = datetime.fromtimestamp(time...
Unless you want to rewrite `strptime` (a very bad idea), the only real option you have is to slice `end_date` and chop off the extra characters at the end, assuming that this will give you the correct result you intend. For example, you can catch the `ValueError`, slice, and try again: ``` fmt = "%a %b %d %H:%M:%S %Z...
How to remove unconverted data from a Python datetime object
5,045,210
10
2011-02-18T18:37:05Z
5,045,386
9
2011-02-18T18:57:11Z
[ "python", "datetime", "strptime" ]
I have a database of mostly correct datetimes but a few are broke like so: `Sat Dec 22 12:34:08 PST 20102015` Without the invalid year, this was working for me: ``` end_date = soup('tr')[4].contents[1].renderContents() end_date = time.strptime(end_date,"%a %b %d %H:%M:%S %Z %Y") end_date = datetime.fromtimestamp(time...
Yeah, I'd just chop off the extra numbers. Assuming they are always appended to the datestring, then something like this would work: ``` end_date = end_date.split(" ") end_date[-1] = end_date[-1][:4] end_date = " ".join(end_date) ``` I was going to try to get the number of excess digits from the exception, but on my ...
Calculating pi in Python using geometry
5,045,660
3
2011-02-18T19:28:54Z
5,046,706
8
2011-02-18T21:22:52Z
[ "python", "algorithm" ]
I'm posting this code with the hope that this community will be willing to assist me in ironing out some bugs I can't seem to be able to tackle. It's quite short, is intended to guess pi, and is not intended to replace already efficiently working approaches. This is not an assignment. ``` # this code is completely bro...
``` # Not broken anymore, prints 3.1415559... from math import sqrt def get_y(x, r): return sqrt((r**2.0)-(x**2.0)) # First mistake: ** is exponentiation, not ^ def get_distance(x1, y1, x2, y2): return sqrt( (x2-x1)**2.0 + (y2-y1)**2.0 ) def c(r): # def range(b): # redundant # a = 0 # wh...
Python: How to prevent subprocesses from receiving CTRL-C / Control-C / SIGINT
5,045,771
25
2011-02-18T19:39:38Z
5,050,521
24
2011-02-19T11:27:36Z
[ "python", "subprocess", "signals", "sigint", "keyboardinterrupt" ]
I am currently working on a wrapper for a dedicated server running in the shell. The wrapper spawns the server process via subprocess and observes and reacts to its output. The dedicated server must be explicitly given a command to shut down gracefully. Thus, CTRL-C must not reach the server process. If I capture the...
Somebody in the #python IRC-Channel (Freenode) helped me by pointing out the *preexec\_fn* parameter of **subprocess.Popen(...)**: > If *preexec\_fn* is set to a callable > object, this object will be called in > the child process just before the > child is executed. (Unix only) Thus, the following code solves the pr...
Python: How to prevent subprocesses from receiving CTRL-C / Control-C / SIGINT
5,045,771
25
2011-02-18T19:39:38Z
5,446,982
15
2011-03-27T03:16:56Z
[ "python", "subprocess", "signals", "sigint", "keyboardinterrupt" ]
I am currently working on a wrapper for a dedicated server running in the shell. The wrapper spawns the server process via subprocess and observes and reacts to its output. The dedicated server must be explicitly given a command to shut down gracefully. Thus, CTRL-C must not reach the server process. If I capture the...
Combining some of other answers that will do the trick - no signal sent to main app will be forwarded to the subprocess. ``` import os from subprocess import Popen def preexec(): # Don't forward signals. os.setpgrp() Popen('whatever', preexec_fn = preexec) ```
getopt() not enforcing required arguments?
5,045,821
9
2011-02-18T19:46:04Z
5,045,875
16
2011-02-18T19:50:48Z
[ "python" ]
I'm having problems with this `getopt()` code in a script that I'm writing which does some simple file manipulation given 2 required parameters (input filename and output filename) and/or 2 optional/situational arguments (debug or help). Code is: ``` def main(argv): try: opts, args = getopt.getopt(argv, "...
An option followed by a colon only means that it needs an argument. It doesn't mean that the option is enforced. You should write your own code to enforce the existence of options/arguments.
Mathematical Integration of a function in Python
5,046,845
2
2011-02-18T21:35:57Z
5,046,981
7
2011-02-18T21:51:32Z
[ "python", "function", "scipy" ]
I'm trying to integrate this function: ![enter image description here](http://i.stack.imgur.com/LFFf9.png) However I'm running into an error of: ``` Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "siestats.py", line 349, in NormalDistro P_inner = scipy.integrate(NDfx...
The module you are attempting to call is `scipy.integrate`, you need to call one of the functions within the module. Based on previous comments on [chat](http://chat.stackexchange.com/transcript/message/533455#533455) you are probably wanting to use `scipy.integrate.quad()`. Also, it returns a tuple of `(Result,Maximu...
Python - do I need to learn about old style classes?
5,046,903
5
2011-02-18T21:41:56Z
5,046,919
13
2011-02-18T21:43:51Z
[ "python", "class", "types", "language-features" ]
I am currently learning Python 2.6.5 and I found out about old style classes and new style classes. I understand that these classes are still existing only for backward compatibility and that they are removed in Python 3. So the question is this: **as a newcomer to the language, do I need to learn about the classic c...
No. Don't bother. Simply inherit all your classes from `object` (or from classes that inherit from `object`) and you will be good to go. Then when you transition to Python 3 you can forget that bit of syntax. There's no advantage to using or even learning about old-style classes at this point. So just make sure all o...
Why is RabbitMQ not persisting messages on a durable queue?
5,046,944
8
2011-02-18T21:46:07Z
5,047,012
18
2011-02-18T21:56:14Z
[ "python", "django", "rabbitmq", "celery" ]
I am using RabbitMQ with Django through Celery. I am using the most basic setup: ``` # RabbitMQ connection settings BROKER_HOST = 'localhost' BROKER_PORT = '5672' BROKER_USER = 'guest' BROKER_PASSWORD = 'guest' BROKER_VHOST = '/' ``` I imported a Celery task and queued it to run one year later. From the iPython shell...
Making a queue durable is not the same as making the messages on it persistent. Durable queues mean they come up again automatically when the server has restarted - which has obviously happened in your case. But this doesn't affect the messages themselves. To make messages persistent, you have to also mark the message...
Python (Numpy) array sorting
5,047,407
7
2011-02-18T22:51:18Z
5,047,432
13
2011-02-18T22:55:15Z
[ "python", "arrays", "sorting", "numpy" ]
I've got this array, named v, of dtype('float64'): ``` array([[ 9.33350000e+05, 8.75886500e+06, 3.45765000e+02], [ 4.33350000e+05, 8.75886500e+06, 6.19200000e+00], [ 1.33360000e+05, 8.75886500e+06, 6.76650000e+02]]) ``` ... which I've acquired from a file by using the np.loadtxt command. ...
Try ``` v[v[:,0].argsort()] ``` (with `v` being the array). `v[:,0]` is the first column, and `.argsort()` returns the indices that would sort the first column. You then apply this ordering to the whole array using advanced indexing. Note that you get a sorte copy of the array. The only way I know of to sort the arr...
How do I build a python string from a raw (binary) ctype buffer?
5,047,536
2
2011-02-18T23:09:24Z
5,047,559
7
2011-02-18T23:13:14Z
[ "python", "string", "ctypes" ]
I'm playing with Python and ctypes and I can't figure out how to resolve this problem. I call to a C function which fills a raw binary data. My code looks like this: ``` class Client(): def __init__(self): self.__BUFSIZE = 1024*1024 self.__buf = ctypes.create_string_buffer(self.__BUFSIZE) self.client = c...
You can access a buffer returned by `create_string_buffer()` as a Python string by using its `raw` attribute: ``` a = ctypes.create_string_buffer(10) a.raw # '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ``` To only access the first `n` bytes, use ``` a.raw[:n] ```
how to match whitespace and alphanumeric characters in python
5,048,091
8
2011-02-19T00:49:01Z
5,048,227
25
2011-02-19T01:23:09Z
[ "python", "regex", "pattern-matching" ]
hey guys im trying to match a string that has a space in the middle and alphanumeric characters like so: ``` test = django cms ``` i have tried matching using the follwing pattern: ``` patter = '\s' ``` unfortunately that only matches whitespace, so when a match is found using the search method in the re object, it...
``` import re test = "this matches" match = re.match('(\w+\s\w+)', test) print match.groups() ``` returns ``` ('this matches',) ```
Controlling stdout/stderr from Jython
5,048,166
4
2011-02-19T01:04:51Z
5,048,200
7
2011-02-19T01:15:11Z
[ "java", "python", "jython" ]
I am calling a function in a java library from jython which prints to stdout. I would like to suppress this output from the jython script. I attempt the python idiom replacing sys.stdout with a file like object (StringIO), but this does not capture the output of the java library. I'm guessing sys.stdout does not affect...
You can use `System.setOut`, like this: ``` >>> from java.lang import System >>> from java.io import PrintStream, OutputStream >>> oldOut = System.out >>> class NoOutputStream(OutputStream): ... def write(self, b, off, len): pass ... >>> System.setOut(PrintStream(NoOutputStream())) >>> System.out....
Chrome extension in python?
5,048,436
21
2011-02-19T02:23:36Z
5,048,477
9
2011-02-19T02:37:29Z
[ "python", "google-chrome-extension" ]
I would like to create a google chrome extension. Specifically, I'd like to make a packaged app, but not a hosted app. Am I correct in thinking this limits me to JavaScript (and HTML/CSS)? My problem is that I need to do some complex math (singular value decomposition, factor analysis) and I don't want to write algori...
There is no Python built into Chrome but I am wondering whether [Pyjamas](http://pyjs.org/) can help you.
Python check if current process is running?
5,048,515
5
2011-02-19T02:49:26Z
5,048,613
9
2011-02-19T03:16:05Z
[ "python", "process" ]
I need to add a function to my python script that checks if the current script is already running. If it is then it will quit, if not it continues running the script. I've looked into methods of doing this but I cant figure out how to do it.
I think you mean "cross-platform single instance of application written in python". Try this workable solution: [Python: single instance of program](http://stackoverflow.com/questions/380870/python-single-instance-of-program/1265445#1265445)
How to alphabetically sort array of dictionaries on single key?
5,048,841
4
2011-02-19T04:28:24Z
5,048,860
8
2011-02-19T04:34:27Z
[ "python", "facebook", "list", "sorting", "dictionary" ]
I want to sort the list of friends returned by Facebook's Graph API. The result after sorting needs to be an alphabetical order of friends by name. ``` [ { "name": "Joe Smith", "id": "6500000" }, { "name": "Andrew Smith", "id": "82000" }, { "na...
``` sorted(flist, key=lambda friend: friend["name"]) ```
Evaluating mathematical expressions in Python
5,049,489
7
2011-02-19T07:23:19Z
5,049,534
7
2011-02-19T07:34:43Z
[ "python", "parsing", "math", "binary-tree", "mathematical-expressions" ]
I want to tokenize a given mathematical expression into a parse tree like this: ``` ((3 + 4 - 1) * 5 + 6 * -7) / 2 '/' / \ + 2 / \ * * / \ / \ - ...
Yes, the Python [`ast`](http://docs.python.org/library/ast.html) module provides facilities to do this. You'll have to look up the exact interface for your version of Python, since the `ast` module seems to change regularly. In particular, the [`ast.parse()`](http://docs.python.org/library/ast.html#ast.parse) method w...
Autocomplete in PyCharm for Python compiled extensions
5,049,842
16
2011-02-19T08:57:01Z
5,196,184
11
2011-03-04T16:01:18Z
[ "python", "autocomplete", "pycharm" ]
When writing Python code using compiled extensions (the OpenCV Python bindings, for example), PyCharm doesn't seem to be aware of their availability. The imports are marked with a grey underline, saying "unresolved reference" as a tooltip, and autocomplete doesn't work, either. (Except for the function names already us...
> The imports are marked with a grey underline, saying "unresolved reference" as a tooltip This most probably means that PyCharm can't see the module you import. In editing mode, PyCharm relies on availability of Python sources of imported modules. If a module is not written in Python but is a C extension module, PyCh...
How do I use beaker caching in Pyramid?
5,050,110
9
2011-02-19T10:03:09Z
8,284,147
12
2011-11-27T07:03:45Z
[ "python", "caching", "pylons", "cache-control", "pyramid" ]
I have the following in my `ini` file: ``` cache.regions = default_term, second, short_term, long_term cache.type = memory cache.second.expire = 1 cache.short_term.expire = 60 cache.default_term.expire = 300 cache.long_term.expire = 3600 ``` And this in my `__init__.py`: ``` from pyramid_beaker import set_cache_regi...
My mistake was to call decorator function **@cache\_region** on a view-callable. I got no error reports but there were no actual caching. So, in my views.py I was trying like: ``` @cache_region('long_term') def photos_view(request): #just an example of a costly call from Google Picasa gd_client = gdata.photos....
How to get application root path in GAE
5,050,615
3
2011-02-19T11:54:26Z
5,061,645
12
2011-02-21T02:08:14Z
[ "python", "google-app-engine", "path" ]
I am using Jinja2 templates for my GAE Python application. Actually there are a couple of small applications inside one project. They are, for example, blog and site. So, the first one is for blog and the second one is for site =). I have this folders structure: ``` / /apps /blog /site /templates /blog /...
The easiest way to get the root path of your app is to put a module in the root of your app, which stores the result of `os.path.dirname(__file__)`, then import that where needed. Alternately, call `os.path.dirname(module.__file__)` on a module that's in the root of your app.
Sharing a database between Twisted and Django
5,051,408
8
2011-02-19T14:42:59Z
5,051,760
10
2011-02-19T15:53:37Z
[ "python", "database", "django", "twisted" ]
I am developing a multiplayer gaming server that uses Django for the webserver (HTML frontend, user authentication, games available, leaderboard, etc.) and Twisted to handle connections between the players and the games and to interface with the games themselves. The gameserver, the webserver, and the database may run ...
First of all I'd identify why you need both Django and Twisted. Assuming you are comfortable with Twisted using twisted.web and auth will easily be sufficient and you'll be able to reuse your database layer for both the frontend and backend apps. Alternatively you could look at it the other way, what is Twisted doing ...
Truncate the length of a Python dictionary
5,051,795
4
2011-02-19T15:59:19Z
5,051,850
8
2011-02-19T16:09:11Z
[ "python", "dictionary" ]
Given an ordered Python dictionary, what is the most Pythonic way to truncate its length? For example, if I'm given a dictionary with several thousand entries how do I truncate it to be the first 500 entries only.
Do you really to modify the dictionary in-place? You can easily generate a new one (thanks to iterators, without even touching the items you don't need): ``` OrderedDict(itertools.islice(d.iteritems(), 500)) ``` You *could* also truncate the original one, but that would be less performant for large one and is propabl...
What is behind python package namespaces: z3c, zc, collective?
5,053,174
6
2011-02-19T20:00:06Z
5,053,242
8
2011-02-19T20:14:28Z
[ "python", "zope" ]
So they all are somehow related to zope. Question is how? I am not familiar with Zope. I guess that zc, z3c stand for `Zope Component` and `Zope3 Component` but I want to be sure. Also there is a `collective` namespace. What kind of packages goes under it? What are other well known python package namespaces? Are the...
* `zc` is "Zope Corporation". * `z3c` is "Zope 3 community", a namespace that long since has been "deprecated", ie no new packages are made with this namespace. * `collective` refers to the Plone Collective, a svn repository for Plone packages with a friendly attitude towards contributors. It's been the "default" names...
AttributeError: 'list' object has no attribute 'encode'
5,054,333
7
2011-02-20T00:02:21Z
5,054,355
15
2011-02-20T00:05:52Z
[ "python", "encoding" ]
I have a list of unicode objects and want to encode them to utf-8, but encoding doesn't seem to work. the code is here : ``` >>> tmp = [u' test context'] >>> tmp.encode('utf-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'encode' >>> ``` I ...
You need to do `encode` on `tmp[0]`, not on `tmp`. `tmp` is not a string. It *contains* a (Unicode) string. Try running `type(tmp)` and `print dir(tmp)` to see it for yourself.
python list comprehension unzipping multiple returns
5,054,836
2
2011-02-20T02:15:37Z
5,054,861
7
2011-02-20T02:22:27Z
[ "python", "list", "list-comprehension", "unzip" ]
anyone have any idea how to unpack the values in a tuple for a list comprehension? So a practical example: ``` def func(x,y): return x*2, y*2 x = [1, 2, 3]; y = [1, 2, 3] a, b = [ func(i,j) for i, j in zip(x,y) ] ``` Unfortunately, that gives me an error sayin' there are too many values to unpack... I've trie...
Do you mean the following?: ``` a, b = zip(*[func(i,j) for i, j in zip(x,y)]) ```
Outputting errors to browser in CherryPy
5,054,957
2
2011-02-20T02:58:26Z
5,069,911
7
2011-02-21T18:44:40Z
[ "python", "browser", "logging", "stack-trace", "cherrypy" ]
I am new to cherrypy, and can't seem to figure out how to have cherrypy emit a stacktrace or error message to my browser when an error occurs. I am running cherrypy on apache with mod\_wsgi, so its particularly annoying to dig through the apache error logs during development. I am used to PHP, where errors are nicely...
The most important config setting which governs tracebacks in the browser is [`request.show_tracebacks`](http://docs.cherrypy.org/dev/refman/_cprequest.html#cherrypy._cprequest.Request.show_tracebacks). Set it to `True` to get tracebacks. Note that using the "production" [config environment](http://docs.cherrypy.org/de...
What's the best practice using a settings file in Python?
5,055,042
119
2011-02-20T03:25:06Z
5,055,075
8
2011-02-20T03:31:40Z
[ "python", "parsing", "settings" ]
I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use fo...
Take a look at [python standard config parser](http://docs.python.org/library/configparser.html). EDIT: Since nesting seems to be that important, you might consider handling your config file through JSON format. It then becomes a matter of using the `json` module with `dumps` and `loads` methods that will work with d...
What's the best practice using a settings file in Python?
5,055,042
119
2011-02-20T03:25:06Z
5,055,117
62
2011-02-20T03:43:30Z
[ "python", "parsing", "settings" ]
I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use fo...
Check out: <http://wiki.python.org/moin/ConfigParserShootout> for a list of configuration parsers available in python. Some support nested config files.
What's the best practice using a settings file in Python?
5,055,042
119
2011-02-20T03:25:06Z
5,055,466
27
2011-02-20T05:44:54Z
[ "python", "parsing", "settings" ]
I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use fo...
Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too. `...
What's the best practice using a settings file in Python?
5,055,042
119
2011-02-20T03:25:06Z
5,056,829
107
2011-02-20T11:49:11Z
[ "python", "parsing", "settings" ]
I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use fo...
You can have a regular Python module, say config.py, like this : ``` truck = dict( color = 'blue', brand = 'ford', ) city = 'new york' cabriolet = dict( color = 'black', engine = dict( cylinders = 8, placement = 'mid', ), doors = 2, ) ``` and use it like that : ``` import conf...
What's the best practice using a settings file in Python?
5,055,042
119
2011-02-20T03:25:06Z
5,060,485
48
2011-02-20T22:21:57Z
[ "python", "parsing", "settings" ]
I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use fo...
The sample config you provided is actually valid Yaml. In fact, yaml meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The [PyYAML project](http://pyyaml.org/wiki/PyYAMLDocumentation) provides a nice python module, that implem...
What's the best practice using a settings file in Python?
5,055,042
119
2011-02-20T03:25:06Z
34,354,110
16
2015-12-18T11:00:56Z
[ "python", "parsing", "settings" ]
I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use fo...
I Found this the most useful and easy to use <https://wiki.python.org/moin/ConfigParserExamples> You just create a "myfile.ini" like: ``` [SectionOne] Status: Single Name: Derek Value: Yes Age: 30 Single: True [SectionTwo] FavoriteColor=Green [SectionThree] FamilyName: Johnson [Others] Route: 66 ``` And retrieve t...
Boost-python How to pass a c++ class instance to a python class
5,055,443
8
2011-02-20T05:35:26Z
5,056,462
13
2011-02-20T10:33:28Z
[ "c++", "python", "boost-python" ]
I am new to boost python. I have to first init a cpp class instance in cpp code, and then pass this cpp instance to python code, use a python class instance to invoke it(the cpp instance). I have tried the Python/C API way, but failed, so I wonder how to pass a c++ class instance to a python class. The following is my...
Pass the object pointer via boost::python::ptr to python. This will prevent the python interpreter from makeing a copy: ``` #include <boost/python.hpp> #include <string> #include <iostream> using namespace boost::python; using namespace std; class World { private: string name; public: void set(string name) {...
PyMongo upsert throws "upsert must be an instance of bool" error
5,055,797
37
2011-02-20T07:22:44Z
5,055,852
56
2011-02-20T07:39:07Z
[ "python", "mongodb", "pymongo" ]
I'm running an update on my MongoDB from Python. I have this line: ``` self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True}) ``` But it throws this error: ``` raise TypeError("upsert must be an instance of bool") ``` But `True` looks like an instance of bool to me! How should I correc...
The third argument to PyMongo's [`update()`](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update) is `upsert` and must be passed a boolean, not a dictionary. Change your code to: ``` self.word_counts[source].update({'date':posttime}, {"$inc" : words}, True) ``` Or pa...
PyMongo upsert throws "upsert must be an instance of bool" error
5,055,797
37
2011-02-20T07:22:44Z
13,029,018
9
2012-10-23T11:02:50Z
[ "python", "mongodb", "pymongo" ]
I'm running an update on my MongoDB from Python. I have this line: ``` self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True}) ``` But it throws this error: ``` raise TypeError("upsert must be an instance of bool") ``` But `True` looks like an instance of bool to me! How should I correc...
According to <http://api.mongodb.org/python/2.3/api/pymongo/collection.html#pymongo.collection.Collection.update> you should indeed pass upsert as a keyword rather than just True, that is ``` self.word_counts[source].update({'date':posttime},{"$inc" : words},**{'upsert':True}) ``` Or ``` self.word_counts[source].upd...
Sort Python list of objects by date
5,055,812
16
2011-02-20T07:26:42Z
5,055,818
32
2011-02-20T07:28:26Z
[ "python", "datetime", "sorting" ]
I have a Python list called results. Each result in the results list has a person object, and each person object has a birthdate (result.person.birthdate). The birthdate is a datetime object. I would like to order the list by birthdate with the oldest first. What is the most Pythonic way to do this?
``` results.sort(key=lambda r: r.person.birthdate) ```
Sort Python list of objects by date (when some are None)
5,055,942
5
2011-02-20T08:05:43Z
5,055,952
8
2011-02-20T08:09:59Z
[ "python", "list", "sorting" ]
This is a slight update to my previous [question](http://stackoverflow.com/questions/5055812/sort-python-list-of-objects-by-date) I have a Python list called results. Most result objects in the results list have a person object, and most person objects have a birthdate property (result.person.birthdate). The birthdate...
``` import datetime results.sort(key=lambda r: r.person.birthdate if (r and r.person and r.person.birthdate) else datetime.datetime.now()) ``` (P.S. You could have just edited your previous question.)
element that appear more that once in the list in Python
5,056,064
2
2011-02-20T08:48:29Z
5,056,587
12
2011-02-20T11:00:57Z
[ "python", "list", "element" ]
Please help (I know that it's a silly question): I have a list `d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']`. How can I exclude elements that appear more than once?
To **exclude** items from the list that appear more than once: ``` d = [x for x in d if d.count(x) == 1] ``` For the example provided above, d will bind to an empty list. Others have posted good solutions to **remove duplicates**.
Inserting new attribute to a document using MongoDB ( Python )
5,056,190
20
2011-02-20T09:25:14Z
5,056,218
39
2011-02-20T09:33:05Z
[ "python", "mongodb" ]
I'm new with MOngoDB ( coming from CouchDB ) and I am having issues with adding new attributes to my documents in MongDB using the MonDB python driver. For example, I have the following document: ``` { '_id':123456, 'text':"this is nice" } ``` And I want to insert a new attribute, for example: ``` { '_id':123456, '...
``` db.collection.update({'_id' : ObjectId(...)}, {'$set' : {'create_time' : datetime(..) }}) ```
Python library for implementing SAML2 based service provider and identity provider?
5,056,475
8
2011-02-20T10:37:21Z
5,351,618
9
2011-03-18T11:55:03Z
[ "python", "saml" ]
I am looking for a Python library which can be used to implement SAML2 based service provider and identity provider. The core library should not depend on any particular web-framework. I am looking for something which is more feature complete and preferably easy to use. Also the library should have more permissive lice...
The **pysaml2** project at launchpad is pretty active now. I think that you were sprinting on it at PyCon 2011. The **pysaml2** package is included in Python package index (PyPi) and installable with `easy_install` / `pip`. The docs can be found at: <https://pypi.python.org/pypi/pysaml2> There is a related project for...
Using Httplib2 on Python Appengine
5,056,719
9
2011-02-20T11:25:47Z
5,056,764
8
2011-02-20T11:34:59Z
[ "python", "google-app-engine", "oauth", "foursquare", "httplib2" ]
Why am I getting this error when running my application which is trying to OAuth with Foursquare? ``` import httplib2 ImportError: No module named httplib2 ``` I have installed httplib2 by downloading it and $ python setup.py install on the command line as instructed [here](http://code.google.com/p/httplib2/wiki/Inst...
You will need to include the library in your project so that the App Engine runtime knows what you're importing. From [here](http://code.google.com/appengine/docs/python/runtime.html#Pure_Python): > You can include other pure Python libraries with your application by putting the code in your application directory. If...
Longest common subsequence of 3+ strings
5,057,243
7
2011-02-20T13:16:54Z
5,057,362
15
2011-02-20T13:41:55Z
[ "python", "algorithm", "dynamic-programming", "lcs" ]
I am trying to find the longest common subsequence of 3 or more strings. The Wikipedia article has a great description of [how to do this for 2 strings](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Solution_for_two_sequences), but I'm a little unsure of how to extend this to 3 or more strings. There...
Just generalize the recurrence relation. For three strings: ``` dp[i, j, k] = 1 + dp[i - 1, j - 1, k - 1] if A[i] = B[j] = C[k] max(dp[i - 1, j, k], dp[i, j - 1, k], dp[i, j, k - 1]) otherwise ``` Should be easy to generalize to more strings from this.
How can I pass images in a server's response using JSON? Base64?
5,057,828
9
2011-02-20T15:07:31Z
5,057,849
8
2011-02-20T15:11:41Z
[ "python", "android", "image", "listview", "base64" ]
In my android app, I show some users in a ListView. I want to display (user's pic, first\_name, last\_name). Right now, it works only with first\_name and last\_name. I want to add the picture. The data JSON I receive from my server (python) is like this: ``` [{"profil":"first_name": "Jim", "last_name": "Carrey"}}, "_...
I would suggest adding a JSON parameter which contains a URL to the resource. For added security, you could create encrypted URLs by adding a md5 with salt checksum to the resource, like <http://server.com/images/1234567890123456789012345678901234567890/image.jpg> - this is the method facebook.com uses.
How can I pass images in a server's response using JSON? Base64?
5,057,828
9
2011-02-20T15:07:31Z
5,057,888
12
2011-02-20T15:18:55Z
[ "python", "android", "image", "listview", "base64" ]
In my android app, I show some users in a ListView. I want to display (user's pic, first\_name, last\_name). Right now, it works only with first\_name and last\_name. I want to add the picture. The data JSON I receive from my server (python) is like this: ``` [{"profil":"first_name": "Jim", "last_name": "Carrey"}}, "_...
Technically it's perfectly ok to encode binary data as base64 string and include it in JSON. But, as @servermanfail noted, you might be better off with embedding links to images into JSON and downloading them in the second step. The added benefit would be size/speed of transfer, as base64 stream is 4/3 the size of th...
How is __slots__ implemented in Python?
5,057,845
10
2011-02-20T15:10:42Z
5,058,327
15
2011-02-20T16:29:27Z
[ "python", "python-3.x", "python-c-api", "descriptor", "slots" ]
* How is [`__slots__`](http://docs.python.org/py3k/reference/datamodel.html#slots) implemented in Python? * Is this exposed in the [C interface](http://docs.python.org/py3k/c-api/index.html#c-api-index)? * How do I get `__slots__` behaviour when defining a Python class in C via [`PyTypeObject`](http://docs.python.org/p...
When creating Python classes, they by default have a `__dict__` and you can set any attribute on them. The point of slots is to not create a `__dict__` to save space. In the C interface it's the other way around, an extension class has by default no `__dict__`, and you would instead explicitly have to add one and add ...
Is there SQLAlchemy automigration tool like South for Django?
5,058,361
23
2011-02-20T16:36:15Z
10,190,793
8
2012-04-17T11:57:48Z
[ "python", "database", "migration", "sqlalchemy" ]
Is there SQLAlchemy automigration tool like South for Django? I looked to [sqlalchemy-migrate](http://code.google.com/p/sqlalchemy-migrate/) but it doesn't seem to generate sql update scripts automatically or upgrade downgrade DB Looks like with sqlalchemy-migrate you need to a) manually copy your old model to a new ...
There is [Alembic](http://alembic.readthedocs.org/en/latest/index.html) which looks very promising, but the problem is (for now) that the support for SQlite databases is very limited.
Using Mako with Pyramid causes an error
5,059,820
2
2011-02-20T20:32:27Z
5,780,755
9
2011-04-25T16:56:38Z
[ "python", "pylons", "mako", "pyramid" ]
When trying to use Mako with the Pyramid framework, by going into the development.ini file, and adding the line ``` mako.directories = TestProject:templates ``` in: ``` [app:TestProject] ``` and then creating a simple html file called template.mako in the templates subdirectory I get an: ``` ImportError: No module...
As summary: Edit the file `development.ini` and add in the section `[app:MyProject]`: > mako.directories = myproject:templates Now we can open the file `/MyProject/myproject/__init__.py` and add a line like: > config.add\_route('foo', '/foo', view='myproject.views.foo', view\_renderer='foo.mako') This will render ...
Can't get ZeroMQ python bindings to receive messages over IPC
5,060,508
16
2011-02-20T22:25:56Z
5,060,636
16
2011-02-20T22:48:15Z
[ "python", "ipc", "zeromq" ]
I'm trying to achieve PUB/SUB over IPC. If I changed the code below so that the subscriber binds to "tcp://\*:5000" and the publisher connects to "tcp://localhost:5000" it works, but I can't get it to work over IPC. What am I doing wrong? subscriber.py ``` import zmq, json def main(): context = zmq.Context() ...
most likely cause is that you are running the publisher in a different directory. Try using absolute path for the pipe location: "ipc:///tmp/test.pipe". The way you are using it now makes it relative to current working directory.
Python regexes: How to access multiple matches of a group?
5,060,659
31
2011-02-20T22:52:15Z
5,060,695
26
2011-02-20T22:58:05Z
[ "python", "regex" ]
I am putting together a fairly complex regular expression. One part of the expression matches strings such as '+a', '-57' etc. A + or a - followed by any number of letters or numbers. I want to match 0 or more strings matching this pattern. This is the expression I came up with: ``` ([\+-][a-zA-Z0-9]+)* ``` If I wer...
Drop the `*` from your regex (so it matches exactly one instance of your pattern). Then use either `re.findall(...)` or `re.finditer` (see [here](http://docs.python.org/library/re.html)) to return all matches. **Update:** It sounds like you're essentially building a [recursive descent parser](http://en.wikipedia.org/...
Python regexes: How to access multiple matches of a group?
5,060,659
31
2011-02-20T22:52:15Z
30,202,102
8
2015-05-12T21:54:50Z
[ "python", "regex" ]
I am putting together a fairly complex regular expression. One part of the expression matches strings such as '+a', '-57' etc. A + or a - followed by any number of letters or numbers. I want to match 0 or more strings matching this pattern. This is the expression I came up with: ``` ([\+-][a-zA-Z0-9]+)* ``` If I wer...
The [`regex` module](https://pypi.python.org/pypi/regex) fixes this, by adding a `.captures` method: ``` >>> m = regex.match(r"(..)+", "a1b2c3") >>> m.captures(1) ['a1', 'b2', 'c3'] ```
format of /dev/input/event*?
5,060,710
15
2011-02-20T23:00:25Z
5,060,754
18
2011-02-20T23:08:44Z
[ "python", "linux", "device" ]
What is the "format" of the character devices located in `/dev/input/event*` ? In other words, how can I decode the character stream? A python example would be greatly appreciated. I've been googling like crazy to no avail... please help.
The format is described in the [`Documentation/input/input.txt`](http://www.kernel.org/doc/Documentation/input/input.txt) file in the Linux source. Basically, you read structs of the following form from the file: ``` struct input_event { struct timeval time; unsigned short type; unsigned short code; un...
format of /dev/input/event*?
5,060,710
15
2011-02-20T23:00:25Z
5,060,761
7
2011-02-20T23:09:50Z
[ "python", "linux", "device" ]
What is the "format" of the character devices located in `/dev/input/event*` ? In other words, how can I decode the character stream? A python example would be greatly appreciated. I've been googling like crazy to no avail... please help.
right here in the [Input.py](https://github.com/kdart/pycopia/blob/master/core/pycopia/OS/Linux/Input.py) module. You'll also need the [event.py](https://github.com/kdart/pycopia/blob/master/core/pycopia/OS/Linux/event.py) module.
format of /dev/input/event*?
5,060,710
15
2011-02-20T23:00:25Z
10,665,053
7
2012-05-19T12:10:15Z
[ "python", "linux", "device" ]
What is the "format" of the character devices located in `/dev/input/event*` ? In other words, how can I decode the character stream? A python example would be greatly appreciated. I've been googling like crazy to no avail... please help.
The [python-evdev](http://gvalkov.github.com/python-evdev/) package provides bindings to the event device interface. A short usage example would be: ``` from evdev import InputDevice from select import select dev = InputDevice('/dev/input/event1') while True: r,w,x = select([dev], [], []) for event in dev.read...
format of /dev/input/event*?
5,060,710
15
2011-02-20T23:00:25Z
16,682,549
16
2013-05-22T02:32:07Z
[ "python", "linux", "device" ]
What is the "format" of the character devices located in `/dev/input/event*` ? In other words, how can I decode the character stream? A python example would be greatly appreciated. I've been googling like crazy to no avail... please help.
A simple and raw reader can be just done using: ``` #!/usr/bin/python import struct import time import sys infile_path = "/dev/input/event" + (sys.argv[1] if len(sys.argv) > 1 else "0") #long int, long int, unsigned short, unsigned short, unsigned int FORMAT = 'llHHI' EVENT_SIZE = struct.calcsize(FORMAT) #open file...
Assign to a slice of a Python list from a lambda
5,060,830
2
2011-02-20T23:22:32Z
5,060,851
7
2011-02-20T23:26:31Z
[ "python", "list", "lambda", "variable-assignment" ]
I know that there are certain "special" methods of various objects that represent operations that would normally be performed with operators (i.e. `int.__add__` for +, `object.__eq__` for ==, etc.), and that one of them is `list.__setitem`, which can assign a value to a list element. However, I need a function that can...
The line ``` some_list[2:4] = [2, 3] ``` will also call `list.__setitem__()`. Instead of an index, it will pass a `slice` object though. The line is equivalent to ``` some_list.__setitem__(slice(2, 4), [2, 3]) ```
How is introspection useful?
5,061,325
9
2011-02-21T00:57:56Z
5,061,360
11
2011-02-21T01:07:33Z
[ "python", "introspection" ]
Python noobie here. OK. I have been programming mainly in PHP, and I am trying to make a switch to python. I am skilled with PHP, and I have never needed to use introspection / introspection like capabilities. What good is code introspection, and in what situations would I find it indispensable? Here is the only way ...
Suppose you are given a custom object and you want to know if you the object has certain attribute or has as a certain method, then the introspection function such as `hasattr` can be used to find out and used in your logic. Also like the DiveintoPython book already illustrates, suppose you are building a GUI Editor w...
Setting stacksize in a python script
5,061,582
16
2011-02-21T01:53:59Z
5,061,627
10
2011-02-21T02:04:13Z
[ "python", "stack", "csh" ]
I am converting a csh script to a python script. The script calls a memory-intensive executable which requires a very large stack, so the csh script sets the stacksize to unlimited: ``` limit stacksize unlimited ``` When I try to reproduce this script in python, I execute them in a very naive manner, using `os.system...
You're looking for the Python [setrlimit](http://docs.python.org/library/resource.html) interface, `resource.RLIMIT_STACK`. Note that standard users cannot raise their hard limits, only root (well, a process with the `CAP_SYS_RESOURCE` capability (see capabilities(7)) processes can raise their limits; so you may need ...
Setting stacksize in a python script
5,061,582
16
2011-02-21T01:53:59Z
5,061,641
13
2011-02-21T02:07:24Z
[ "python", "stack", "csh" ]
I am converting a csh script to a python script. The script calls a memory-intensive executable which requires a very large stack, so the csh script sets the stacksize to unlimited: ``` limit stacksize unlimited ``` When I try to reproduce this script in python, I execute them in a very naive manner, using `os.system...
You can just use the (u)limit command of your shell, if you want: ``` os.system('ulimit -s unlimited; some_executable') ``` Or (probably better) use [resource.setrlimit](http://docs.python.org/library/resource.html): ``` resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY)) ```
Setting stacksize in a python script
5,061,582
16
2011-02-21T01:53:59Z
16,248,113
7
2013-04-27T03:45:50Z
[ "python", "stack", "csh" ]
I am converting a csh script to a python script. The script calls a memory-intensive executable which requires a very large stack, so the csh script sets the stacksize to unlimited: ``` limit stacksize unlimited ``` When I try to reproduce this script in python, I execute them in a very naive manner, using `os.system...
I have good experience with the following code. It doesn't require any special user permissions: ``` import resource, sys resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1)) sys.setrecursionlimit(10**6) ``` It does however not seem to work with pypy.
negatives and positives in lists
5,061,630
3
2011-02-21T02:04:48Z
5,061,648
7
2011-02-21T02:09:48Z
[ "python" ]
I'm trying to write a function that allows me to add only the positive numbers in a list and only the negative numbers in a list. I don't know where to start with my coding though. Any help would be great thanks! example: ``` negpos([-5,5,6,-8,9]) ``` should return: ``` [-13, 20] ```
Try this on for size: ``` def negpos (lst): (neg, pos) = (0, 0) for elem in lst: if elem < 0: neg = neg + elem else: pos = pos + elem return [neg, pos] print negpos ([-5,5,6,-8,9]) ``` It simply maintains two accumulators and adds to the relevant one. The output is...
Dynamic template "Includes" with django
5,062,456
6
2011-02-21T04:55:11Z
5,063,164
15
2011-02-21T06:57:43Z
[ "python", "django" ]
I am building a Django website and my side bar can have different elements for different users. So my main sidebar template has a div for every plugin to be included and the specific HTML for every one of these plugins is included in their own template file. example: ``` <div id="plugins"> <div id="plugin1"> ...
You can use a variable inside the `include` tag: ``` {% include my_user_html %} ```
How to use a string as stdin
5,062,895
5
2011-02-21T06:12:14Z
5,062,926
9
2011-02-21T06:16:40Z
[ "python" ]
I have been going crazy over a seemingly easy question with Python: I want to call a function that uses raw\_input() and input(), and somehow supply those with a string in my program. I've been searching and found that subprocess can change stdin and stdout to PIPE; however, I can't use subprocess to call a function. H...
Temporarily replace `sys.stdin` with a `StringIO` or `cStringIO` with the desired string. ``` >>> s = StringIO.StringIO('Hello, world!') >>> sys.stdin = s ; r = raw_input('What you say?\n') ; sys.stdin = sys.__stdin__ What you say? >>> r 'Hello, world!' ```
is there a self flag can reference python function inside itself?
5,063,607
17
2011-02-21T08:07:23Z
5,063,695
8
2011-02-21T08:23:30Z
[ "python", "function", "reference", "self" ]
I can access a python function's attribute inside of function itself by below code: ``` def aa(): print aa.__name__ print aa.__hash__ # other simliar ``` however, if above aa() function is a template for write other code,say bb() , I have to write ``` def bb(): print bb.__name__ print bb.__hash__...
<http://docs.python.org/library/inspect.html> looks promising: ``` import inspect def foo(): felf = globals()[inspect.getframeinfo(inspect.currentframe()).function] print felf.__name__, felf.__doc__ ``` you can also use the `sys` module to get the name of the current function: ``` import sys def bar(): ...
is there a self flag can reference python function inside itself?
5,063,607
17
2011-02-21T08:07:23Z
5,063,783
16
2011-02-21T08:37:04Z
[ "python", "function", "reference", "self" ]
I can access a python function's attribute inside of function itself by below code: ``` def aa(): print aa.__name__ print aa.__hash__ # other simliar ``` however, if above aa() function is a template for write other code,say bb() , I have to write ``` def bb(): print bb.__name__ print bb.__hash__...
There is no generic way for a function to refer to itself. Consider using a decorator instead. If all you want as you indicated was to print information about the function that can be done easily with a decorator: ``` from functools import wraps def showinfo(f): @wraps(f) def wrapper(*args, **kwds): p...
How to add items into a numpy array
5,064,822
42
2011-02-21T10:29:32Z
5,068,182
72
2011-02-21T16:03:42Z
[ "python", "numpy" ]
I need to accomplish the following task: from: ``` a = array([[1,3,4],[1,2,3]...[1,2,1]]) ``` (add one element to each row) to: ``` a = array([[1,3,4,x],[1,2,3,x]...[1,2,1,x]]) ``` I have tried doing stuff like a[n] = array([1,3,4,x]) but numpy complained of shape mismatch. I tried iterating through `a` and appen...
Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python `list` will. You'll find that every "append" action require...
packaging common python namespaces
5,064,951
15
2011-02-21T10:41:31Z
5,065,350
14
2011-02-21T11:24:11Z
[ "python", "namespaces", "packaging", "pypi" ]
I'm looking to package and upload a library I have to PyPI in the next few days, but I'm a little unsure about my approach to the namespace. I have a few otherwise unrelated projects with a similar approach and wanted to give them all the same namespace. For example: * Library 1 namespace: `abc.seo` * Library 2 names...
In each project base directory, create the following structure: ``` /setup.py /abc/__init__.py /abc/seo/ ``` `/abc/__init__.py` contains : ``` __import__('pkg_resources').declare_namespace(__name__) ``` `setup.py` contains : ``` setup(..., packages: ['abc', 'abc.seo'], namespace_packages = ['abc'] ... ...
Memory Limit for Jython
5,065,840
3
2011-02-21T12:19:39Z
5,072,995
10
2011-02-22T00:56:48Z
[ "python", "jvm", "jython" ]
How can I set the JVM memory limit (-Xmx option for Java) for my Jython program? I understand that Jython **2.5** introduces the -J option in order to send options to the JVM: ``` jython -J-Xmx8000m ``` However, I have to work with **Jython 2.2a0 on java1.6.0\_23**, which does not have that option.
You could set environment variables `JAVA_OPTIONS` (for jython < 2.5) or `JAVA_MEM` for jython 2.5 e.g.: ``` alias jython1G="JAVA_OPTIONS=\"-Xmx1000m $JAVA_OPTIONS\" /usr/bin/jython" ```
Update app engine entity
5,066,357
4
2011-02-21T13:12:13Z
5,066,445
40
2011-02-21T13:20:33Z
[ "python", "google-app-engine" ]
How to update existing record in app engine.
As long as an entity has a key defined it will be updated on `put()`: ``` record = Record(value='foo') # This creates a new record record.put() record.value = 'shmoo' # This updates it record.put() key = record.key() record2 = Record.get(key) record2.value = 'bar' # Yet again this updates the same record record2.put...
Setting up Django with Eclipse - "Django not found"
5,066,381
4
2011-02-21T13:14:08Z
5,068,519
11
2011-02-21T16:32:16Z
[ "python", "django", "eclipse", "pydev", "django-errors" ]
I'm trying to setup Django with Eclipse. Right now I'm creating a new Pydev Django project, and getting "Django not found" error message. When I try to verify Django is integrated via the command line, it works. ``` >>> import django >>> print django.get_version() 1.2.5 ``` I have exactly two python installations, 2...
If you added the python interpreter before installing django, you can get this error message. Remove the python interpreter from eclipse and add it again. Eclipse will do some caching/searching of some sort. This solved my same problem.
python udisks - enumerating device information
5,067,005
5
2011-02-21T14:13:33Z
5,081,937
12
2011-02-22T17:59:24Z
[ "python", "linux", "udev" ]
It's apparently possible to get a lot of info relating to attached disks using the udisks binary: ``` udisks --show-info /dev/sda1 ``` udisks is apparently just enumerating the data which is available udev. Is it possible to get this information using python? say for example if i just wanted to retrieve the device s...
You can use Udisks via dbus directly in python. ``` import dbus bus = dbus.SystemBus() ud_manager_obj = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks") ud_manager = dbus.Interface(ud_manager_obj, 'org.freedesktop.UDisks') for dev in ud_manager.EnumerateDevices(): device_obj = bus.get_object("...
get UTC timestamp in python with datetime
5,067,218
36
2011-02-21T14:36:30Z
5,499,906
28
2011-03-31T12:33:18Z
[ "python", "datetime", "timestamp", "utc" ]
Is there a way to get the UTC timestamp by specifying the date? What I would expect: ``` datetime(2008, 1, 1, 0, 0, 0, 0) ``` should result in ``` 1199145600 ``` Creating a naive datetime object means that there is no time zone information. If I look at the documentation for datetime.utcfromtimestamp, creating a U...
**What is a naïve `datetime`?** Default `datetime` objects are said to be "naïve": they keep time information without the time zone information. Think about naïve `datetime` as a relative number (ie: `+4`) without a clear origin (in fact your origin will be common throughout your system boundary). Think about aware...
get UTC timestamp in python with datetime
5,067,218
36
2011-02-21T14:36:30Z
11,428,389
15
2012-07-11T08:19:00Z
[ "python", "datetime", "timestamp", "utc" ]
Is there a way to get the UTC timestamp by specifying the date? What I would expect: ``` datetime(2008, 1, 1, 0, 0, 0, 0) ``` should result in ``` 1199145600 ``` Creating a naive datetime object means that there is no time zone information. If I look at the documentation for datetime.utcfromtimestamp, creating a U...
Also note the [calendar.timegm()](http://docs.python.org/library/calendar.html#calendar.timegm) function as described by [this](http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-datetime-object-to-unix-timestamp/) blog entry: ``` import calendar calendar.timegm(utc_timetuple) ``` The output should agree wi...
get UTC timestamp in python with datetime
5,067,218
36
2011-02-21T14:36:30Z
13,423,091
9
2012-11-16T19:25:40Z
[ "python", "datetime", "timestamp", "utc" ]
Is there a way to get the UTC timestamp by specifying the date? What I would expect: ``` datetime(2008, 1, 1, 0, 0, 0, 0) ``` should result in ``` 1199145600 ``` Creating a naive datetime object means that there is no time zone information. If I look at the documentation for datetime.utcfromtimestamp, creating a U...
If input datetime object is in UTC: ``` >>> dt = datetime(2008, 1, 1, 0, 0, 0, 0) >>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds() 1199145600.0 ``` Note: it returns float i.e., microseconds are represented as fractions of a second. If input date object is in UTC: ``` >>> from datetime import date >>> utc...
PyGTK: How do I make an image automatically scale to fit it's parent widget?
5,067,310
7
2011-02-21T14:46:25Z
5,069,101
7
2011-02-21T17:22:49Z
[ "python", "image", "gtk", "pygtk" ]
I have a PyGTK app that needs to load an image of unknown size, however I am having the problem that if the image is either very big or very small, the window layout becomes distorted and hard to use. I need some way of making the image automatically scale to fit its parent widget. Unfortunately, after doing some resea...
You can use widget.get\_allocation() to find out the size of the parent widget and pixbuf.scale\_simple to scale the image, like this: ``` allocation = parent_widget.get_allocation() desired_width = allocation.width desired_height = allocation.height pixbuf = gtk.gdk.pixbuf_new_from_file('your_image.png') pixbuf = pi...
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
5,067,654
163
2011-02-21T15:16:04Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
``` import inspect def foo(): print inspect.stack()[0][3] ```
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
5,067,661
68
2011-02-21T15:16:44Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
Python doesn't have a feature to access the function or its name within the function itself. It has been [proposed](http://www.python.org/dev/peps/pep-3130/) but rejected. If you don't want to play with the stack yourself, you should either use `"bar"` or `bar.__name__` depending on context.
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
5,067,858
24
2011-02-21T15:34:31Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
You can get the name that it was defined with using [the approach that @Andreas Jung shows](http://stackoverflow.com/a/5067654), but that may not be the name that the function was called with: ``` import inspect def Foo(): print inspect.stack()[0][3] Foo2 = Foo >>> Foo() Foo >>> Foo2() Foo ``` Whether that dis...
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
15,725,912
15
2013-03-31T03:05:31Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
``` functionNameAsString = sys._getframe().f_code.co_name ``` I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here's a way to get the name of the current function.
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
17,366,561
59
2013-06-28T14:04:54Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
There are a few ways to get the same result: ``` from __future__ import print_function import sys import inspect def what_is_my_name(): print(inspect.stack()[0][0].f_code.co_name) print(inspect.stack()[0][3]) print(inspect.currentframe().f_code.co_name) print(sys._getframe().f_code.co_name) ``` Note ...
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
20,192,278
9
2013-11-25T11:46:55Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
I found a wrapper that will write the function name ``` from functools import wraps def tmp_wrap(func): @wraps(func) def tmp(*args, **kwargs): print func.__name__ return func(*args, **kwargs) return tmp @tmp_wrap def my_funky_name(): print "STUB" my_funky_name() ``` This will print ...
Determine function name from within that function (without using traceback)
5,067,604
174
2011-02-21T15:11:36Z
24,628,710
8
2014-07-08T09:48:23Z
[ "python", "function", "introspection", "traceback" ]
In Python, without using the `traceback` module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing `foo.bar()`, is there a way for bar to know bar's name? Or better yet, `foo.bar`'s name? ``` #foo.py def bar(): print "my name is"...
I keep this handy utility nearby: ``` import inspect myself = lambda: inspect.stack()[1][3] ``` Usage: ``` myself() ```
Python: Replace, rstrip() not able to remove newlines
5,067,856
2
2011-02-21T15:34:16Z
5,067,921
10
2011-02-21T15:40:51Z
[ "python", "replace", "newline" ]
I've got a spreadsheet of information (UTF-8 CSV file being read in by the csv module) that contains information for a large number of products that need to go into an inventory db. I'm trying to setup descriptions from newlined rows of text to a html list tags. The issue I'm having is that the following lines fail to...
From python manual > **str.replace(old, new[, count])** > ***Return a copy of the string with all occurrences of substring old replaced by new***. If the optional argument count is given, only the first count occurrences are replaced. As you can see, it doesn't replace "in place", instead, try: ``` line[2] = "<ul>...
How do you increment file name in Python
5,068,461
2
2011-02-21T16:27:25Z
5,068,492
7
2011-02-21T16:30:04Z
[ "python", "file-io" ]
I'm trying to save a lot of data that needs to be separated in to different files like so data\_1.dat data\_2.dat data\_3.dat data\_4.dat how do I implement this in python?
``` for i in range(10): filename = 'data_%d.dat'%(i,) print filename ```
How do you increment file name in Python
5,068,461
2
2011-02-21T16:27:25Z
5,068,500
7
2011-02-21T16:30:32Z
[ "python", "file-io" ]
I'm trying to save a lot of data that needs to be separated in to different files like so data\_1.dat data\_2.dat data\_3.dat data\_4.dat how do I implement this in python?
``` from itertools import count filename = ("data_%03i.dat" % i for i in count(1)) next(filename) # 'data_001.dat' next(filename) # 'data_002.dat' next(filename) # 'data_003.dat' ```
Bizzarre issue trying to make Rpy2 2.1.9 work with R 2.12.1, using Python 2.6 under Windows xp - Rpy can't find the R.dll?
5,068,760
8
2011-02-21T16:52:25Z
12,130,384
18
2012-08-26T13:09:59Z
[ "python", "windows", "windows-xp", "rpy2" ]
I've been having a real issue trying to make Rpy2 play nice with my R install. I first tried installing the rpy2 MSI package, and this didn't appear to work. When I ran the recommended tests, it was giving me an error saying that it couldn't find the R.dll, because the new R installs (post 2.11) install the DLLs into a...
After many hours of searching on the web and trying out many different things, amongst others encountering the same issues as above, I finally got Rpy2 working on my windows 7 computer! Basically, the crucial help came from this thread: <http://www.mail-archive.com/rpy-list@lists.sourceforge.net/msg03348.html>. Summa...
Handling subprocess crash in Windows
5,069,224
15
2011-02-21T17:33:42Z
5,103,935
15
2011-02-24T11:21:07Z
[ "python", "subprocess" ]
I am running a python script from windows command prompt. It calls the function below, which converts an MP3 file to a wave file using [LAME](http://lame.sourceforge.net/). ``` def convert_mp3_to_wav(input_filename, output_filename): """ converts the incoming mp3 file to wave file """ if not os.path.ex...
After some more googling, I stumbled upon this <http://www.activestate.com/blog/2007/11/supressing-windows-error-report-messagebox-subprocess-and-ctypes> It required a bit of tinkering, but the method below now doesn't get annoying Windows messages :) Note the creationflags=subprocess\_flags in the subprocess.Popen to...