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
DRY way to add created/modified by and time
4,754,485
31
2011-01-21T01:14:03Z
11,031,907
46
2012-06-14T11:15:28Z
[ "python", "django" ]
Having something like * created\_by * created\_date * modified\_by * modified\_date Would be a very common pattern for a lot of tables. 1) You can set created date automatically (but not others) in model.py with ``` created_date = models.DateTimeField(auto_now_add=True, editable=False) ``` 2) You could do created/...
The create/modification dates can be handled by Django now, so they can be implemented like: ``` class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True ``` By adding this to a abstract m...
How to output coverage XML with nosetests?
4,755,131
9
2011-01-21T03:34:40Z
4,755,156
13
2011-01-21T03:41:30Z
[ "python", "code-coverage", "cobertura", "nosetests" ]
I'm trying to output the coverage XML of my nosetests so they show up on Hudson. The line I'm executing is: ``` nosetests --with-gae -v --all-modules --with-xunit --with-coverage ``` I see the coverage output in the console, but there's no xml file containing the coverage data. How can I get it to output the coverage...
Once you've run the `nosetests` command, there will be a `.coverage` data file in the directory. If you then run `coverage xml`, it will create a Cobertura-compatible XML file from the `.coverage` file.
List of big-O analysis for Python datastructures
4,755,221
22
2011-01-21T03:57:39Z
4,755,236
29
2011-01-21T04:00:02Z
[ "python", "performance", "data-structures" ]
Is there a list of the different data structures and their big-O access times for Python? I was rummaging through the standard library docs and didn't see any, hence the question. :-)
It's not in the manual, it's [here](http://wiki.python.org/moin/TimeComplexity) on the python wiki. The table also includes complexities for methods for the data structures as well. Thanks for asking, I'd never seen this before until I looked for it.
Python: I'm getting an 'indented block' error on the last 3 quotes (""") of my comments under functions. What's up?
4,755,566
3
2011-01-21T05:03:26Z
4,755,573
16
2011-01-21T05:05:22Z
[ "python", "comments", "indentation" ]
Super odd, no? The offending code: ``` def main(): """ main function """ # Argument handling args = sys.argv[1:] if not args: print "usage is: ... ``` The third quote is where I get the usual indentation error: ``` >>>Import someScript Traceback (most recent call last): File "<stdin>", line 1,...
You need to indent the docstring along with the block for your function. Every colon (`:`) must be immediately followed by an indented block.
python: how to write daemon in Linux
4,755,760
3
2011-01-21T05:38:50Z
4,755,830
7
2011-01-21T05:54:29Z
[ "python", "linux" ]
I have a .py file that is ran by: python a.py & I am using a ssh to run the command, after it I have to log off. I find after some time the process is exited. I suspect it's Linux send some signal to it? I think if I can make the daemon then I can avoid this?
Although nohup will work, it's a quick and dirty solution. To make a proper daemon process you need to use SysV init or (If you are running Ubuntu 6.10+ or Fedora 9+) upstart. Here's a simple script that starts a.py and restarts it whenever it gets killed (up to 5 times inside a 5 minute span): ``` respawn respawn l...
python 2.7 vs python 3.1
4,756,205
12
2011-01-21T06:55:45Z
4,756,269
9
2011-01-21T07:05:50Z
[ "python", "versions" ]
Some python 3 features and modules having been backported to python 2.7 what are the notable differences between python 3.1 and python 2.7?
I think these resources might help you: * A [introduction to Python "3000"](http://www.python.org/doc/essays/ppt/pycon2008/Py3kAndYou.pdf) from Guido van Rossum * [Porting your code to Python 3](http://peadrop.com/slides/mp5.pdf) * and of course the documentation of [changes in Python 3.0](http://docs.python.org/py3k/...
Not quite sure what the point of the %s is in Python, help?
4,756,423
3
2011-01-21T07:33:59Z
4,756,453
14
2011-01-21T07:37:45Z
[ "python", "syntax", "string-formatting" ]
I'm learning Python from a book right now and I can't figure out what the point is of using the %s to site a specific item in a list, string, dictionary, etc. For example: ``` names = ["jones", "cohen", "smith", "griffin"] print(names[1]) print("%s" % names[1]) ``` Both commands print "cohen," what's the point of e...
The idea is to allow you to easily create more complicated output like ``` print("The name is %s!" % names[1]) ``` instead of ``` print("The name is " + names[1] + "!") ``` However, as you're just starting to use Python, you should start learning the [new string formatting syntax](http://docs.python.org/library/str...
How do you set your pythonpath in an already-created virtualenv?
4,757,178
57
2011-01-21T09:24:23Z
4,758,351
77
2011-01-21T11:39:06Z
[ "python", "linux", "unix", "virtualenv" ]
What file do I edit, and how? I created a virtual environment.
If you want to change the `PYTHONPATH` used in a virtualenv, you can add the following line to your virtualenv's `bin/activate` file: ``` export PYTHONPATH="/the/path/you/want" ``` This way, the new `PYTHONPATH` will be set each time you use this virtualenv. **EDIT:** *(to answer @RamRachum's comment)* To have it r...
How do you set your pythonpath in an already-created virtualenv?
4,757,178
57
2011-01-21T09:24:23Z
17,963,979
39
2013-07-31T07:17:49Z
[ "python", "linux", "unix", "virtualenv" ]
What file do I edit, and how? I created a virtual environment.
The comment by @s29 should be an answer: One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do ``` mkvirtualenv myenv workon myenv add2virtualenv . #for current directory add2virtualenv ~/my/path ``` If you want to remove these path edit t...
numpy.ndarray: converting to a "normal" class
4,757,611
6
2011-01-21T10:18:54Z
4,758,961
7
2011-01-21T12:49:06Z
[ "python", "numpy", "python-3.x", "wrapper" ]
[Python 3] I like `ndarray` but I find it annoying to use. Here's one problem I face. I want to write `class Array` that will inherit much of the functionality of ndarray, but has only one way to be instantiated: as a zero-filled array of a certain size. I was hoping to write: ``` class Array(numpy.ndarray): def _...
> Why does ndarray use global (module) functions instead of constructors in many cases? 1. To be compatible/similar to Matlab, where functions like `zeros` or `ones` originally came from. 2. Global factory functions are quick to write and easy to understand. What should the semantics of a constructor be, e.g. how woul...
Modifying a variable in a module imported using from ... import *
4,758,562
6
2011-01-21T12:02:58Z
4,758,580
9
2011-01-21T12:04:22Z
[ "python", "python-3.x", "python-import" ]
Consider the following code: ``` #main.py From toolsmodule import * database = "foo" #toolsmodule database = "mydatabase" ``` As it seems, this creates one variable in each module with different content. How can I modify the variable inside toolsmodule from main? The following does not work: ``` toolsmodule.databas...
Sounds like yet another of the multitude of good reasons not to use `from toolsmodule import *`. If you just do `import toolsmodule`, then you can do `toolsmodule.database = 'foo'`, and everything is wonderful.
Python select random date in current year
4,759,223
6
2011-01-21T13:21:18Z
4,759,779
13
2011-01-21T14:13:58Z
[ "python", "python-datetime" ]
In Python can you select a random date from a year. e.g. if the year was 2010 a date returned could be 15/06/2010
It's much simpler to use ordinal dates (according to which today's date is 734158): ``` from datetime import date import random start_date = date.today().replace(day=1, month=1).toordinal() end_date = date.today().toordinal() random_day = date.fromordinal(random.randint(start_date, end_date)) ``` This will fail for ...
Differences between webapp and web.py
4,759,565
10
2011-01-21T13:54:36Z
4,761,392
18
2011-01-21T16:45:41Z
[ "python", "google-app-engine", "web-applications", "web.py" ]
Webpy.org - [Who uses web.py?](http://webpy.org) > "[web.py inspired the] web framework > we use at FriendFeed [and] the webapp > framework that ships with App > Engine..." > — Brett Taylor, > co-founder of FriendFeed and original > tech lead on Google App Engine [Google App Engine Getting Started for Python](htt...
**web.py experience**: I started to use [web.py](http://webpy.org/) three years ago when I decided to learn some [Python web frameworks](http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#Python). The first thing I loved of web.py was its simplicity; I was searching for an essential microframewor...
Running shell command from Python and capturing the output
4,760,215
343
2011-01-21T14:55:44Z
4,760,274
83
2011-01-21T15:02:38Z
[ "python", "shell", "subprocess" ]
I want to write a function that will execute a shell command and return its output **as a string**, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line. What would be a code example that would do such a thing? For example: ``` def run_comman...
Something like that: ``` def runProcess(exe): p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while(True): retcode = p.poll() #returns None while subprocess is running line = p.stdout.readline() yield line if(retcode is not None): break ``` Note,...
Running shell command from Python and capturing the output
4,760,215
343
2011-01-21T14:55:44Z
4,760,517
343
2011-01-21T15:27:52Z
[ "python", "shell", "subprocess" ]
I want to write a function that will execute a shell command and return its output **as a string**, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line. What would be a code example that would do such a thing? For example: ``` def run_comman...
For convenience, Python 2.7 provides the ``` subprocess.check_output(*popenargs, **kwargs) ``` function, which takes the same arguments as Popen, but returns a string containing the program's output. You can pass `stderr=subprocess.STDOUT` to ensure that error messages are included in the returned output -- but don't...
Running shell command from Python and capturing the output
4,760,215
343
2011-01-21T14:55:44Z
9,266,901
114
2012-02-13T19:41:31Z
[ "python", "shell", "subprocess" ]
I want to write a function that will execute a shell command and return its output **as a string**, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line. What would be a code example that would do such a thing? For example: ``` def run_comman...
This is way easier, but only works on Unix (including Cygwin). ``` import commands print commands.getstatusoutput('wc -l file') ``` it returns a tuple with the (return\_value, output)
Running shell command from Python and capturing the output
4,760,215
343
2011-01-21T14:55:44Z
13,135,985
42
2012-10-30T09:24:46Z
[ "python", "shell", "subprocess" ]
I want to write a function that will execute a shell command and return its output **as a string**, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line. What would be a code example that would do such a thing? For example: ``` def run_comman...
[Vartec's](http://stackoverflow.com/a/4760274/577088) answer doesn't read all lines, so I made a version that did: ``` def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return iter(p.stdout.readline, b'') ...
Running shell command from Python and capturing the output
4,760,215
343
2011-01-21T14:55:44Z
21,867,841
8
2014-02-18T23:32:20Z
[ "python", "shell", "subprocess" ]
I want to write a function that will execute a shell command and return its output **as a string**, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line. What would be a code example that would do such a thing? For example: ``` def run_comman...
Your Mileage May Vary, I attempted @senderle's spin on Vartec's solution in Windows on Python 2.6.5, but I was getting errors, and no other solutions worked. My error was: `WindowsError: [Error 6] The handle is invalid`. I found that I had to assign PIPE to every handle to get it to return the output I expected - the ...
Python import src modules when running tests
4,761,041
9
2011-01-21T16:15:54Z
4,761,058
11
2011-01-21T16:17:53Z
[ "python", "unit-testing", "import" ]
My source files are located under src and my test files are located under tests. When I want to run a test file, say python myTest.py, I get an import error: "No module named ASourceModule.py". How do I import all the modules from source needed to run my tests?
You need to add that directory to the path: ``` import sys sys.path.append('../src') ``` Maybe put this into a module if you are using it a lot.
why this python program is not working?
4,761,138
7
2011-01-21T16:23:57Z
4,761,153
24
2011-01-21T16:25:22Z
[ "python", "random" ]
I have started to learn python. I wrote a very simple program. ``` #!/usr/bin/env python import random x = random.uniform(-1, 1) print str(x) ``` I run this from command prompt. ``` python random.py ``` It returned with error : ``` Traceback (most recent call last): File "random.py", line 2, in <module> impo...
Don't name your file `random.py`, it is importing itself and looking for `uniform` in it. It's a bit of a quirk with how Python imports things, it looks in the local directory first and then starts searching the `PYTHONPATH`. Basically, be careful naming any of your `.py` files the same as one of the standard library ...
Changing the color of the axis, ticks and labels for a plot in matplotlib
4,761,623
34
2011-01-21T17:07:49Z
4,762,002
52
2011-01-21T17:44:30Z
[ "python", "colors", "pyqt", "matplotlib" ]
I'd like to Change the color of the axis, as well as ticks and value-labels for a plot I did using matplotlib an PyQt. Any ideas?
As a quick example (using a slightly cleaner method than the potentially duplicate question): ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(10)) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.spines['bottom'].set_color('red') ax.spines['top'].set_color('red') ax....
Socket.IO Client Library in Python
4,762,086
36
2011-01-21T17:53:07Z
6,193,530
24
2011-05-31T21:03:58Z
[ "python", "client-server", "socket.io" ]
Can anyone recommend a Socket.IO client library for Python? I've had a look around, but the only ones I can find are either server implementations, or depend on a framework such as Twisted. I need a client library that has no dependencies on other frameworks. Simply using one of the many connection types isn't suffic...
First of all, I'm not sure why some of your Socket.IO servers won't support websockets...the intent of Socket.IO is to make front-end browser development of web apps easier by providing an abstracted interface to real-time data streams being served up by the Socket.IO server. Perhaps Socket.IO is not what you should be...
Socket.IO Client Library in Python
4,762,086
36
2011-01-21T17:53:07Z
7,586,302
34
2011-09-28T16:17:45Z
[ "python", "client-server", "socket.io" ]
Can anyone recommend a Socket.IO client library for Python? I've had a look around, but the only ones I can find are either server implementations, or depend on a framework such as Twisted. I need a client library that has no dependencies on other frameworks. Simply using one of the many connection types isn't suffic...
Archie1986's answer was good but has become outdated with socketio updates (more specifically, its protocol : <https://github.com/LearnBoost/socket.io-spec>)... as far as i can tell, you need to perform the handshake manually before you can ask for a transport (e.g., websockets) connection... note that the code below i...
Socket.IO Client Library in Python
4,762,086
36
2011-01-21T17:53:07Z
11,883,600
15
2012-08-09T12:35:25Z
[ "python", "client-server", "socket.io" ]
Can anyone recommend a Socket.IO client library for Python? I've had a look around, but the only ones I can find are either server implementations, or depend on a framework such as Twisted. I need a client library that has no dependencies on other frameworks. Simply using one of the many connection types isn't suffic...
The [socketIO-client](https://github.com/invisibleroads/socketIO-client) library supports event callbacks and channels thanks to the work of contributors and is available on [PyPI](http://pypi.python.org/pypi/socketIO-client) under the MIT license. *Emit with callback.* ``` from socketIO_client import SocketIO def o...
Is it safe to mix readline() and line iterators in python file processing?
4,762,262
14
2011-01-21T18:12:08Z
4,762,355
12
2011-01-21T18:22:49Z
[ "python", "file-io" ]
Is it safe to read some lines with `readline()` and also use `for line in file`, and is it guaranteed to use the same file position? Usually, I want to disregard the first line (headers), so I do this: ``` FI = open("myfile.txt") FI.readline() # disregard the first line for line in FI: my_process(line...
No, [it isn't safe](http://docs.python.org/library/stdtypes.html#file.next): > As a consequence of using a read-ahead > buffer, combining next() with other > file methods (like readline()) does > not work right. You could use `next()` to skip the first line here. You should also test for `StopIteration`, which will b...
Is it possible to override .objects on a django model?
4,762,524
6
2011-01-21T18:40:21Z
4,762,561
14
2011-01-21T18:44:29Z
[ "python", "django", "filtering" ]
I'd like to by default only return "published" instances (published=True). Is it possible to override .objects so that MyModel.objects.all() actually returns MyModel.objects.filter(published=True)? Is this sensible? How would I get the unpublished ones in the rare cases where I did want them?
You can do this by writing a custom [Manager](http://docs.djangoproject.com/en/dev/topics/db/managers/) -- just override the `get_queryset` method and set your `objects` to a Manager instance. For example: ``` class MyModelManager(models.Manager): def get_queryset(self): return super(MyModelManager, self)....
Why can't it find my celery config file?
4,763,072
10
2011-01-21T19:44:02Z
6,973,261
18
2011-08-07T14:03:03Z
[ "python", "django", "celery" ]
> /home/myuser/mysite-env/lib/python2.6/site-packages/celery/loaders/default.py:53: > NotConfigured: No celeryconfig.py > module found! Please make sure it > exists and is available to Python. > NotConfigured) I even defined it in my /etc/profile and also in my virtual environment's "activate". But it's not reading ...
I had a similar problem with my tasks module. A simple ``` # celery config is in a non-standard location import os os.environ['CELERY_CONFIG_MODULE'] = 'mypackage.celeryconfig' ``` in my package's `__init__.py` solved this problem.
Index python dict by object or two floats
4,763,193
5
2011-01-21T19:56:54Z
4,763,336
9
2011-01-21T20:13:34Z
[ "python", "hash", "dictionary", "floating-point" ]
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers. I need to record that, for example: ``` Point(X = 2.765, Y = 3.982) -> 2 Point(X = 33.9, Y = 98.45...
Add a hash method to your Point class: ``` ... def __hash__(self): return hash(self.x) ^ hash(self.y) ... ``` In other words, the hash of a point is a munging of the hash of the x and y coordinates. EDIT: a better hash function (based on comments here) is: ``` ... def __hash__(self): return hash((self.x, se...
SQLAlchemy, clear database content but don't drop the schema
4,763,472
27
2011-01-21T20:30:43Z
5,003,705
29
2011-02-15T12:34:38Z
[ "python", "sqlalchemy", "pylons" ]
I'm developing a Pylons app which is based on exisitng database, so I'm using reflection. I have an SQL file with the schema that I used to create my test database. That's why I can't simply use `drop_all` and `create_all`. I would like to write some unit tests and I faced the problem of clearing the database content ...
I asked about the same thing on the SQLAlchemy Google group, and I got a recipe that appears to work well (all my tables are emptied). See [the thread](http://groups.google.com/group/sqlalchemy/browse_thread/thread/f3f24131164eb93) for reference. My code (excerpt) looks like this: ``` from sqlalchemy import MetaData ...
Overriding class variables in python
4,763,743
8
2011-01-21T20:59:05Z
4,763,796
9
2011-01-21T21:04:52Z
[ "python", "oop", "inheritance", "class-design" ]
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code: ``` #/usr/bin/python2.6 class Base(object): default = "default value in base" def __init__(self): super(Base, self).__init__() @classmethod def showDefaultValue(c...
The class variable is being overwritten. Try ``` @classmethod def showDefaultValue(cls): print "defl == %s" % (cls.default,) ``` The reason your way doesn't work has more to do with the way Python treats default arguments to functions than with class attributes. The default value for `defl` is evaluated at the ti...
Overriding class variables in python
4,763,743
8
2011-01-21T20:59:05Z
4,763,800
10
2011-01-21T21:05:16Z
[ "python", "oop", "inheritance", "class-design" ]
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code: ``` #/usr/bin/python2.6 class Base(object): default = "default value in base" def __init__(self): super(Base, self).__init__() @classmethod def showDefaultValue(c...
``` def showDefaultValue(cls, defl=default): ``` means that `default` gets evaluated when the function is defined, as usual in Python. So the definition looks like this then: ``` def showDefaultValue(cls, defl="default value in base"): ``` This value of `defl` is stored as a default argument on the function object a...
Accessing the outer scope in Python 2.6
4,763,965
5
2011-01-21T21:27:39Z
4,764,098
7
2011-01-21T21:42:02Z
[ "python", "scope" ]
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables: ``` def outer(): s = 'qwerty' n = 123 modify() def modify(): s = 'abcd' n = 456 ``` Is it possible somehow to access the outer scope? Something like `nonlocal` variables from Py3k....
Sometimes I run across code like this. A nested function modifies a mutable object instead of assigning to a `nonlocal`: ``` def outer(): s = [4] def inner(): s[0] = 5 inner() ```
Django template can't loop defaultdict
4,764,110
53
2011-01-21T21:42:50Z
4,764,311
32
2011-01-21T22:07:03Z
[ "python", "django", "loops" ]
``` import collections data = [ {'firstname': 'John', 'lastname': 'Smith'}, {'firstname': 'Samantha', 'lastname': 'Smith'}, {'firstname': 'shawn', 'lastname': 'Spencer'}, ] new_data = collections.defaultdict(list) for d in data: new_data[d['lastname']].append(d['firstname']) print new_data ``` Here's ...
try: ``` dict(new_data) ``` and is better to use iteritems instead of items:)
Django template can't loop defaultdict
4,764,110
53
2011-01-21T21:42:50Z
12,842,716
60
2012-10-11T15:05:36Z
[ "python", "django", "loops" ]
``` import collections data = [ {'firstname': 'John', 'lastname': 'Smith'}, {'firstname': 'Samantha', 'lastname': 'Smith'}, {'firstname': 'shawn', 'lastname': 'Spencer'}, ] new_data = collections.defaultdict(list) for d in data: new_data[d['lastname']].append(d['firstname']) print new_data ``` Here's ...
You can avoid the copy to a new dict by disabling the defaulting feature of *defaultdict* once you are done inserting new values: ``` new_data.default_factory = None ``` **Explanation** The [template variable resolution algorithm in Django](https://docs.djangoproject.com/en/dev/topics/templates/#variables) will atte...
creating dictionary from space separated key=value string in python
4,764,547
7
2011-01-21T22:34:41Z
4,764,592
11
2011-01-21T22:42:27Z
[ "python", "dictionary" ]
I have string as follows: s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"' I want to convert in to a dictionary as follows: ``` key | value -----|-------- key1 | 1234 key2 | string with space key3 | SrtingWithoutSpace ``` How do I do this in python? Thanks.
Try this: ``` >>> import re >>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s)) {'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'} ``` If you also want to strip the quotes: ``` >>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)} ```
creating dictionary from space separated key=value string in python
4,764,547
7
2011-01-21T22:34:41Z
4,764,691
15
2011-01-21T22:54:20Z
[ "python", "dictionary" ]
I have string as follows: s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"' I want to convert in to a dictionary as follows: ``` key | value -----|-------- key1 | 1234 key2 | string with space key3 | SrtingWithoutSpace ``` How do I do this in python? Thanks.
> The [shlex](http://docs.python.org/library/shlex.html) class makes it easy to write > lexical analyzers for simple syntaxes > resembling that of the Unix shell. > This will often be useful for writing > minilanguages, (for example, in run > control files for Python applications) > or for parsing quoted strings. ``` ...
In Python, how do I read the exif data for an image?
4,764,932
37
2011-01-21T23:27:48Z
4,765,242
66
2011-01-22T00:21:34Z
[ "python", "image", "python-imaging-library", "exif" ]
I'm using PIL. How do I turn the EXIF data into a dictionary of stuff?
Try this: ``` import PIL.Image img = PIL.Image.open('img.jpg') exif_data = img._getexif() ``` This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like: ``` import PIL.ExifTags exif = { PIL.ExifTags.TAGS[k]: v fo...
In Python, how do I read the exif data for an image?
4,764,932
37
2011-01-21T23:27:48Z
18,027,454
9
2013-08-02T23:08:00Z
[ "python", "image", "python-imaging-library", "exif" ]
I'm using PIL. How do I turn the EXIF data into a dictionary of stuff?
You can also use the [ExifRead](https://pypi.python.org/pypi/ExifRead) module: ``` import exifread # Open image file for reading (binary mode) f = open(path_name, 'rb') # Return Exif tags tags = exifread.process_file(f) ```
Installing Numpy and Scipy - Can't find system python 2.6
4,765,226
5
2011-01-22T00:18:57Z
4,765,866
8
2011-01-22T02:50:12Z
[ "python", "osx", "numpy", "scipy", "python-2.6" ]
I"m trying to install numpy and scipy for a data analysis class I have this semester. I'm trying to install it from the package on sourceforge.net, but as I follow the wizard I can't select my HD. There is a message saying numpy.1.5.1 requires System Python 2.6. I know it is there as when I type `$ python` version 2.6....
The official [Numpy 1.5.1 installer for Python 2.6](http://sourceforge.net/projects/numpy/files/NumPy/1.5.1/) for OS X appear to require the [python.org Python 2.6](http://www.python.org/download/releases/2.6.6/), not the Apple-supplied Python 2.6.
Repeat Python function call on exception?
4,766,556
7
2011-01-22T06:52:48Z
4,766,569
8
2011-01-22T06:56:37Z
[ "python" ]
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised. Pseudo-code: ``` try: myfunc(x) except myError: ###try to call myfunc(x) again Y number of times, until success(no exceptions raised) otherwise raise myError2 ``` ...
Use a loop ``` i = 0 while True: try: myfunc(x); break; except myError: i = i + 1; # print "Trying again" if i > 5: raise myError2; ```
Repeat Python function call on exception?
4,766,556
7
2011-01-22T06:52:48Z
4,766,592
11
2011-01-22T07:03:27Z
[ "python" ]
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised. Pseudo-code: ``` try: myfunc(x) except myError: ###try to call myfunc(x) again Y number of times, until success(no exceptions raised) otherwise raise myError2 ``` ...
To do precisely what you want, you could do something like the following: ``` import functools def try_x_times(x, exceptions_to_catch, exception_to_raise, fn): @functools.wraps(fn) #keeps name and docstring of old function def new_fn(*args, **kwargs): for i in xrange(x): try: ...
Decrementing for loops
4,767,401
32
2011-01-22T10:57:50Z
4,767,413
59
2011-01-22T11:00:31Z
[ "python", "for-loop", "decrement" ]
I want to have a for loop like so: ``` for counter in range(10,0): print counter, ``` and the output should be 10 9 8 7 6 5 4 3 2 1
``` >>> for counter in range(10, 0, -1): print counter, ``` `step` is -1.
Decrementing for loops
4,767,401
32
2011-01-22T10:57:50Z
4,767,419
22
2011-01-22T11:01:03Z
[ "python", "for-loop", "decrement" ]
I want to have a for loop like so: ``` for counter in range(10,0): print counter, ``` and the output should be 10 9 8 7 6 5 4 3 2 1
Check out the [`range`](http://docs.python.org/library/functions.html#range) documentation, you have to define a negative step: ``` >>> range(10, 0, -1) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] ```
Decrementing for loops
4,767,401
32
2011-01-22T10:57:50Z
4,767,426
8
2011-01-22T11:02:07Z
[ "python", "for-loop", "decrement" ]
I want to have a for loop like so: ``` for counter in range(10,0): print counter, ``` and the output should be 10 9 8 7 6 5 4 3 2 1
You need to give the range a -1 step ``` for i in range(10,0,-1): print i ```
How to transfer basic objects between Ruby and Python?
4,767,514
5
2011-01-22T11:21:47Z
4,767,554
8
2011-01-22T11:31:19Z
[ "python", "ruby", "serialization" ]
Currently I'm using JSON as a serialization format to transfer a simple hash containing strings, numbers and an array from Ruby into a Python script: ``` IO.popen('./convert.py', 'w') do |w| w.write({ :height => height, :width => width, :id => job_id, :data => pix }.to_json) w.write "\n" w.close_write end ...
Maybe [MessagePack](http://msgpack.org/) is the way to go then. Bindings for several languages exist, including Ruby and Python.
How to perform double sort inside an array?
4,768,151
4
2011-01-22T13:43:08Z
4,768,167
7
2011-01-22T13:48:14Z
[ "python", "sorting" ]
I don't know the exact term exists for this type of sorting. Here is the problem - I have a class `foo` ``` class foo: def __init__(self,a1,a2): self.attrb1 = a1 self.attrb2 = a2 def sort(self): return self.attrb1 ``` An array "bar" contain objects of type foo. I want to sort the arra...
``` bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True) ``` And you don't need to define `foo.sort`
I can't install python-ldap
4,768,446
130
2011-01-22T14:44:26Z
4,768,467
146
2011-01-22T14:49:43Z
[ "python", "module", "ldap" ]
When I run the following command: ``` sudo pip install python-ldap ``` I get this error: > In file included from Modules/LDAPObject.c:9: > > Modules/errors.h:8: fatal error: lber.h: No such file or directory Any ideas how to fix this?
The [website](http://www.python-ldap.org/) says that python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called `libldap2-dev`. ``` sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev ```
I can't install python-ldap
4,768,446
130
2011-01-22T14:44:26Z
6,941,608
131
2011-08-04T12:42:24Z
[ "python", "module", "ldap" ]
When I run the following command: ``` sudo pip install python-ldap ``` I get this error: > In file included from Modules/LDAPObject.c:9: > > Modules/errors.h:8: fatal error: lber.h: No such file or directory Any ideas how to fix this?
To install python-ldap successfully with pip, following development libraries are needed (package names taken from ubuntu environment): ``` sudo apt-get install -y python-dev libldap2-dev libsasl2-dev libssl-dev ```
I can't install python-ldap
4,768,446
130
2011-01-22T14:44:26Z
13,159,938
60
2012-10-31T14:11:57Z
[ "python", "module", "ldap" ]
When I run the following command: ``` sudo pip install python-ldap ``` I get this error: > In file included from Modules/LDAPObject.c:9: > > Modules/errors.h:8: fatal error: lber.h: No such file or directory Any ideas how to fix this?
On CentOS/RHEL 6, you need to install: ``` sudo yum install python-devel sudo yum install openldap-devel ``` and yum will also install `cyrus-sasl-devel` as a dependency. Then you can run: ``` pip-2.7 install python-ldap ```
I can't install python-ldap
4,768,446
130
2011-01-22T14:44:26Z
13,759,122
29
2012-12-07T08:00:39Z
[ "python", "module", "ldap" ]
When I run the following command: ``` sudo pip install python-ldap ``` I get this error: > In file included from Modules/LDAPObject.c:9: > > Modules/errors.h:8: fatal error: lber.h: No such file or directory Any ideas how to fix this?
In Ubuntu it looks like this : ``` $ sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev $ sudo pip install python-ldap ```
How to break a line of chained methods in Python?
4,768,941
46
2011-01-22T16:14:20Z
4,768,979
106
2011-01-22T16:19:54Z
[ "python", "coding-style", "pep8" ]
I have a line of the following code (don't blame for naming conventions, they are not mine): ``` subkeyword = Session.query( Subkeyword.subkeyword_id, Subkeyword.subkeyword_word ).filter_by( subkeyword_company_id=self.e_company_id ).filter_by( subkeyword_word=subkeyword_word ).filter_by( subkeyword_act...
You could use additional parenthesis: ``` subkeyword = ( Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word) .filter_by(subkeyword_company_id=self.e_company_id) .filter_by(subkeyword_word=subkeyword_word) .filter_by(subkeyword_active=True) .one() ) ```
How to break a line of chained methods in Python?
4,768,941
46
2011-01-22T16:14:20Z
4,769,685
7
2011-01-22T18:26:12Z
[ "python", "coding-style", "pep8" ]
I have a line of the following code (don't blame for naming conventions, they are not mine): ``` subkeyword = Session.query( Subkeyword.subkeyword_id, Subkeyword.subkeyword_word ).filter_by( subkeyword_company_id=self.e_company_id ).filter_by( subkeyword_word=subkeyword_word ).filter_by( subkeyword_act...
My personal choice would be: ``` subkeyword = Session.query( Subkeyword.subkeyword_id, Subkeyword.subkeyword_word, ).filter_by( subkeyword_company_id=self.e_company_id, subkeyword_word=subkeyword_word, subkeyword_active=True, ).one() ```
How to break a line of chained methods in Python?
4,768,941
46
2011-01-22T16:14:20Z
15,905,678
21
2013-04-09T15:10:46Z
[ "python", "coding-style", "pep8" ]
I have a line of the following code (don't blame for naming conventions, they are not mine): ``` subkeyword = Session.query( Subkeyword.subkeyword_id, Subkeyword.subkeyword_word ).filter_by( subkeyword_company_id=self.e_company_id ).filter_by( subkeyword_word=subkeyword_word ).filter_by( subkeyword_act...
This is a case where a line continuation character is preferred to open parentheses. The need for this style becomes more obvious as method names get longer and as methods start taking arguments: ``` subkeyword = Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word) \ .filter_by(subke...
Learning Python from Ruby; Differences and Similarities
4,769,004
107
2011-01-22T16:24:53Z
4,769,056
9
2011-01-22T16:34:14Z
[ "python", "ruby" ]
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different? I'm looking for a list similar to a primer I wrote for [Learning Lua for JavaScripters](http://phrogz.net/Lua/LearningLua_FromJS.html): simple things l...
My suggestion: Don't try to learn the differences. Learn how to approach the problem in Python. Just like there's a Ruby approach to each problem (that works very well givin the limitations and strengths of the language), there's a Python approach to the problem. they are both different. To get the best out of each lan...
Learning Python from Ruby; Differences and Similarities
4,769,004
107
2011-01-22T16:24:53Z
4,769,092
128
2011-01-22T16:41:45Z
[ "python", "ruby" ]
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different? I'm looking for a list similar to a primer I wrote for [Learning Lua for JavaScripters](http://phrogz.net/Lua/LearningLua_FromJS.html): simple things l...
Here are some key differences to me: 1. Ruby has blocks; Python does not. 2. Python has functions; Ruby does not. In Python, you can take any function or method and pass it to another function. In Ruby, everything is a method, and methods can't be directly passed. Instead, you have to wrap them in Proc's to pass them....
Learning Python from Ruby; Differences and Similarities
4,769,004
107
2011-01-22T16:24:53Z
4,769,134
7
2011-01-22T16:49:18Z
[ "python", "ruby" ]
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different? I'm looking for a list similar to a primer I wrote for [Learning Lua for JavaScripters](http://phrogz.net/Lua/LearningLua_FromJS.html): simple things l...
I know little Ruby, but here are a few bullet points about the things you mentioned: * `nil`, the value indicating lack of a value, would be `None` (note that you check for it like `x is None` or `x is not None`, not with `==` - or by coercion to boolean, see next point). * `None`, zero-esque numbers (`0`, `0.0`, `0j`...
Learning Python from Ruby; Differences and Similarities
4,769,004
107
2011-01-22T16:24:53Z
4,770,112
25
2011-01-22T19:39:54Z
[ "python", "ruby" ]
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different? I'm looking for a list similar to a primer I wrote for [Learning Lua for JavaScripters](http://phrogz.net/Lua/LearningLua_FromJS.html): simple things l...
I've just spent a couple of months learning Python after 6 years of Ruby. There really was no great comparison out there for the two languages, so I decided to man up and write one myself. Now, it *is* mainly concerned with functional programming, but since you mention Ruby's `inject` method, I'm guessing we're on the ...
Learning Ruby from Python; Differences and Similarities
4,769,478
17
2011-01-22T17:48:46Z
4,769,544
7
2011-01-22T17:59:46Z
[ "python", "ruby" ]
Inspired by [Learning Python from Ruby; Differences and Similarities](http://stackoverflow.com/questions/4769004/learning-python-from-ruby-differences-and-similarities). I'm in the exact opposite boat - I'm pretty well-versed in Python, but I need to start learning Ruby soon (and Rails later, but that's another topic)...
The Ruby website has [a page exactly on this topic](http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/). It's a summary list, so other answers with more best-practice style comments are surely a good idea.
Learning Ruby from Python; Differences and Similarities
4,769,478
17
2011-01-22T17:48:46Z
4,770,146
11
2011-01-22T19:47:49Z
[ "python", "ruby" ]
Inspired by [Learning Python from Ruby; Differences and Similarities](http://stackoverflow.com/questions/4769004/learning-python-from-ruby-differences-and-similarities). I'm in the exact opposite boat - I'm pretty well-versed in Python, but I need to start learning Ruby soon (and Rails later, but that's another topic)...
While not targeted at Python programmers, you might find [this idomatic Ruby talk](http://cbcg.net/talks/rubyidioms/) useful. (Related, but for Python: [Code Like a Pythonista: Idiomatic Python](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html))
Python - Convert UTC datetime string to local datetime
4,770,297
99
2011-01-22T20:14:50Z
4,770,688
14
2011-01-22T21:22:15Z
[ "python", "datetime", "utc", "localtime" ]
I've never had to convert time to and from utc. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to utc, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily conver...
See the [datetime](http://docs.python.org/library/datetime.html?highlight=tzinfo#module-datetime) documentation on [tzinfo](http://docs.python.org/library/datetime.html?highlight=tzinfo#tzinfo-objects) objects. You have to implement the timezones you want to support yourself. The are examples at the bottom of the docum...
Python - Convert UTC datetime string to local datetime
4,770,297
99
2011-01-22T20:14:50Z
4,771,733
161
2011-01-23T01:23:37Z
[ "python", "datetime", "utc", "localtime" ]
I've never had to convert time to and from utc. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to utc, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily conver...
If you don't want to provide your own `tzinfo` objects, check out the [python-dateutil](http://niemeyer.net/python-dateutil) library. It provides `tzinfo` implementations on top of a [zoneinfo (Olson) database](http://en.wikipedia.org/wiki/Tz_database) such that you can refer to time zone rules by a somewhat canonical ...
Python - Convert UTC datetime string to local datetime
4,770,297
99
2011-01-22T20:14:50Z
19,238,551
9
2013-10-08T03:24:25Z
[ "python", "datetime", "utc", "localtime" ]
I've never had to convert time to and from utc. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to utc, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily conver...
Here's a resilient method that doesn't depend on any external libraries: ``` from datetime import datetime import time def datetime_from_utc_to_local(utc_datetime): now_timestamp = time.time() offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp) return utc_datetime + o...
PermanentTaskFailure: 'module' object has no attribute 'Migrate'
4,770,669
8
2011-01-22T21:20:23Z
4,777,368
7
2011-01-23T23:46:04Z
[ "python", "google-app-engine", "gae-datastore" ]
I'm using Nick Johnson's Bulk Update library on google appengine (http://blog.notdot.net/2010/03/Announcing-a-robust-datastore-bulk-update-utility-for-App-Engine). It works wonderfully for other tasks, but for some reason with the following code: ``` from google.appengine.ext import db from myapp.main.models import ...
It seems likely that your declaration of the 'Migrate' class is in the handler script (Eg, the one directly invoked by app.yaml). A limitation of deferred is that you can't use it to call functions defined in the handler module. Incidentally, my bulk update library is deprecated in favor of App Engine's mapreduce supp...
Functional Equivalent to Python Statement Logic
4,770,727
3
2011-01-22T21:29:02Z
4,770,759
9
2011-01-22T21:35:07Z
[ "python", "scripting" ]
I'm trying to find the functional equivalent of logic statements in Python (e.g. and/or/not). I thought I had found them in the `operator` module, but the behavior is remarkable different. For example, the `and` statement does the behavior I want, whereas `operator.and_` seems to requir an explicit type comparison, or...
The functions `operator.and_` and `operator.or_` are the equivalent of the **bit-wise** "and" function and "or" function, respectively. There are no functions representing the `and` and `or` operators in `operator`, but you can use the built-ins `any()` and `all()` instead. They will take a single sequence as argument,...
Should I make silent exceptions louder in tkinter?
4,770,993
11
2011-01-22T22:17:09Z
4,771,200
18
2011-01-22T23:02:28Z
[ "python", "exception", "user-interface", "tkinter", "warnings" ]
If I run the following code from a terminal, I get a helpful error message in the terminal: ``` import Tkinter as tk master = tk.Tk() def callback(): raise UserWarning("Exception!") b = tk.Button(master, text="This will raise an exception", command=callback) b.pack() tk.mainloop() ``` However, if I run it wit...
There is `report_callback_exception` to do this: ``` import traceback import tkMessageBox # You would normally put that on the App class def show_error(self, *args): err = traceback.format_exception(*args) tkMessageBox.showerror('Exception',err) # but this works too tk.Tk.report_callback_exception = show_erro...
Django queryset filter for blank FileField?
4,771,464
26
2011-01-23T00:06:28Z
4,988,004
39
2011-02-14T00:55:41Z
[ "python", "django" ]
How do I perform a Django queryset filter looking for blank files in "FileField" fields? The field isn't null, it has a FileObject in it that doesn't have a file.
I was having this issue too, and finally found the solution! ``` no_files = MyModel.objects.filter(foo='') ``` This works because internally, the `FileField` is represented as a local file path in a `CharField`, and Django stores non-files as an empty string `''` in the database.
I need to define __setattr__ for assignment of fields without properties, but use the setter/getter functions for fields with a property defined
4,772,095
4
2011-01-23T03:12:37Z
4,772,241
8
2011-01-23T04:05:47Z
[ "python" ]
Defining `__setattr__` overrides all setter methods / properties I define in a class. I want to use the defined setter methods in the property, if a property exists for a field and use `self.__dict__[name] = value` otherwise. Help! I found one solution that used `__setitem__`, but this does not work for me Where are ...
You need to rewrite your `__setattr__` function. As per the [docs](http://docs.python.org/reference/datamodel.html#customizing-attribute-access), new style classes should use `baseclass.__setattr__(self, attr, value)` instead of `self.__dict__[attr] = value`. The former will lookup any descriptors whereas the latter wi...
Python or Ruby Interpreter on iOS
4,772,591
29
2011-01-23T06:19:18Z
4,773,274
8
2011-01-23T10:11:39Z
[ "iphone", "python", "ruby", "ios", "lua" ]
I found this application on the app store: [iLuaBox](http://www.mobileappsystems.com/software/iluabox) and I wondered if there was anything else like this for the iPhone without jailbreaking but instead for Python or Ruby? Lua is probably similar for me to play around with the basic programming I do anyway but I thoug...
The Agreement about Apple not accepting any coding language layer has been removed not too long ago. I guess we will have to wait a little to see complex language like Python and Ruby interpreter. Since Lua is a scripting language, it is easier to port it.
Python or Ruby Interpreter on iOS
4,772,591
29
2011-01-23T06:19:18Z
8,759,459
17
2012-01-06T14:38:04Z
[ "iphone", "python", "ruby", "ios", "lua" ]
I found this application on the app store: [iLuaBox](http://www.mobileappsystems.com/software/iluabox) and I wondered if there was anything else like this for the iPhone without jailbreaking but instead for Python or Ruby? Lua is probably similar for me to play around with the basic programming I do anyway but I thoug...
A python interpreter App called ***[Python for iOS](http://pythonforios.com/)*** is available on the App store: *<http://itunes.apple.com/us/app/python-for-ios/id485729872?mt=8&uo=4>* --- ***Full disclosure:*** I am the sole creator/developer of the ***[Python for iOS](http://pythonforios.com/)*** App.
Python or Ruby Interpreter on iOS
4,772,591
29
2011-01-23T06:19:18Z
11,488,477
9
2012-07-15T00:33:42Z
[ "iphone", "python", "ruby", "ios", "lua" ]
I found this application on the app store: [iLuaBox](http://www.mobileappsystems.com/software/iluabox) and I wondered if there was anything else like this for the iPhone without jailbreaking but instead for Python or Ruby? Lua is probably similar for me to play around with the basic programming I do anyway but I thoug...
Pythonista by omz:software (I have no affiliation) just came out for the iPad and it looks pretty good. Has an extended keyboard, code completion and other nice things. <http://omz-software.com/pythonista/> App Store link: <http://itunes.apple.com/app/id528579881>
Creating a CLI (Shell?) in Python
4,772,847
4
2011-01-23T07:55:41Z
4,774,088
8
2011-01-23T13:31:24Z
[ "python", "command-line-interface" ]
I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that. I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this: ``` def delete(loc): if os.path.exis...
Or if you want a cmd shell, you could use the cmd lib. It offers python interfaces to making command lines. <http://docs.python.org/library/cmd.html>
How are Python in-place operator functions different than the standard operator functions?
4,772,987
5
2011-01-23T08:44:34Z
4,773,111
14
2011-01-23T09:21:38Z
[ "python", "function", "operator-keyword" ]
*Why isn't `operator.iadd(x, y)` equivalent to `z = x; z += y`?* And *how does `operator.iadd(x, y)` differ from `operator.add(x, y)`?* From the [docs](http://docs.python.org/library/operator.html): > Many operations have an “in-place” > version. The following functions > provide a more primitive access to > in-p...
First, you need to understand the difference between `__add__` and `__iadd__`. An object's `__add__` method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter. An object's `__iadd__` method also takes two parameters, but makes the change in-place, modifying the conten...
Count duplicates between 2 lists
4,775,004
3
2011-01-23T16:49:02Z
4,775,018
8
2011-01-23T16:50:52Z
[ "python", "list", "loops" ]
``` a = [1, 2, 9, 5, 1] b = [9, 8, 7, 6, 5] ``` I want to count the number of duplicates between the two lists. So using the above, I want to return a count of 2 because 9 and 5 are common to both lists. I tried something like this but it didn't quite work. ``` def filter_(x, y): count = 0 for num in y: ...
You can use [`set.intersection`](http://docs.python.org/library/stdtypes.html#set.intersection): ``` >>> set(a).intersection(set(b)) # or just: set(a).intersection(b) set([9, 5]) ``` Or, for the length of the intersection: ``` >>> len(set(a).intersection(set(b))) 2 ``` Or, more concise: ``` >>> len(set(a) & set(b)...
Count duplicates between 2 lists
4,775,004
3
2011-01-23T16:49:02Z
4,775,027
10
2011-01-23T16:52:24Z
[ "python", "list", "loops" ]
``` a = [1, 2, 9, 5, 1] b = [9, 8, 7, 6, 5] ``` I want to count the number of duplicates between the two lists. So using the above, I want to return a count of 2 because 9 and 5 are common to both lists. I tried something like this but it didn't quite work. ``` def filter_(x, y): count = 0 for num in y: ...
Shorter way and better: ``` >>> a = [1, 2, 9, 5, 1] >>> b = [9, 8, 7, 6, 5] >>> len(set(a) & set(b)) # & is intersection - elements common to both 2 ``` Why your code doesn't work: ``` >>> def filter_(x, y): ... count = 0 ... for num in y: ... if num in x: ... count += 1 ....
__main__ and scoping in python
4,775,579
13
2011-01-23T18:30:15Z
4,775,596
17
2011-01-23T18:32:56Z
[ "python", "scope" ]
I was somehow surprised by the following behavior: ``` def main(): print "%s" % foo if __name__ == "__main__": foo = "bar" main() ``` i.e. a module function has access to enclosing variables in the `__main__`. What's the explanation for it?
Variables in the current modules global scope are visible everywhere in the module -- this rule also holds for the `__main__` module. From [Guido's tutorial](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces): > At any time during execution, there are at least three nested scopes whose namespa...
Python IDLE: Change Python Version
4,776,359
9
2011-01-23T20:39:55Z
4,776,403
8
2011-01-23T20:49:00Z
[ "python", "editor", "version", "python-idle" ]
I have Python 2.x and 3.x on my machine (Mac OS X 10.6). For some things I want to use ver 2, but for others I want ver 3. I like the IDLE software for editing/running, but it always uses version 3. **Is there any way to change the version of the interpreter that IDLE uses?** Thanks!
There are different versions of IDLE installed for each Python version. Depending on how you installed Python on Mac OS X, you may find different folders in `/Applications`. Look for a Python 3.n (n = 1 or 2) folder with an IDLE in it. Or, from a terminal command line, you may find an `idle2.6` and an `idle3` or `idle3...
How to safely get the file extension from a URL?
4,776,924
11
2011-01-23T22:15:36Z
4,776,958
8
2011-01-23T22:21:58Z
[ "python", "file" ]
Consider the following URLs ``` http://m3u.com/tunein.m3u http://asxsomeurl.com/listen.asx:8024 http://www.plssomeotherurl.com/station.pls?id=111 http://22.198.133.16:8024 ``` Whats the proper way to determine the file extensions (.m3u/.asx/.pls)? Obviously the last one doesn't have a file extension. EDIT: I forgot ...
The *real* proper way is to not use file extensions at all. Do a GET (or HEAD) request to the URL in question, and use the returned "Content-type" HTTP header to get the content type. File extensions are unreliable. See [Multimedia MIME reference](http://www.w3schools.com/media/media_mimeref.asp) for a list of useful ...
How to safely get the file extension from a URL?
4,776,924
11
2011-01-23T22:15:36Z
4,776,959
25
2011-01-23T22:22:03Z
[ "python", "file" ]
Consider the following URLs ``` http://m3u.com/tunein.m3u http://asxsomeurl.com/listen.asx:8024 http://www.plssomeotherurl.com/station.pls?id=111 http://22.198.133.16:8024 ``` Whats the proper way to determine the file extensions (.m3u/.asx/.pls)? Obviously the last one doesn't have a file extension. EDIT: I forgot ...
Use `urlparse` to parse the path out of the URL, then `os.path.splitext` to get the extension. ``` import urlparse, os url = 'http://www.plssomeotherurl.com/station.pls?id=111' path = urlparse.urlparse(url).path ext = os.path.splitext(path)[1] ``` Note that the extension may not be a reliable indicator of the type o...
Shortcut for if __name__ == '__main__':
4,777,031
9
2011-01-23T22:36:43Z
4,777,047
9
2011-01-23T22:39:53Z
[ "python" ]
Is there a shorter form of this? ``` if __name__ == '__main__': ``` It is pretty tedious to write, and also doesn't look very nice in my opinion :)
Basically every python programmer does that. So simply live with it. ;) Besides that you could omit it completely if your script is always meant to be run as an application and not imported as a module - but you are encouraged to use it anyway, even if it's not really necessary.
Shortcut for if __name__ == '__main__':
4,777,031
9
2011-01-23T22:36:43Z
4,813,472
11
2011-01-27T06:39:41Z
[ "python" ]
Is there a shorter form of this? ``` if __name__ == '__main__': ``` It is pretty tedious to write, and also doesn't look very nice in my opinion :)
PEP299 proposed a solution to this wart, namely having a special function name `__main__`. It was rejected, partly because: > Guido pronounced that he doesn't like > the idea anyway as it's "not worth the > change (in docs, user habits, etc.) > and there's nothing particularly > broken." <http://www.python.org/dev/pe...
What does Python optimization (-O or PYTHONOPTIMIZE) do?
4,777,113
30
2011-01-23T22:52:56Z
4,777,156
39
2011-01-23T23:02:36Z
[ "python", "optimization", "python-3.x" ]
The docs only say that Python interpreter performs "basic optimizations", without going into any detail. Obviously, it's implementation dependent, but is there any way to get a feel for what type of things could be optimized, and how much run-time savings it could generate? Is there any downside to using -O? The only...
In Python 2.7, `-O` has the following effect: * the byte code extension changes to `.pyo` * sys.flags.optimize gets set to 1 * `__debug__` is False * asserts don't get executed In addition `-OO` has the following effect: * doc strings are not available To verify the effect for a different release of CPython, grep t...
python: sorting two lists of polygons for intersections
4,777,495
4
2011-01-24T00:15:55Z
4,777,525
8
2011-01-24T00:23:19Z
[ "python", "sorting", "geometry", "gis" ]
I have two big lists of polygons. Using python, I want to take each polygon in list 1, and find the results of its geometric intersection with the polygons in list 2 (I'm using [shapely](http://trac.gispython.org/lab/wiki/Shapely) to do this). So for polygon *i* in list 1, there may be several polygons in list 2 that...
[Quadtrees](http://en.wikipedia.org/wiki/Quadtree) are often used for the purpose of narrowing down the sets of polygons that need to be checked against each other - two polygons only need to be checked against each other if they both occupy at least one of the same regions in the quadtree. How deep you make your quadt...
converting string to long in python
4,777,972
21
2011-01-24T02:07:31Z
4,777,991
12
2011-01-24T02:10:27Z
[ "python" ]
Python provides a convenient method long() to convert string to long: ``` long('234') ``` ; converts '234' into a long If user keys in 234.89 then python will raise an error message: ``` ValueError: invalid literal for long() with base 10: '234.89' ``` How should we a python programmer handles scenarios where a st...
Well, longs can't hold anything but integers. One option is to use a float: `float('234.89')` The other option is to truncate or round. Converting from a float to a long will truncate for you: `long(float('234.89'))` ``` >>> long(float('1.1')) 1L >>> long(float('1.9')) 1L >>> long(round(float('1.1'))) 1L >>> long(ro...
converting string to long in python
4,777,972
21
2011-01-24T02:07:31Z
4,778,034
15
2011-01-24T02:18:22Z
[ "python" ]
Python provides a convenient method long() to convert string to long: ``` long('234') ``` ; converts '234' into a long If user keys in 234.89 then python will raise an error message: ``` ValueError: invalid literal for long() with base 10: '234.89' ``` How should we a python programmer handles scenarios where a st...
`long`can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, `float` the value before calling the `long`. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just...
Ways to store and access large (~10 GB) lists in Python?
4,778,089
9
2011-01-24T02:31:27Z
4,778,137
9
2011-01-24T02:42:44Z
[ "python", "list", "nlp", "pickle", "shelve" ]
I have a large set of strings that I'm using for natural language processing research, and I'd like a nice way to store it in Python. I could use pickle, but loading the entire list into memory would then be an impossibility (I believe), as it's about 10 GB large, and I don't have that much main memory. Currently I ha...
Depending upon how you intend to get at the data, SQLite3 might be the best approach. SQLite3 is excellent at random access to relational data, but if your data is not very relational, it might not make as much sense. (Even if all your have is an 'id' number and then your string, I think SQLite3 for underlying storage ...
How do I use Django groups and permissions?
4,778,685
58
2011-01-24T04:36:12Z
4,784,936
88
2011-01-24T17:19:15Z
[ "python", "django", "django-permissions" ]
I understand the basic user stuff. I know authentication, login, creating accounts, etc. But now I want to work on groups and permissions. Where is the documentation for django groups/permissions? This is not it: <http://docs.djangoproject.com/en/dev/topics/auth/>
I suppose the first question you need to ask are what permissions do you need and what sort. By what sort, I mean do you want Model- or Object-level. To clarify the difference say you have a model Car. If you want to give permissions on all cars, then Model-level is appropriate, but if you want to give permissions on a...
how to replace (update) text in a file line by line
4,778,697
7
2011-01-24T04:39:06Z
4,778,773
7
2011-01-24T04:53:29Z
[ "python" ]
I am trying to replace text in a text file by reading each line, testing it, then writing if it needs to be updated. I DO NOT want to save as a new file, as my script already backs up the files first and operates on the backups. Here is what I have so far... I get fpath from os.walk() and I guarantee that the pathmatc...
First, you want to write the line whether it matches the pattern or not. Otherwise, you're writing out only the matched lines. Second, between reading the lines and writing the results, you'll need to either truncate the file (can `f.seek(0)` then `f.truncate()`), or close the original and reopen. Picking the former, ...
how to replace (update) text in a file line by line
4,778,697
7
2011-01-24T04:39:06Z
4,779,164
8
2011-01-24T06:16:11Z
[ "python" ]
I am trying to replace text in a text file by reading each line, testing it, then writing if it needs to be updated. I DO NOT want to save as a new file, as my script already backs up the files first and operates on the backups. Here is what I have so far... I get fpath from os.walk() and I guarantee that the pathmatc...
1. Open the file for read and copy all of the lines into memory. Close the file. 2. Apply your transformations on the lines in memory. 3. Open the file for write and write out all the lines of text in memory. --- ``` with open(filename, "r") as f: lines = (line.rstrip() for line in f) altered_lines = [some_fu...
Python Tutorial Question: Ends With Function
4,779,790
4
2011-01-24T07:59:50Z
4,779,820
15
2011-01-24T08:04:09Z
[ "python" ]
I have a python tutorial question which i couldn't get past. The question as follow: **Ends With** Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). My solution:...
What about using python's builtin [`str.endswith()`](http://docs.python.org/library/stdtypes.html#str.endswith) method? ``` def end_other(a, b): a_lower = a.lower() b_lower = b.lower() return a_lower.endswith(b_lower) or b_lower.endswith(a_lower) ```
Python Tutorial Question: Ends With Function
4,779,790
4
2011-01-24T07:59:50Z
4,780,039
7
2011-01-24T08:41:05Z
[ "python" ]
I have a python tutorial question which i couldn't get past. The question as follow: **Ends With** Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). My solution:...
I think this is what you were actually trying to do: ``` def end_other ( a, b ): a = a.lower() b = b.lower() if a == b: return True elif len( a ) > len( b ): return b == a[-len( b ):] else: return a == b[-len( a ):] ``` You had a couple of mistakes in your solution: * `s1[...
Vim : Moving Through Code
4,780,429
8
2011-01-24T09:31:01Z
4,780,672
8
2011-01-24T09:57:01Z
[ "javascript", "python", "vim", "code-navigation" ]
I want to be able to navigate the cursor across functions using Vim. Mainly, I want a command to allow me to go to the next function, like `}` allows me to go to the next paragraph. I found this: [Go to the end of the C++ function in Vim](http://stackoverflow.com/questions/674930/go-to-the-end-of-the-c-function-in-vim...
In a Python file I find: * `}` will take me to the end of a block, * `]]` will take me to the start of the next function. * `[[` takes me to the start of the current function, or the one above if I keep pressing. `]}` didn't seem to work though.
N dimensional arrays - Python/Numpy
4,780,791
3
2011-01-24T10:11:18Z
4,780,929
9
2011-01-24T10:26:43Z
[ "python", "math", "numpy", "scipy" ]
just wondering if there is any clever way to do the following. **I have an N dimensional array representing a 3x3 grid** ``` grid = [[1,2,3], [4,5,6], [7,8,9]] ``` In order to get the **first row** I do the following: ``` grid[0][0:3] >> [1,2,3] ``` In order to get the **first column** I would like...
Yes, there is something like that in Numpy: ``` import numpy as np grid = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) grid[0,:] # array([1, 2, 3]) grid[:,0] # array([1, 4, 7]) ```
python unicode beginner : how to print out a series of letters?
4,780,985
5
2011-01-24T10:33:58Z
4,781,007
10
2011-01-24T10:38:00Z
[ "python", "unicode", "iteration" ]
I'de like to iterate through a list and print it out (for later use with the curses library) : * U+0080 ... U+00FF: Latin-1 Supplement * U+0100 ... U+017F: Latin Extended-A * U+0180 ... U+024F: Latin Extended-B * U+0250 ... U+02AF: IPA Extensions * U+02B0 ... U+02FF: Spacing Modifier Letters * U+0300 ... U+036F: Combi...
What about : <http://docs.python.org/howto/unicode.html> ``` for i in xrange(0x80, 0xFF): print unichr(i) ```
Speedier/less resource-demolishing way to strip html from large files than BeautifulSoup? Or, a better way to use BeautifulSoup?
4,781,833
5
2011-01-24T12:15:40Z
4,781,893
13
2011-01-24T12:21:55Z
[ "python", "html", "parsing", "performance", "beautifulsoup" ]
Currently I am having trouble typing this because, according to `top`, my processor is at 100% and my memory is at 85.7%, all being taken up by python. Why? Because I had it go through a 250-meg file to remove markup. 250 megs, that's it! I've been manipulating these files in python with so many other modules and thin...
lxml.html is FAR more efficient. <http://lxml.de/lxmlhtml.html> ![enter image description here](http://i.stack.imgur.com/0ToVM.png) <http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/> Looks like this will do what you want. ``` import lxml.html t = lxml.html.fromstring("...") t.text_content() ``...
What is an expression in Python?
4,782,590
5
2011-01-24T13:34:18Z
4,782,649
12
2011-01-24T13:40:34Z
[ "python" ]
I have some confusion about its meaning or definition. Isn't that some code that produce or calculate new data values? (Says Zelle in his book) Then I wonder if a string data type is an expression. If it is, then what does `eval()` do when its argument is a string? The book by Zelle says`eval(<string>)` evaluates `...
Expressions **represent** something, like a number, a string, or an instance of a class. Any value is an expression! Anything that **does something** is a statement. Any assignment to a variable or function call is a statement. Any value contained in that statement in an expression. `foo = "hello"` is a statement tha...
Install tkinter for Python
4,783,810
57
2011-01-24T15:36:36Z
4,784,123
84
2011-01-24T16:04:29Z
[ "python", "linux", "tkinter", "install" ]
I am trying to import Tkinter. However, I get an error stating that Tkinter has not been installed: > ImportError: No module named \_tkinter, please install the python-tk package I could probably install it using synaptic manager (can I?), however, I would have to install it on every machine I program on. Would it be...
It is not very easy to install Tkinter locally to use with system-provided Python. You may build it from sources, but this is usually not the best idea with a binary package-based distro you're apparently running. It's safer to `apt-get install python-tk` on your machine(s). (Works on Debian-derived distributions like...
Install tkinter for Python
4,783,810
57
2011-01-24T15:36:36Z
10,015,546
25
2012-04-04T16:37:58Z
[ "python", "linux", "tkinter", "install" ]
I am trying to import Tkinter. However, I get an error stating that Tkinter has not been installed: > ImportError: No module named \_tkinter, please install the python-tk package I could probably install it using synaptic manager (can I?), however, I would have to install it on every machine I program on. Would it be...
If, like me, you don't have root privileges on your network because of your wonderful friends in I.S., and you are working in a local install you may have some problems with the above approaches. I spent ages on Google - but in the end, it's easy. Download the tcl and tk from <http://www.tcl.tk/software/tcltk/downloa...
Install tkinter for Python
4,783,810
57
2011-01-24T15:36:36Z
11,496,983
19
2012-07-16T00:56:15Z
[ "python", "linux", "tkinter", "install" ]
I am trying to import Tkinter. However, I get an error stating that Tkinter has not been installed: > ImportError: No module named \_tkinter, please install the python-tk package I could probably install it using synaptic manager (can I?), however, I would have to install it on every machine I program on. Would it be...
If you are using Python 3 it might be because you are typing `Tkinter` not `tkinter`
Install tkinter for Python
4,783,810
57
2011-01-24T15:36:36Z
11,690,261
18
2012-07-27T14:50:43Z
[ "python", "linux", "tkinter", "install" ]
I am trying to import Tkinter. However, I get an error stating that Tkinter has not been installed: > ImportError: No module named \_tkinter, please install the python-tk package I could probably install it using synaptic manager (can I?), however, I would have to install it on every machine I program on. Would it be...
Actually, you just need to use the following to install the tkinter for python3: ``` sudo apt-get install python3-tk ```
Install tkinter for Python
4,783,810
57
2011-01-24T15:36:36Z
20,075,485
12
2013-11-19T15:26:54Z
[ "python", "linux", "tkinter", "install" ]
I am trying to import Tkinter. However, I get an error stating that Tkinter has not been installed: > ImportError: No module named \_tkinter, please install the python-tk package I could probably install it using synaptic manager (can I?), however, I would have to install it on every machine I program on. Would it be...
For Python 2.7: > You don't need to download Tkinter - it's an integral part of all Python distributions (except binary distributions for platforms that don't support Tcl/Tk). as it says [here](http://ftp.ntua.gr/mirror/python/topics/tkinter/download.html). In my case, on Windows, what helped was reinstalling the Pyt...