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
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
27,071,962
27
2014-11-21T23:15:46Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
This option seems to me more straightforward and readable: ``` pip install -U `pip list --outdated | awk '{ print $1}'` ``` (`awk '{ print $1}'` selects the first word of the line (separated by a space)) And this version allows for the suppression of warning message from `pip list --outdated`: ``` pip install -U `p...
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
33,667,992
54
2015-11-12T09:20:27Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
Works on Windows. Should be good for others too. ($ is whatever directory you're in, in command prompt. eg. C:/Users/Username>) do ``` $ pip freeze > requirements.txt ``` then do ``` $ pip install -r requirements.txt --upgrade ``` If you have a problem with a certain package stalling the upgrade (numpy sometimes),...
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
37,739,555
13
2016-06-10T03:47:23Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
This seems more concise. ``` pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U ``` Explanation: `pip list --outdated` gets lines like these ``` urllib3 (1.7.1) - Latest: 1.15.1 [wheel] wheel (0.24.0) - Latest: 0.29.0 [wheel] ``` In `cut -d ' ' -f1`, `-f1` means to get the first column, `-d ' '` sets ...
Python: Figure out local timezone
2,720,319
28
2010-04-27T10:20:24Z
2,721,038
21
2010-04-27T12:18:24Z
[ "python", "datetime", "time", "timezone", "utc" ]
I want to compare UTC timestamps from a log file with local timestamps. When creating the local `datetime` object, I use something like: ``` >>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0, tzinfo=pytz.timezone('Israel')) ``` I want to find an automatic tool that would repl...
Try [dateutil](http://labix.org/python-dateutil), which has a [tzlocal](http://labix.org/python-dateutil#head-5fb12f4538c5a2fd83f87eea8e6c0ddd47f8b4b0) type that does what you need.
Python: Figure out local timezone
2,720,319
28
2010-04-27T10:20:24Z
17,363,006
13
2013-06-28T10:50:45Z
[ "python", "datetime", "time", "timezone", "utc" ]
I want to compare UTC timestamps from a log file with local timestamps. When creating the local `datetime` object, I use something like: ``` >>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0, tzinfo=pytz.timezone('Israel')) ``` I want to find an automatic tool that would repl...
> to compare UTC timestamps from a log file with local timestamps. It is [hard to find out Olson TZ name for a local timezone](http://stackoverflow.com/q/7669938/4279) in a portable manner. Fortunately, you don't need it to perform the comparison. [`tzlocal` module](https://github.com/regebro/tzlocal) returns a pytz ...
how to remove attribute of a etree Element?
2,720,396
15
2010-04-27T10:31:30Z
2,720,418
22
2010-04-27T10:34:45Z
[ "python", "xml", "lxml", "elementtree" ]
I've Element of etree having some attributes - how can we delete the attribute of perticular etree Element.
The [`.attrib` member of the element object](http://effbot.org/zone/element.htm#attributes) contains the dict of attributes - you can use `.pop("key")` or `del` [like you would on any other dict](http://docs.python.org/library/stdtypes.html#mapping-types-dict) to remove a key-val pair.
Use Twisted's getPage as urlopen?
2,720,484
4
2010-04-27T10:48:20Z
2,720,864
19
2010-04-27T11:53:32Z
[ "python", "django", "twisted", "urllib2", "urllib" ]
I would like to use **Twisted non-blocking getPage** method within a webapp, but it feels quite complicated to use such function compared to urlopen. This is an example of what I'm trying to achive: ``` def web_request(request): response = urllib.urlopen('http://www.example.org') return HttpResponse(len(respons...
The thing to realize about non-blocking operations (which you seem to explicitly want) is that you can't really write sequential code with them. The operations don't block because they don't wait for a result. They start the operation and return control to your function. So, `getPage` doesn't return a file-like object ...
One letter game Issue?
2,721,514
8
2010-04-27T13:19:59Z
2,722,965
10
2010-04-27T16:21:17Z
[ "python", "optimization", "letter" ]
Recently at a job interview I was given the following problem: 1. Write a script capable of running on the command line as python 2. It should take in two words on the command line (or optionally if you'd prefer it can query the user to supply the two words via the console). 3. Given those two words: a. Ensure they...
I wouldn't say your solution is *wrong*, but it is a little slow. For two reasons. 1. Breadth-first-search is going to visit all paths of length one shorter than is needed, plus some-to-all of paths of length needed, before it can give you an answer. A best-first-search (A\*) will ideally skip most irrelevant paths. 2...
Fastest way to generate delimited string from 1d numpy array
2,721,521
13
2010-04-27T13:20:43Z
13,861,407
16
2012-12-13T14:00:28Z
[ "python", "numpy" ]
I have a program which needs to turn many large one-dimensional numpy arrays of floats into delimited strings. I am finding this operation quite slow relative to the mathematical operations in my program and am wondering if there is a way to speed it up. For example, consider the following loop, which takes 100,000 ran...
A little late, but this is faster for me: ``` #generate an array with strings x_arrstr = np.char.mod('%f', x) #combine to a string x_str = ",".join(x_arrstr) ``` Speed up is on my machine about 1.5x
How to convert a Date string to a DateTime object?
2,721,782
20
2010-04-27T13:56:13Z
2,721,807
30
2010-04-27T13:58:14Z
[ "python", "datetime" ]
I have following date: ``` 2005-08-11T16:34:33Z ``` I need to know if this is date is before or after *datetime(2009,04,01)* and I can't seem to find a method that will convert that string to something that lets me compare it to *datetime(2009,04,01)* in a meaningful way.
Since the string is in ISO format, it can be meaningfully compared directly with the ISO format version of the `datetime` you mention: ``` >>> s='2005-08-11T16:34:33Z' >>> t=datetime.datetime(2009,04,01) >>> t.isoformat() '2009-04-01T00:00:00' >>> s < t Traceback (most recent call last): File "<stdin>", line 1, in <...
Using Models and Forms outside of Django?
2,721,938
7
2010-04-27T14:17:42Z
2,750,087
10
2010-05-01T13:26:22Z
[ "python", "django", "django-models" ]
Is it possible to run a view file using Django Model and Form outside of the Django environment?
It is possible. Django is fairly good at being straight python without much magic, so you can usually decouple things. Views are just functions, and can be called from any other python code. To use the ORM, you'll have to set up the django environment in your script. Looking at a "manage.py" file shows how to do this:...
How to do dependency injection python-way?
2,722,501
12
2010-04-27T15:23:53Z
2,722,808
14
2010-04-27T16:00:11Z
[ "python", "design-patterns", "dependency-injection" ]
I've been reading a lot about python-way lately so my question is > How to do dependency injection python-way? I am talking about usual scenarios when, for example, service A needs access to UserService for authorization checks.
It all depends on the situation. For example, if you use dependency injection for testing purposes -- so you can easily mock out something -- you can often forgo injection altogether: you can instead mock out the module or class you would otherwise inject: ``` subprocess.Popen = some_mock_Popen result = subprocess.cal...
writing a fast parser in python
2,722,995
7
2010-04-27T16:24:46Z
2,723,031
7
2010-04-27T16:30:29Z
[ "python", "parsing", "arff" ]
I've written a hands-on recursive pure python parser for a some file format ([ARFF](http://weka.wikispaces.com/ARFF+%28developer+version%29)) we use in one lecture. Now running my exercise submission is awfully slow. Turns out by far the most time is spent in my parser. It's consuming a lot of CPU time, the HD is not t...
You could use [ANTLR](http://antlr.org/) or [pyparsing](http://pyparsing.wikispaces.com/), they might speed up your parsing process. And if you want to keep your current code, you might want to look at [Cython](http://cython.org)/[PyPy](http://pypy.org/), which increases your perfomance (sometimes upto 4x).
how to find recursively for a tag of xml using LXML?
2,723,015
23
2010-04-27T16:28:26Z
2,723,968
41
2010-04-27T18:38:18Z
[ "python", "xml", "find", "lxml", "elementtree" ]
using lxml is it possible to find recursively for tag " f1 ", i tried findall method but it works only for immediate children. I think I should go for BeautifulSoup for this !!!
You can use XPath to search recursively: ``` >>> from lxml import etree >>> q = etree.fromstring('<xml><hello>a</hello><x><hello>b</hello></x></xml>') >>> q.findall('hello') # Tag name, first level only. [<Element hello at 414a7c8>] >>> q.findall('.//hello') # XPath, recursive. [<Element hello at 414a7c8>, <Eleme...
how to find recursively for a tag of xml using LXML?
2,723,015
23
2010-04-27T16:28:26Z
8,991,579
14
2012-01-24T17:49:54Z
[ "python", "xml", "find", "lxml", "elementtree" ]
using lxml is it possible to find recursively for tag " f1 ", i tried findall method but it works only for immediate children. I think I should go for BeautifulSoup for this !!!
`iterfind()` iterates over all Elements that match the path expression `findall()` returns a list of matching Elements `find()` efficiently returns only the first match `findtext()` returns the .text content of the first match **Illustrative Examples:** ``` >>> root = etree.XML("<root><a x='123'>aText<b/><c/><b/><...
python: list manipulation
2,723,404
4
2010-04-27T17:17:23Z
2,723,422
8
2010-04-27T17:19:30Z
[ "python", "list" ]
I have a list `L` of objects (for what it's worth this is in scons). I would like to create two lists `L1` and `L2` where `L1` is `L` with an item `I1` appended, and `L2` is `L` with an item `I2` appended. I would use `append` but that modifies the original list. How can I do this in Python? (sorry for the beginner q...
``` L1 = L + [i1] L2 = L + [i2] ``` That is probably the simplest way. Another option is to copy the list and then append: ``` L1 = L[:] #make a copy of L L1.append(i1) ```
How to get HTTP status message in (py)curl?
2,723,715
15
2010-04-27T18:02:39Z
2,736,722
20
2010-04-29T11:02:08Z
[ "python", "libcurl", "pycurl", "http-status" ]
spending some time studying pycurl and libcurl documentation, i still can't find a (simple) way, how to get HTTP status message (reason-phrase) in pycurl. status code is easy: ``` import pycurl import cStringIO curl = pycurl.Curl() buff = cStringIO.StringIO() curl.setopt(pycurl.URL, 'http://example.org') curl.setopt...
i've found a solution myself, which does what i need, but could be more robust (works for HTTP). it's based on a fact that captured headers obtained by `pycurl.HEADERFUNCTION` include the status line. ``` import pycurl import cStringIO import re curl = pycurl.Curl() buff = cStringIO.StringIO() hdr = cStringIO.Strin...
Why does Python's __import__ require fromlist?
2,724,260
57
2010-04-27T19:15:22Z
2,725,668
103
2010-04-27T22:39:46Z
[ "python", "python-import" ]
In Python, if you want to programmatically import a module, you can do: ``` module = __import__('module_name') ``` If you want to import a submodule, you would think it would be a simple matter of: ``` module = __import__('module_name.submodule') ``` Of course, this doesn't work; you just get `module_name` again. Y...
In fact, the behaviour of `__import__()` is entirely because of the implementation of the `import` statement, which calls `__import__()`. There's basically five slightly different ways `__import__()` can be called by `import` (with two main categories): ``` import pkg import pkg.mod from pkg import mod, mod2 from pkg....
Should I use `import os.path` or `import os`?
2,724,348
74
2010-04-27T19:26:26Z
2,724,611
25
2010-04-27T20:00:04Z
[ "python", "coding-style", "python-import" ]
According to the [official documentation](http://docs.python.org/library/os.path.html), `os.path` is a module. Thus, what is the preferred way of importing it? ``` # Should I always import it explicitly? import os.path ``` Or... ``` # Is importing os enough? import os ``` Please DON'T answer "importing `os` works f...
As per [PEP-20](http://www.python.org/dev/peps/pep-0020/) by Tim Peters, "Explicit is better than implicit" and "Readability counts". If all you need from the `os` module is under `os.path`, `import os.path` would be more explicit and let others know what you really care about. Likewise, PEP-20 also says "Simple is be...
Should I use `import os.path` or `import os`?
2,724,348
74
2010-04-27T19:26:26Z
2,725,195
89
2010-04-27T21:14:58Z
[ "python", "coding-style", "python-import" ]
According to the [official documentation](http://docs.python.org/library/os.path.html), `os.path` is a module. Thus, what is the preferred way of importing it? ``` # Should I always import it explicitly? import os.path ``` Or... ``` # Is importing os enough? import os ``` Please DON'T answer "importing `os` works f...
`os.path` works in a funny way. It looks like `os` should be a package with a submodule `path`, but in reality `os` is a normal module that does magic with `sys.modules` to inject `os.path`. Here's what happens: * When Python starts up, it loads a bunch of modules into `sys.modules`. They aren't bound to any names in ...
Should I use `import os.path` or `import os`?
2,724,348
74
2010-04-27T19:26:26Z
16,233,403
9
2013-04-26T09:43:04Z
[ "python", "coding-style", "python-import" ]
According to the [official documentation](http://docs.python.org/library/os.path.html), `os.path` is a module. Thus, what is the preferred way of importing it? ``` # Should I always import it explicitly? import os.path ``` Or... ``` # Is importing os enough? import os ``` Please DON'T answer "importing `os` works f...
Definitive answer: `import os` and use `os.path`. do not `import os.path` directly. From the documentation of the module itself: ``` >>> import os >>> help(os.path) ... Instead of importing this module directly, import os and refer to this module as os.path. The "os.path" name is an alias for this module on Posix sy...
slicing arrays in numpy/scipy
2,725,750
6
2010-04-27T22:59:53Z
2,725,783
11
2010-04-27T23:07:35Z
[ "python", "numpy", "scipy" ]
I have an array like: ``` a = array([[1,2,3],[3,4,5],[4,5,6]]) ``` what's the most efficient way to slice out a 1x2 array out of this that has only the first two columns of "a"? I.e., ``` array([[2,3],[4,5],[5,6]]) in this case. ``` thanks.
Two dimensional numpy arrays are indexed using `a[i,j]` (not `a[i][j]`), but you can use the same slicing notation with numpy arrays and matrices as you can with ordinary matrices in python (just put them in a single `[]`): ``` >>> from numpy import array >>> a = array([[1,2,3],[3,4,5],[4,5,6]]) >>> a[:,1:] array([[2,...
Schedule Python Script - Windows 7
2,725,754
29
2010-04-27T23:00:41Z
2,725,908
39
2010-04-27T23:37:40Z
[ "python", "windows", "scheduled-tasks" ]
I have a python script which I would like to run at regular intervals. I am running windows 7. What is the best way to accomplish this? Easiest way?
You can do it in the command line as follows: ``` schtasks /Create /SC HOURLY /TN PythonTask /TR "PATH_TO_PYTHON_EXE PATH_TO_PYTHON_SCRIPT" ``` That will create an hourly task called 'PythonTask'. You can replace HOURLY with DAILY, WEEKLY etc. PATH\_TO\_PYTHON\_EXE will be something like: C:\python25\python.exe. Chec...
Schedule Python Script - Windows 7
2,725,754
29
2010-04-27T23:00:41Z
5,314,695
35
2011-03-15T16:21:32Z
[ "python", "windows", "scheduled-tasks" ]
I have a python script which I would like to run at regular intervals. I am running windows 7. What is the best way to accomplish this? Easiest way?
You can use the GUI from the control panel (called "scheduled tasks") to add a task, most of it should be self-explanatory, but there are two things to watch out for: * Make sure you fill in `C:\python27\python.exe` as the program path, and the path to your script as the argument. * If you choose `Run whether user is ...
writing to existing workbook using xlwt
2,725,852
42
2010-04-27T23:25:52Z
2,725,910
17
2010-04-27T23:37:51Z
[ "python", "xlwt", "xlrd" ]
I am unable to find examples where xlwt is used to write into existing files. I have a existing xls file that I need to write to. When I use xlrd to read the file, I cant seem to figure out how to transform the "Book" type returned into a xlwt.Workbook. I would appreciate if someone can point me to an example.
You need `xlutils.copy`. Try something like this: ``` from xlutils.copy import copy w = copy('book1.xls') w.get_sheet(0).write(0,0,"foo") w.save('book2.xls') ``` Keep in mind you can't overwrite cells by default as noted in [this question](http://stackoverflow.com/questions/2679502/python-xlwt-attempt-to-overwrite-ce...
writing to existing workbook using xlwt
2,725,852
42
2010-04-27T23:25:52Z
2,726,298
185
2010-04-28T01:30:54Z
[ "python", "xlwt", "xlrd" ]
I am unable to find examples where xlwt is used to write into existing files. I have a existing xls file that I need to write to. When I use xlrd to read the file, I cant seem to figure out how to transform the "Book" type returned into a xlwt.Workbook. I would appreciate if someone can point me to an example.
Here's some sample code I used recently to do just that. It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file. ``` from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils from xlrd import open_workbook # http://pypi.python.org/py...
how to use @ in python.. and the @property and the @classmethod
2,726,345
4
2010-04-28T01:50:58Z
2,726,358
8
2010-04-28T01:54:48Z
[ "python" ]
this is my code: ``` def a(): print 'sss' @a() def b(): print 'aaa' b() ``` and the Traceback is: ``` sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable ``` so how to use the '@' thanks **updated** ``` class a: ...
A decorator needs to be a callable object (either a function or an object implementing \_\_call\_\_), where the parameter is the function that has been decorated, and the result is a function that will replace the function that has been decorated, so, to use your example of printing 'sss' instead of printing 'aaa': ``...
Django Multiple Choice Field / Checkbox Select Multiple
2,726,476
23
2010-04-28T02:30:37Z
2,729,804
28
2010-04-28T13:27:23Z
[ "python", "django", "select", "checkbox" ]
I have a Django application and want to display multiple choice checkboxes in a user's profile. They will then be able to select multiple items. This is a simplified version of my models.py: ``` from profiles.choices import SAMPLE_CHOICES class Profile(models.Model): user = models.ForeignKey(User, unique=True, v...
The profile choices need to be setup as a ManyToManyField for this to work correctly. So... your model should be like this: ``` class Choices(models.Model): description = models.CharField(max_length=300) class Profile(models.Model): user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user') c...
Django Multiple Choice Field / Checkbox Select Multiple
2,726,476
23
2010-04-28T02:30:37Z
2,734,790
10
2010-04-29T04:34:40Z
[ "python", "django", "select", "checkbox" ]
I have a Django application and want to display multiple choice checkboxes in a user's profile. They will then be able to select multiple items. This is a simplified version of my models.py: ``` from profiles.choices import SAMPLE_CHOICES class Profile(models.Model): user = models.ForeignKey(User, unique=True, v...
Brant's solution is absolutely correct, but I needed to modify it to make it work with multiple select checkboxes and `commit=false`. Here is my solution: models.py ``` class Choices(models.Model): description = models.CharField(max_length=300) class Profile(models.Model): user = models.ForeignKey(User, blank...
Django Multiple Choice Field / Checkbox Select Multiple
2,726,476
23
2010-04-28T02:30:37Z
4,033,308
12
2010-10-27T12:43:40Z
[ "python", "django", "select", "checkbox" ]
I have a Django application and want to display multiple choice checkboxes in a user's profile. They will then be able to select multiple items. This is a simplified version of my models.py: ``` from profiles.choices import SAMPLE_CHOICES class Profile(models.Model): user = models.ForeignKey(User, unique=True, v...
The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet). You *could* use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choic...
How to make lists automatically instantiate on use in Python as they do in Perl?
2,726,632
4
2010-04-28T03:27:52Z
2,726,647
9
2010-04-28T03:33:23Z
[ "python", "perl" ]
In Perl, I can do this: ``` push(@{$h->[x]}, y); ``` Can I simplify the following python codes according to above Perl example? ``` if x not in h: h[x] = [] h[x].append(y) ``` I want to simplify this, because it goes many places in my code, (and I cannot initialize all possible x with []). I do not want to make i...
A very elegant way (since Python 2.5) is to use `defaultdict` from the "collections" module: ``` >>> from collections import defaultdict >>> h = defaultdict(list) >>> h['a'].append('b') >>> h defaultdict(<type 'list'>, {'a': ['b']}) ``` `defaultdict` is like a dict, but provides a default value using whichever constr...
Creating a pygtk text field that only accepts number
2,726,839
2
2010-04-28T04:39:53Z
2,727,085
7
2010-04-28T05:47:26Z
[ "python", "pygtk", "glade" ]
Does anybody know how to create a text field using PyGTK that only accepts number. I am using Glade to build my UI. Cheers,
I wouldn't know about a way to do something like this by simple switching a settings, I guess you will need to handle this via signals, one way would be to connect to the `changed` signal and then filter out anything that's not a number. Simple approach(untested but should work): ``` class NumberEntry(gtk.Entry): ...
Common elements between two lists not using sets in Python
2,727,650
11
2010-04-28T07:53:24Z
2,727,661
8
2010-04-28T07:55:51Z
[ "python", "list", "set" ]
I want count the same elements of two lists. Lists can have duplicate elements, so I can't convert this to sets and use & operator. ``` a=[2,2,1,1] b=[1,1,3,3] ``` set(a) & set(b) work a & b don't work It is possible to do it withoud set and dictonary?
Using sets is the most efficient, but you could always do `r = [i for i in l1 if i in l2]`.
Common elements between two lists not using sets in Python
2,727,650
11
2010-04-28T07:53:24Z
2,728,353
11
2010-04-28T09:48:46Z
[ "python", "list", "set" ]
I want count the same elements of two lists. Lists can have duplicate elements, so I can't convert this to sets and use & operator. ``` a=[2,2,1,1] b=[1,1,3,3] ``` set(a) & set(b) work a & b don't work It is possible to do it withoud set and dictonary?
In Python 3.x (and Python 2.7, when it's released), you can use [collections.Counter](http://docs.python.org/dev/library/collections.html#collections.Counter) for this: ``` >>> from collections import Counter >>> list((Counter([2,2,1,1]) & Counter([1,3,3,1])).elements()) [1, 1] ``` Here's an alternative using [collec...
finding the missing values in a range using any scripting language - perl, python or shell script
2,727,809
7
2010-04-28T08:23:31Z
18,094,097
8
2013-08-07T03:23:07Z
[ "python", "perl", "bash", "shell" ]
I got stuck in one problem of finding the missing values in a range and the range is also variable for the successive rows. ### input ``` 673 673 673 676 676 680 2667 2667 2668 2670 2671 2674 ``` ### output should be like this ``` 674 675 677 678 679 2669 2672 2673 ``` This is just one part and the row values can ...
Pure bash. Use two subshells and run a `diff`, then clean up the results. ``` diff <(cat my_range_with_holes) <(seq 1 1000) | grep '>' | cut -c 3- ```
Python indentation in "empty lines"
2,727,988
23
2010-04-28T08:53:53Z
2,728,019
23
2010-04-28T08:58:27Z
[ "python", "coding-style", "idioms" ]
Which is preferred ("." indicating whitespace)? A) ``` def foo(): x = 1 y = 2 .... if True: bar() ``` B) ``` def foo(): x = 1 y = 2 if True: bar() ``` My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most...
If you use **A**, you could copy paste your block in python shell, **B** will get unexpected indentation error.
Python indentation in "empty lines"
2,727,988
23
2010-04-28T08:53:53Z
2,728,059
16
2010-04-28T09:05:40Z
[ "python", "coding-style", "idioms" ]
Which is preferred ("." indicating whitespace)? A) ``` def foo(): x = 1 y = 2 .... if True: bar() ``` B) ``` def foo(): x = 1 y = 2 if True: bar() ``` My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most...
The [PEP 8](http://www.python.org/dev/peps/pep-0008/) does not seem to be clear on this issue, although the statements about "blank lines" could be interpreted in favor of B. The PEP 8 style-checker (pep8.py) prefers B and warns if you use A; however, both variations are legal. My own view is that since Python will suc...
Passing parameter to base class constructor or using instance variable?
2,728,346
6
2010-04-28T09:48:27Z
2,728,405
7
2010-04-28T09:56:04Z
[ "python", "oop", "parameters", "constructor", "python-3.x" ]
All classes derived from a certain base class have to define an attribute called "path". In the sense of duck typing I could rely upon definition in the subclasses: ``` class Base: pass # no "path" variable here def Sub(Base): def __init__(self): self.path = "something/" ``` Another possiblity would ...
**In Python 3.0+:** I would go with a parameter to the base class's constructor like you have in the second example. As this forces classes which derive from Base to provide the necessary path property, which documents the fact that the class has such a property and that derived classes are required to provide it. Wi...
Python BOM error in Ascii file
2,729,260
4
2010-04-28T12:11:53Z
2,729,303
9
2010-04-28T12:18:37Z
[ "python", "encoding", "ascii", "byte-order-mark" ]
I have a weird, annoying problem with Python 2.6. I'm trying to run this file (and the other), on my Embedded Linux ARM board. <http://svn.tuxisalive.com/software_suite_v3/smart-core/smart-server/trunk/TDSService.py> I get this error: > File "tuxhttpserver.py", line 1 > SyntaxError: encoding problem: with > BOM I kn...
Don't get too hung up on the "with BOM" remark. It's probably not relevant. What this error usually means is that the Python you are trying to run in does not support the encoding you declare. Observe: ``` % head -1 tmp.py # -*- coding: asdfasdfasdf -*- % python tmp.py File "tmp.py", line 1 SyntaxError: encoding pro...
Replacement for htmllib module in Python 3.0
2,730,752
11
2010-04-28T15:14:53Z
2,730,773
9
2010-04-28T15:17:23Z
[ "python", "python-3.x" ]
I want to use the htmllib module but it's been removed from Python 3.0. Does anyone know what's the replacement for this module?
I haven't used it, but it looks like what you want is the [`html.parser`](http://docs.python.org/py3k/library/html.parser.html) library, and possibly also [`html.entity`](http://docs.python.org/py3k/library/html.entities.html).
Replacement for htmllib module in Python 3.0
2,730,752
11
2010-04-28T15:14:53Z
2,730,799
10
2010-04-28T15:19:17Z
[ "python", "python-3.x" ]
I want to use the htmllib module but it's been removed from Python 3.0. Does anyone know what's the replacement for this module?
It is Superseded by HTMLParser see [Python library reorganization](http://www.python.org/dev/peps/pep-3108/)
Finding most recently edited file in python
2,731,014
4
2010-04-28T15:44:56Z
2,731,041
11
2010-04-28T15:48:50Z
[ "python", "file", "path", "folder" ]
I have a set of folders, and I want to be able to run a function that will find the most recently edited file and tell me the name of the file and the folder it is in. Folder layout: ``` root Folder A File A File B Folder B File C File D etc... ``` Any tips to get me started a...
You should look at the [os.walk](http://docs.python.org/library/os.html#os.walk) function, as well as [os.stat](http://docs.python.org/library/os.html#os.stat), which can let you do something like: ``` import os max_mtime = 0 for dirname,subdirs,files in os.walk("."): for fname in files: full_path = os.pa...
Do comments slow down an interpreted language?
2,731,022
51
2010-04-28T15:46:41Z
2,731,049
18
2010-04-28T15:49:35Z
[ "python", "comments", "interpreter", "interpreted-language" ]
I am asking this because I use Python, but it could apply to other interpreted languages as well (Ruby, PHP, JavaScript). Am I slowing down the interpreter whenever I leave a comment in my code? According to my limited understanding of an interpreter, it reads program expressions in as strings and then converts those ...
Comments are usually stripped out in or before the parsing stage, and parsing is very fast, so effectively comments will not slow down the initialization time.
Do comments slow down an interpreted language?
2,731,022
51
2010-04-28T15:46:41Z
2,731,094
52
2010-04-28T15:54:55Z
[ "python", "comments", "interpreter", "interpreted-language" ]
I am asking this because I use Python, but it could apply to other interpreted languages as well (Ruby, PHP, JavaScript). Am I slowing down the interpreter whenever I leave a comment in my code? According to my limited understanding of an interpreter, it reads program expressions in as strings and then converts those ...
For the case of Python, source files are compiled before being executed (the `.pyc` files), and the comments are stripped in the process. So comments *could* slow down the compilation time if you have gazillions of them, but they won't impact the execution time.
Do comments slow down an interpreted language?
2,731,022
51
2010-04-28T15:46:41Z
2,731,154
13
2010-04-28T16:03:27Z
[ "python", "comments", "interpreter", "interpreted-language" ]
I am asking this because I use Python, but it could apply to other interpreted languages as well (Ruby, PHP, JavaScript). Am I slowing down the interpreter whenever I leave a comment in my code? According to my limited understanding of an interpreter, it reads program expressions in as strings and then converts those ...
Well, I wrote a short python program like this: ``` for i in range (1,1000000): a = i*10 ``` The idea is, do a simple calculation loads of times. By timing that, it took 0.35±0.01 seconds to run. I then rewrote it with the whole of the King James Bible inserted like this: ``` for i in range (1,1000000): "...
Python Lambdas and Variable Bindings
2,731,111
6
2010-04-28T15:57:34Z
2,731,158
7
2010-04-28T16:03:59Z
[ "python" ]
I've been working on a basic testing framework for an automated build. The piece of code below represents a simple test of communication between two machines using different programs. Before I actually do any tests, I want to completely define them - so this test below is not actually run until after all the tests have...
The `client` variable is defined in the outer scope, so by the time the `lambda` is run it will always be set to the last client in the list. To get the intended result, you can give the lambda an argument with a default value: ``` passIf = lambda client=client: client.returncode(CMD2) == 0 ``` Since the default val...
Why numpy is 'slow' by itself?
2,731,157
5
2010-04-28T16:03:46Z
2,731,243
12
2010-04-28T16:15:10Z
[ "python", "performance", "numpy", "scientific-computing" ]
Given the [thread here](http://stackoverflow.com/questions/2119761/simple-python-challenge-fastest-bitwise-xor-on-data-buffers/2566106?benchmark#2566106 "here") It seems that numpy is not the most ideal for ultra fast calculation. Does anyone know what overhead we must be aware of when using numpy for numerical calcul...
Well, depends on what you want to do. XOR is, for instance, hardly relevant for someone interested in doing numerical linear algebra (for which numpy is pretty fast, by virtue of using optimized BLAS/LAPACK libraries underneath). Generally, the big idea behind getting good performance from numpy is to amortize the cos...
differences between "d.clear()" and "d={}"
2,732,550
4
2010-04-28T19:30:42Z
2,732,571
19
2010-04-28T19:33:39Z
[ "python", "timing" ]
On my machine, the execution speed between `d.clear()` and `d={}` is over 100ns so am curious why one would use one over the other. ``` import timeit def timing(): d = dict() if __name__=='__main__': t = timeit.Timer('timing()', 'from __main__ import timing') print t.repeat() ```
The difference is that `d = {}` creates a new dictionary and `d.clear()` just empties the dictionary you already have. This subtle difference matters if you have other places in your code holding references to your dictionary. In the first case those other objects won't see any change because you haven't modified the o...
Search over multiple fields
2,732,898
3
2010-04-28T20:29:12Z
2,741,778
9
2010-04-30T01:21:16Z
[ "python", "django", "django-haystack" ]
I think I don't unterstand django-haystack properly: I have a data model containing several fields, and I would to have two of them searched: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True, default=None) twitter_account = models.CharField(max_length=50, blank=False) ``` My se...
I guess thats because haystack uses the document field for generic searches unless you define a specific search for other fields like the twitter\_account field. [from haystack documentation](http://docs.haystacksearch.org/dev/tutorial.html#creating-searchindexes) > Every SearchIndex requires there be > one (and only...
Python: sort a list and change another one consequently
2,732,994
15
2010-04-28T20:41:21Z
2,733,000
16
2010-04-28T20:42:22Z
[ "python", "list", "sorting" ]
I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in two separate lists.. how do I do it?
You could zip the lists and sort the result. Sorting tuples should, by default, sort on the first member. ``` >>> xs = [3,2,1] >>> ys = [1,2,3] >>> points = zip(xs,ys) >>> points [(3, 1), (2, 2), (1, 3)] >>> sorted(points) [(1, 3), (2, 2), (3, 1)] ``` And then to unpack them again: ``` >>> sorted_points = sorted(poi...
Python: sort a list and change another one consequently
2,732,994
15
2010-04-28T20:41:21Z
2,733,056
14
2010-04-28T20:51:17Z
[ "python", "list", "sorting" ]
I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in two separate lists.. how do I do it?
``` >>> xs = [5, 2, 1, 4, 6, 3] >>> ys = [1, 2, 3, 4, 5, 6] >>> xs, ys = zip(*sorted(zip(xs, ys))) >>> xs (1, 2, 3, 4, 5, 6) >>> ys (3, 2, 6, 4, 1, 5) ```
Python: sort a list and change another one consequently
2,732,994
15
2010-04-28T20:41:21Z
2,737,404
8
2010-04-29T12:53:17Z
[ "python", "list", "sorting" ]
I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in two separate lists.. how do I do it?
``` >>> import numpy >>> sorted_index = numpy.argsort(xs) >>> xs = [xs[i] for i in sorted_index] >>> ys = [ys[i] for i in sorted_index] ``` if you can work with numpy.array ``` >>> xs = numpy.array([3,2,1]) >>> xs = numpy.array([1,2,3]) >>> sorted_index = numpy.argsort(xs) >>> xs = xs[sorted_index] >>> ys = ys[sorte...
Disadvantage of Python eggs?
2,733,629
7
2010-04-28T22:46:56Z
2,733,647
8
2010-04-28T22:51:19Z
[ "python", "comparison", "egg" ]
Are there any disadvantages about using eggs through `easy-install` compared to the "traditional" packages/modules/libs?
One (potential) disadvantage is that eggs are zipped by default unless `zip_safe=False` is set in their `setup()` function in `setup.py`. If an egg is zipped, you can't get at the files in it (without unzipping it, obviously). If the module itself uses non-source files (such as templates) it will probably specify `zip_...
Disadvantage of Python eggs?
2,733,629
7
2010-04-28T22:46:56Z
2,734,885
8
2010-04-29T05:02:56Z
[ "python", "comparison", "egg" ]
Are there any disadvantages about using eggs through `easy-install` compared to the "traditional" packages/modules/libs?
Using eggs does cause a long `sys.path`, which has to be searched and when it's *really* long that search can take a while. Only when you get a hundred entries or so is this going to be a problem (but installing a hundred eggs via easy\_install is certainly possible).
Iterating through a JSON object
2,733,813
26
2010-04-28T23:30:21Z
2,733,844
33
2010-04-28T23:37:32Z
[ "python", "dictionary", "loops" ]
``` [ { "title": "Baby (Feat. Ludacris) - Justin Bieber", "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark", "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq", "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400", "pubTime": 1272436673,...
Your loading of the JSON data is a little fragile. Instead of: ``` json_raw= raw.readlines() json_object = json.loads(json_raw[0]) ``` you should really just do: ``` json_object = json.load(raw) ``` You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dic...
Iterating through a JSON object
2,733,813
26
2010-04-28T23:30:21Z
2,733,847
15
2010-04-28T23:38:09Z
[ "python", "dictionary", "loops" ]
``` [ { "title": "Baby (Feat. Ludacris) - Justin Bieber", "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark", "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq", "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400", "pubTime": 1272436673,...
After deserializing the JSON, you have a python object. Use the regular object methods. In this case you have a list made of dictionaries: ``` json_object[0].items() json_object[0]["title"] ``` etc.
Iterating through a JSON object
2,733,813
26
2010-04-28T23:30:21Z
2,741,381
24
2010-04-29T23:24:12Z
[ "python", "dictionary", "loops" ]
``` [ { "title": "Baby (Feat. Ludacris) - Justin Bieber", "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark", "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq", "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400", "pubTime": 1272436673,...
I believe you probably meant: ``` for song in json_object: # now song is a dictionary for attribute, value in song.iteritems(): print attribute, value # example usage ```
Run python file -- what function is main?
2,734,314
9
2010-04-29T01:52:04Z
2,734,319
8
2010-04-29T01:54:31Z
[ "python" ]
I have simple python script, 'first.py': ``` #first.py def firstFunctionEver() : print "hello" firstFunctionEver() ``` I want to call this script using : `python first.py` and have it call the `firstFunctionEver()`. But, the script is ugly -- what function can I put the call to `firstFunctionEver()` in and have ...
``` if __name__ == '__main__': firstFunctionEver() ```
Run python file -- what function is main?
2,734,314
9
2010-04-29T01:52:04Z
2,734,328
24
2010-04-29T01:55:55Z
[ "python" ]
I have simple python script, 'first.py': ``` #first.py def firstFunctionEver() : print "hello" firstFunctionEver() ``` I want to call this script using : `python first.py` and have it call the `firstFunctionEver()`. But, the script is ugly -- what function can I put the call to `firstFunctionEver()` in and have ...
``` if __name__ == "__main__": firstFunctionEver() ``` Read more at the docs [here](http://docs.python.org/tutorial/modules.html).
Is there anyway to get pdb and Mac Terminal to play nicely?
2,735,828
8
2010-04-29T08:34:18Z
2,745,035
8
2010-04-30T14:00:56Z
[ "python", "django", "osx", "terminal", "pdb" ]
When debugging my django apps I use pdb for interactive debugging with `pdb.set_trace()`. However, when I amend a file the local django webserver restarts and then I cant see what I type in the terminal, until I type `reset`. Is there anyway for this to happen automatically? It can be real annoying, having to cancel ...
OK - this works for me I created a ~/.pdbrc and added > import os > os.system("stty sane") Now each time pdb is run it sets the line settings back to sane. If I fall out to the terminal then I still have to do it manually - but it solves having to quit runserver and reset all the time.
Python, add trailing slash to directory string, os independently
2,736,144
38
2010-04-29T09:28:40Z
2,736,172
37
2010-04-29T09:33:48Z
[ "python", "string" ]
How can I add a trailing slash (`/` for \*nix, `\` for win32) to a directory string, if the tailing slash is not already there? Thanks!
``` os.path.normpath(mypath) + os.sep ```
Python, add trailing slash to directory string, os independently
2,736,144
38
2010-04-29T09:28:40Z
2,736,301
19
2010-04-29T09:54:50Z
[ "python", "string" ]
How can I add a trailing slash (`/` for \*nix, `\` for win32) to a directory string, if the tailing slash is not already there? Thanks!
Since you want to connect a directory and a filename, use ``` os.path.join(directory, filename) ``` If you want to get rid of `.\..\..\blah\` paths, use ``` os.path.join(os.path.normpath(directory), filename) ```
Python, add trailing slash to directory string, os independently
2,736,144
38
2010-04-29T09:28:40Z
15,010,678
47
2013-02-21T19:31:50Z
[ "python", "string" ]
How can I add a trailing slash (`/` for \*nix, `\` for win32) to a directory string, if the tailing slash is not already there? Thanks!
`os.path.join(path, '')` will add the trailing slash if it's not already there. You can do `os.path.join(path, '', '')` or `os.path.join(path_with_a_trailing_slash, '')` and you will still only get one trailing slash.
Abstract attributes in Python
2,736,255
14
2010-04-29T09:47:57Z
2,736,417
20
2010-04-29T10:11:00Z
[ "python", "oop", "scala", "abstract-class" ]
What is the shortest / most elegant way to implement the following Scala code with an abstract attribute in Python? ``` abstract class Controller { val path: String } ``` A subclass of `Controller` is enforced to define "path" by the Scala compiler. A subclass would look like this: ``` class MyController exten...
Python has a built-in exception for this, though you won't encounter the exception until runtime. ``` class Base(object): @property def path(self): raise NotImplementedError class SubClass(Base): path = 'blah' ```
Creating a list in Python- something sneaky going on?
2,736,693
8
2010-04-29T10:56:48Z
2,736,723
12
2010-04-29T11:02:08Z
[ "python", "list", "constructor" ]
Apologies if this doesn't make any sense, I'm very new to Python! From testing in an interpreter, I can see that `list()` and `[]` both produce an empty list: ``` >>> list() [] >>> [] [] ``` From what I've learned so far, the only way to create an object is to call its constructor (`__init__`), but I don't see this ...
Those two constructs are handled quite differently: ``` >>> import dis >>> def f(): return [] ... >>> dis.dis(f) 1 0 BUILD_LIST 0 3 RETURN_VALUE >>> def f(): return list() ... >>> dis.dis(f) 1 0 LOAD_GLOBAL 0 (list) 3 CALL_FUNCTIO...
Does Django cache url regex patterns somehow?
2,737,400
4
2010-04-29T12:53:10Z
2,737,495
7
2010-04-29T13:04:57Z
[ "python", "django", "django-urls" ]
I'm a Django newbie who needs help: Even though I change some urls in my urls.py I keep on getting the same error message from Django. Here is the relevant line from my settings.py: ``` ROOT_URLCONF = 'mydjango.urls' ``` Here is my urls.py: ``` from django.conf.urls.defaults import * # Uncomment the next two lines ...
Django compiles the URL regexes when it starts up for performance reasons - restart your server and you should see the new URL working correctly.
How to change the stdin encoding on python
2,737,966
11
2010-04-29T14:07:33Z
2,738,005
16
2010-04-29T14:12:18Z
[ "python", "encoding" ]
I'm using windows and linux machines for the same project. The default encoding for stdin on windows is cp1252 and on linux is utf-8. I would like to change everything to uft-8. Is it possible? How can I do it? Thanks Eduardo
You can do this by not relying on the implicit encoding when printing things. Not relying on that is a good idea in any case -- the implicit encoding is only used when printing to stdout and when stdout is connected to a terminal. A better approach is to use `unicode` everywhere, and use `codecs.open` or `codecs.getwr...
How to change the stdin encoding on python
2,737,966
11
2010-04-29T14:07:33Z
27,425,797
9
2014-12-11T14:58:04Z
[ "python", "encoding" ]
I'm using windows and linux machines for the same project. The default encoding for stdin on windows is cp1252 and on linux is utf-8. I would like to change everything to uft-8. Is it possible? How can I do it? Thanks Eduardo
This is an old question, but just for reference. To read `UTF-8` from `stdin`, use: ``` UTF8Reader = codecs.getreader('utf8') sys.stdin = UTF8Reader(sys.stdin) # Then, e.g.: for _ in sys.stdin: print _.strip() ``` To write `UTF-8` to `stdout`, use: ``` UTF8Writer = codecs.getwriter('utf8') sys.stdout = UTF8Wri...
itertools.islice compared to list slice
2,738,096
10
2010-04-29T14:25:55Z
2,738,746
11
2010-04-29T15:51:34Z
[ "python", "performance", "iteration" ]
I've been trying to apply an algorithm to reduce a python list into a smaller one based on a certain criteria. Due to the large volume of the original list, in the order of 100k elements, I tried to itertools for avoiding multiple memory allocations so I came up with this: ``` reducedVec = [ 'F' if sum( 1 for x in isl...
`islice` works with arbitrary iterables. To do this, rather than jumping straight to the nth element, it has to iterate over the first n-1, throwing them away, then yield the ones you want. Check out the pure Python implementation from the [itertools documentation](http://docs.python.org/2/library/itertools.html#itert...
What's the advantage of using 'with .. as' statement in Python?
2,738,365
18
2010-04-29T14:58:33Z
2,738,401
13
2010-04-29T15:02:34Z
[ "python", "with-statement" ]
``` with open("hello.txt", "wb") as f: f.write("Hello Python!\n") ``` seems to be the same as ``` f = open("hello.txt", "wb") f.write("Hello Python!\n") f.close() ``` What's the advantage of using open .. as instead of f = ? Is it just syntactic sugar? Just saving one line of code?
If `f.write` throws an exception, `f.close()` is called when you use `with` and not called in the second case. Also `f` has a smaller scope and the code is cleaner when using `with.`
What's the advantage of using 'with .. as' statement in Python?
2,738,365
18
2010-04-29T14:58:33Z
2,738,468
24
2010-04-29T15:12:13Z
[ "python", "with-statement" ]
``` with open("hello.txt", "wb") as f: f.write("Hello Python!\n") ``` seems to be the same as ``` f = open("hello.txt", "wb") f.write("Hello Python!\n") f.close() ``` What's the advantage of using open .. as instead of f = ? Is it just syntactic sugar? Just saving one line of code?
In order to be equivalent to the `with` statement version, the code you wrote should look instead like this: ``` f = open("hello.txt", "wb") try: f.write("Hello Python!\n") finally: f.close() ``` While this might seem like syntactic sugar, it ensures that you release resources. Generally the world is more com...
compare two windows paths, one containing tilde, in python
2,738,473
6
2010-04-29T15:12:57Z
3,931,799
8
2010-10-14T09:28:22Z
[ "python", "windows", "directory", "path", "string-comparison" ]
I'm trying to use the TMP environment variable in a program. When I ask for ``` tmp = os.path.expandvars("$TMP") ``` I get ``` C:\Users\STEVE~1.COO\AppData\Local\Temp ``` Which contains the old-school, tilde form. A function I have no control over returns paths like ``` C:\Users\steve.cooper\AppData\Local\Temp\fil...
Here is alternative solution using only [ctypes](http://docs.python.org/library/ctypes.html) from Standard Python Library. ``` tmp = unicode(os.path.expandvars("$TMP")) import ctypes GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW buffer = ctypes.create_unicode_buffer(GetLongPathName(tmp, 0, 0)) GetLongPath...
Testing Python Decorators?
2,738,641
11
2010-04-29T15:35:56Z
2,743,646
18
2010-04-30T09:52:06Z
[ "python", "django", "unit-testing", "decorator", "pyunit" ]
I'm writing some unit tests for a Django project, and I was wondering if its possible (or necessary?) to test some of the decorators that I wrote for it. Here is an example of a decorator that I wrote: ``` class login_required(object): def __init__(self, f): self.f = f def __call__(self, *args): ...
Simply: ``` from nose.tools import assert_equal from mock import Mock class TestLoginRequired(object): def test_no_user(self): func = Mock() decorated_func = login_required(func) request = prepare_request_without_user() response = decorated_func(request) assert not func.cal...
In Windows shell scripting (cmd.exe) how do you assign the stdout of a program to an environment variable?
2,738,673
7
2010-04-29T15:41:20Z
2,738,763
11
2010-04-29T15:54:01Z
[ "python", "windows", "cmd" ]
In UNIX you can assign the output of a script to an environment variable using the technique explained [here](http://stackoverflow.com/questions/2115615/assigning-value-to-shell-variable-using-a-function-return-value-from-python) - but what is the Windows equivalent? I have a python utility which is intended to correc...
Use: ``` for /f "delims=" %A in ('<insert command here>') do @set <variable name>=%A ``` For example: ``` for /f "delims=" %A in ('time /t') do @set my_env_var=%A ``` ...will run the command "time /t" and set the env variable "my\_env\_var" to the result. Remember to use %%A instead of %A if you're running this in...
Lisp's "some" in Python?
2,738,777
10
2010-04-29T15:56:02Z
2,738,793
17
2010-04-29T15:58:00Z
[ "python", "lisp" ]
I have a list of strings and a list of filters (which are also strings, to be interpreted as regular expressions). I want a list of all the elements in my string list that are accepted by at least one of the filters. Ideally, I'd write ``` [s for s in strings if some (lambda f: re.match (f, s), filters)] ``` where so...
There is a function called [`any`](http://docs.python.org/library/functions.html#any) which does roughly want you want. I think you are looking for this: ``` [s for s in strings if any(re.match(f, s) for f in filters)] ```
Lisp's "some" in Python?
2,738,777
10
2010-04-29T15:56:02Z
2,738,833
7
2010-04-29T16:03:15Z
[ "python", "lisp" ]
I have a list of strings and a list of filters (which are also strings, to be interpreted as regular expressions). I want a list of all the elements in my string list that are accepted by at least one of the filters. Ideally, I'd write ``` [s for s in strings if some (lambda f: re.match (f, s), filters)] ``` where so...
``` [s for s in strings if any(re.match (f, s) for f in filters)] ```
Cannot import PyQt4.QtGui
2,738,879
10
2010-04-29T16:08:44Z
2,739,585
9
2010-04-29T17:53:26Z
[ "python", "qt", "pyqt4" ]
I have a working Python 2.6 install and just installed the PyQt4 built for Python 2.6 (available at <http://www.riverbankcomputing.co.uk/software/pyqt/download>). When I try to import PyQt4.QtGui I get the following error: ``` ImportError: DLL load failed: The specified procedure could not be found. ``` I'm on Window...
Add the the PyQt4 directory containing Qt's applications and DLLs to your `PATH` environment variable. In PowerShell, provided you didn't change any of your install paths, that'd be ``` $env:path += ';C:\Python26\Lib\site-packages\PyQt4\bin' ```
Cannot import PyQt4.QtGui
2,738,879
10
2010-04-29T16:08:44Z
5,869,748
7
2011-05-03T12:54:14Z
[ "python", "qt", "pyqt4" ]
I have a working Python 2.6 install and just installed the PyQt4 built for Python 2.6 (available at <http://www.riverbankcomputing.co.uk/software/pyqt/download>). When I try to import PyQt4.QtGui I get the following error: ``` ImportError: DLL load failed: The specified procedure could not be found. ``` I'm on Window...
I found a solution on another forum that worked for me. I needed to copy QtGui4.dll and QtCore4.dll into the ...\Python2.7.1\Lib\site-packages\PyQt4 directory. Note, I left the original in the bin directory.
Retrieve the two highest item from a list containing 100,000 integers
2,739,051
23
2010-04-29T16:33:29Z
2,739,310
44
2010-04-29T17:08:34Z
[ "python", "list", "sorting" ]
How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?
In Python, use `heapq.nlargest`. This is the most flexible approach in case you ever want to handle more than just the top two elements. Here's an example. ``` >>> import heapq >>> import random >>> x = range(100000) >>> random.shuffle(x) >>> heapq.nlargest(2, x) [99999, 99998] ``` Documentation: <http://docs.python...
Retrieve the two highest item from a list containing 100,000 integers
2,739,051
23
2010-04-29T16:33:29Z
2,739,812
14
2010-04-29T18:34:01Z
[ "python", "list", "sorting" ]
How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?
[JacobM's answer](http://stackoverflow.com/questions/2739051/retrieve-the-2-highest-item-from-a-list-containing-100-000-integers/2739090#2739090) is absolutely the way to go. However, there are a few things to keep in mind while implementing what he described. Here's a little play-along-at-home tutorial to guide you th...
Extract list of attributes from list of objects in python
2,739,800
26
2010-04-29T18:31:17Z
2,739,860
33
2010-04-29T18:39:30Z
[ "list", "loops", "python" ]
I have an *uniform* list of objects in python: ``` class myClass(object): def __init__(self, attr): self.attr = attr self.other = None objs = [myClass (i) for i in range(10)] ``` Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function ...
`attrs = [o.attr for o in objs]` was the right code for making a list like the one you describe. Don't try to subclass `list` for this. Is there something you did not like about that snippet?
Extract list of attributes from list of objects in python
2,739,800
26
2010-04-29T18:31:17Z
2,739,874
8
2010-04-29T18:41:29Z
[ "list", "loops", "python" ]
I have an *uniform* list of objects in python: ``` class myClass(object): def __init__(self, attr): self.attr = attr self.other = None objs = [myClass (i) for i in range(10)] ``` Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function ...
You can also write: ``` attr=(o.attr for o in objsm) ``` This way you get a generator that conserves memory. For more benefits look at [Generator Expressions](http://www.python.org/dev/peps/pep-0289/).
Could somebody give me a high-level technical overview of WSGI details behind the scenes vs other web interface approaces with Python?
2,739,892
8
2010-04-29T18:43:20Z
2,741,256
8
2010-04-29T22:46:37Z
[ "python", "mod-wsgi", "wsgi" ]
Firstly: 1. I understand what WSGI is and how to use it 2. I understand what "other" methods (Apache mod-python, fcgi, et al) are, and how to use them 3. I understand their practical differences What ***I don't understand*** is how each of the various "other" methods work compared to something like UWSGI, behind the ...
Except for CGI, a new Python interpreter is nearly never created per request. Read: <http://blog.dscpl.com.au/2009/03/python-interpreter-is-not-created-for.html> This was written in respect of mod\_python but also applies to mod\_wsgi and any WSGI hosting mechanism that uses persistent processes. Also read: <http:/...
Reading numeric Excel data as text using xlrd in Python
2,739,989
14
2010-04-29T18:58:43Z
2,740,525
18
2010-04-29T20:22:06Z
[ "python", "excel", "csv", "xls", "xlrd" ]
I am trying to read in an Excel file using xlrd, and I am wondering if there is a way to ignore the cell formatting used in Excel file, and just import all data as text? Here is the code I am using for far: ``` import xlrd xls_file = 'xltest.xls' xls_workbook = xlrd.open_workbook(xls_file) xls_sheet = xls_workbook.s...
That's because integer values in Excel are imported as floats in Python. Thus, `sheet.cell(r,c).value` returns a float. Try converting the values to integers but first make sure those values were integers in Excel to begin with: ``` cell = sheet.cell(r,c) cell_value = cell.value if cell.ctype in (2,3) and int(cell_val...
Why are filename underscores better than hyphens?
2,740,026
27
2010-04-29T19:03:41Z
2,740,045
38
2010-04-29T19:07:02Z
[ "python" ]
From [Building Skills in Python](http://homepage.mac.com/s_lott/books/python/BuildingSkillsinPython.pdf): "A file name like exercise\_1.py is better than the name execise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisti...
The issue here is that importing files with dashes in their name doesn't work since dashes are minus signs in python. So, if you had your own module you wanted to import, it couldn't have a dash in its name: ``` >>> import test-1 File "<stdin>", line 1 import test-1 ^ SyntaxError: invalid syntax >...
Why are filename underscores better than hyphens?
2,740,026
27
2010-04-29T19:03:41Z
2,740,078
8
2010-04-29T19:11:04Z
[ "python" ]
From [Building Skills in Python](http://homepage.mac.com/s_lott/books/python/BuildingSkillsinPython.pdf): "A file name like exercise\_1.py is better than the name execise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisti...
From that very document (p.368, Section 30.2 'Module Definition'): > Note that a module name must be a valid Python name... A module's name is limited to letters, digits and "\_"s.
Python raises a KeyError (for an out of dictionary key) even though the key IS in the dictionary
2,740,036
8
2010-04-29T19:04:54Z
2,740,050
26
2010-04-29T19:07:44Z
[ "python", "exception", "dictionary", "key" ]
I'm getting a KeyError for an out of dictionary key, even though I know the key IS in fact in the dictionary. Any ideas as to what might be causing this? ``` print G.keys() ``` returns the following: ``` ['24', '25', '20', '21', '22', '23', '1', '3', '2', '5', '4', '7', '6', '9', '8', '11', '10', '13', '12', '15', '...
That's simple, `17 != '17'`
Are there some cases where Python threads can safely manipulate shared state?
2,740,435
5
2010-04-29T20:06:43Z
2,740,494
7
2010-04-29T20:17:03Z
[ "python", "multithreading", "gil" ]
Some discussion in another question has encouraged me to to better understand cases where locking is required in multithreaded Python programs. Per [this](http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/) article on threading in Python, I have several solid, testable examples of pitfal...
Appending to a list is thread-safe, yes. You can only append to a list while holding the GIL, and the list takes care not to release the GIL during the `append` operation (which is, after all, a fairly simple operation.) The *order* in which different thread's append operations go through is of course up for grabs, but...
Python SQLite: database is locked
2,740,806
19
2010-04-29T21:12:15Z
2,741,015
25
2010-04-29T21:48:33Z
[ "python", "sqlite", "pysqlite" ]
I'm trying this code: ``` import sqlite connection = sqlite.connect('cache.db') cur = connection.cursor() cur.execute('''create table item (id integer primary key, itemno text unique, scancode text, descr text, price real)''') connection.commit() cur.close() ``` I'm catching this exception: ``` Traceback...
I'm presuming you are actually using sqlite3 even though your code says otherwise. Here are some things to check: 1. That you don't have a hung process sitting on the file (unix: `$ fuser cache.db` should say nothing) 2. There isn't a cache.db-journal file in the directory with cache.db; this would indicate a crashed ...
Python SQLite: database is locked
2,740,806
19
2010-04-29T21:12:15Z
8,618,328
19
2011-12-23T16:26:09Z
[ "python", "sqlite", "pysqlite" ]
I'm trying this code: ``` import sqlite connection = sqlite.connect('cache.db') cur = connection.cursor() cur.execute('''create table item (id integer primary key, itemno text unique, scancode text, descr text, price real)''') connection.commit() cur.close() ``` I'm catching this exception: ``` Traceback...
Set the timeout parameter in your connect call, as in: ``` connection = sqlite.connect('cache.db', timeout=10) ```
Which Python API should be used with Mongo DB and Django
2,740,837
45
2010-04-29T21:18:20Z
2,741,932
11
2010-04-30T02:17:47Z
[ "python", "django", "mongodb" ]
I have been going back and forth over which Python API to use when interacting with Mongo. I did a quick survey of the landscape and identified three leading candidates. * [PyMongo](http://api.mongodb.org/python/1.6/index.html) * [MongoEngine](http://github.com/hmarr/mongoengine) * [Ming](http://merciless.sourceforge....
I've been working with [Mongokit](http://github.com/namlook/mongokit). Like it so far. Here's a [blog post I referenced when integrating with Django](http://www.peterbe.com/plog/how-and-why-to-use-django-mongokit)
Which Python API should be used with Mongo DB and Django
2,740,837
45
2010-04-29T21:18:20Z
2,749,154
55
2010-05-01T07:02:44Z
[ "python", "django", "mongodb" ]
I have been going back and forth over which Python API to use when interacting with Mongo. I did a quick survey of the landscape and identified three leading candidates. * [PyMongo](http://api.mongodb.org/python/1.6/index.html) * [MongoEngine](http://github.com/hmarr/mongoengine) * [Ming](http://merciless.sourceforge....
As Mike says, you can't avoid PyMongo - all the other interfaces build on top of it. These other interfaces are arguably unnecessary. ORMs such as that used in Django are useful when dealing with SQL because they mitigate the complexity of creating SQL queries and schemas, and parsing result sets into objects. PyMongo...
Simulating C-style for loops in python
2,740,901
17
2010-04-29T21:30:26Z
2,741,943
23
2010-04-30T02:21:14Z
[ "python" ]
(even the title of this is going to cause flames, I realize) Python made the deliberate design choice to have the `for` loop use explicit iterables, with the benefit of considerably simplified code in most cases. However, sometimes it is quite a pain to construct an iterable if your test case and update function are ...
This is the best I can come up with: ``` def cfor(first,test,update): while test(first): yield first first = update(first) def example(blah): print "do some stuff" for i in cfor(0,lambda i:i<blah,lambda i:i+1): print i print "done" ``` I wish python had a syntax for closured e...
Can ElementTree be told to preserve the order of attributes?
2,741,480
14
2010-04-29T23:48:50Z
2,741,758
14
2010-04-30T01:16:37Z
[ "python", "xml", "elementtree" ]
I've written a fairly simple filter in python using ElementTree to munge the contexts of some xml files. And it works, more or less. But it reorders the attributes of various tags, and I'd like it to not do that. Does anyone know a switch I can throw to make it keep them in specified order? ## Context for this I'm ...
Nope. ElementTree uses a dictionary to store attribute values, so it's inherently unordered. Even DOM doesn't guarantee you attribute ordering, and DOM exposes a lot more detail of the XML infoset than ElementTree does. (There are some DOMs that do offer it as a feature, but it's not standard.) Can it be fixed? Maybe...
Can ElementTree be told to preserve the order of attributes?
2,741,480
14
2010-04-29T23:48:50Z
30,902,567
10
2015-06-17T21:19:07Z
[ "python", "xml", "elementtree" ]
I've written a fairly simple filter in python using ElementTree to munge the contexts of some xml files. And it works, more or less. But it reorders the attributes of various tags, and I'd like it to not do that. Does anyone know a switch I can throw to make it keep them in specified order? ## Context for this I'm ...
With help from @bobince's answer and these two ([setting attribute order](http://stackoverflow.com/questions/14257978/elementtree-setting-attribute-order), [overriding module methods](http://stackoverflow.com/questions/10829200/override-module-method-where-from-import-is-used)) I managed to get this monkey patched it'...
Location of global libraries for Python on Mac?
2,741,496
4
2010-04-29T23:53:35Z
2,741,579
12
2010-04-30T00:16:52Z
[ "python", "osx", "configuration", "python-sip" ]
I'm fighting with installation SIP for Python on Mac OS X. Finally after compilation and installation when I run console form folder of SIP (locally) I can import sipconfig, but when I`m in other folder I cant - there is no module called sipconfig. My question is - Where is folder to which I have to copy modules if I ...
Try checking your python's sys.path list with: ``` import sys print sys.path ```
A simple Python deployment problem - a whole world of pain
2,741,507
19
2010-04-29T23:55:50Z
2,807,310
22
2010-05-11T00:18:51Z
[ "python", "linux", "deployment", "pylons" ]
We have several Python 2.6 applications running on Linux. Some of them are Pylons web applications, others are simply long-running processes that we run from the command line using `nohup`. We're also using `virtualenv`, both in development and in production. **What is the best way to deploy these applications to a pro...
Development and deployment of Python code is made much easier by [setuptools](http://peak.telecommunity.com/DevCenter/setuptools) in combination with [virtualenv](http://pypi.python.org/pypi/virtualenv) and [pip](http://pypi.python.org/pypi/pip). ## Core ideas The trickiest part, I've found, is running a development ...
Python Profiling In Windows, How do you ignore Builtin Functions
2,741,520
3
2010-04-29T23:59:50Z
2,741,828
8
2010-04-30T01:40:48Z
[ "python", "optimization", "profiling", "builtin", "cprofile" ]
I have not been capable of finding this anywhere online. I was looking to find out using a profiler how to better optimize my code, and when sorting by which functions use up the most time cumulatively, things like str(), print, and other similar widely used functions eat up much of the profile. What is the best way to...
OK, I assume your *real* goal is to make your code as fast as reasonably possible, right? It is natural to assume you do that by finding out how long your functions take, but there is another way to look at it. Consider as your program runs it traces out a call tree, which is kind of like a real tree outside your win...
Python match and return string in between
2,742,309
16
2010-04-30T04:33:02Z
2,742,324
15
2010-04-30T04:36:53Z
[ "python", "regex" ]
I have ``` stringA = "xxxxxxFoundAaaaaaaaaaaaaaaFoundBxxxxxxx" stringB = "FoundA" stringC = "FoundB" ``` How do I do a regular expression in python in order to return aaaaaaaaaaaaaa? Please help. Thanks in advance.
``` >>> >>> stringA = "xxxxxxFoundAaaaaaaaaaaaaaaFoundBxxxxxxx" >>> stringB = "FoundA" >>> stringC = "FoundB" >>> >>> import re >>> re.search(re.escape(stringB)+"(.*?)"+re.escape(stringC),stringA).group(1) 'aaaaaaaaaaaaaa' >>> ```
Python: How to round 123 to 100 instead of 100.0?
2,742,784
6
2010-04-30T06:50:49Z
2,742,788
11
2010-04-30T06:52:06Z
[ "python", "rounding" ]
> > > round(123,-2) > > > 100.0 How to round it to 100 instead of 100.0?
``` int(round(123,-2)) ``` The [int function](http://docs.python.org/library/functions.html#int) can be used to ***convert a string or number to a plain integer***.