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
Removing pip's cache?
9,510,474
109
2012-03-01T04:06:35Z
29,513,564
21
2015-04-08T11:39:45Z
[ "python", "pip" ]
I need to install psycopg2 v2.4.1 specifically. I accidentally did: ``` pip install psycopg2 ``` Instead of: ``` pip install psycopg2==2.4.1 ``` That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re...
pip can install py ignoring the cache, like this ``` pip --no-cache-dir install scipy ```
Removing pip's cache?
9,510,474
109
2012-03-01T04:06:35Z
31,807,659
57
2015-08-04T11:07:07Z
[ "python", "pip" ]
I need to install psycopg2 v2.4.1 specifically. I accidentally did: ``` pip install psycopg2 ``` Instead of: ``` pip install psycopg2==2.4.1 ``` That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re...
Clear the cache directory where appropriate for your system Linux and Unix ``` ~/.cache/pip # and it respects the XDG_CACHE_HOME directory. ``` OS X ``` ~/Library/Caches/pip ``` Windows ``` <CSIDL_LOCAL_APPDATA>\pip\Cache ```
More than one static path in local Flask instance
9,513,072
21
2012-03-01T08:43:31Z
9,516,694
14
2012-03-01T13:02:09Z
[ "python", "html", "flask" ]
Is that possible to add more static paths for my local dev Flask instance? I want to have default `static` folder for storing js/css/images files for the site and another folder, e.g. `designs` to keep my specific assets. I don't want to place `designs` folder inside `static` if there is a better solution exists.
You can use a Blueprint with its own static dir <http://flask.pocoo.org/docs/blueprints/> Blueprint ``` blueprint = Blueprint('site', __name__, static_url_path='/static/site', static_folder='path/to/files') app.register_blueprint(blueprint) ``` Template ``` {{ url_for('site.static', filename='filename') }} ```
More than one static path in local Flask instance
9,513,072
21
2012-03-01T08:43:31Z
9,519,004
21
2012-03-01T15:32:52Z
[ "python", "html", "flask" ]
Is that possible to add more static paths for my local dev Flask instance? I want to have default `static` folder for storing js/css/images files for the site and another folder, e.g. `designs` to keep my specific assets. I don't want to place `designs` folder inside `static` if there is a better solution exists.
I have been using following approach: ``` # Custom static data @app.route('/cdn/<path:filename>') def custom_static(filename): return send_from_directory(app.config['CUSTOM_STATIC_PATH'], filename) ``` The `CUSTOM_STATIC_PATH` variable is defined in my configuration. And in templates: ``` {{ url_for('custom_sta...
Python: ElementTree, get the namespace string of an Element
9,513,540
9
2012-03-01T09:21:59Z
9,513,853
12
2012-03-01T09:44:36Z
[ "python", "elementtree" ]
This XML file is named `example.xml`: ``` <?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>14.0.0</modelVersion> <groupId>.co...
The namespace should be in [`Element.tag`](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tag) right before the "actual" tag: ``` >>> root = tree.getroot() >>> root.tag '{http://maven.apache.org/POM/4.0.0}project' ``` To know more about namespaces, take a look at [ElementTree:...
Python: ElementTree, get the namespace string of an Element
9,513,540
9
2012-03-01T09:21:59Z
12,946,675
9
2012-10-18T03:34:16Z
[ "python", "elementtree" ]
This XML file is named `example.xml`: ``` <?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>14.0.0</modelVersion> <groupId>.co...
This is a perfect task for a [regular expression](http://docs.python.org/library/re.html). ``` import re def namespace(element): m = re.match('\{.*\}', element.tag) return m.group(0) if m else '' ```
Parsing datetime in Python..?
9,516,025
28
2012-03-01T12:13:58Z
9,516,071
11
2012-03-01T12:16:53Z
[ "python", "datetime", "format" ]
I have a system (developed in Python) that accepts **datetime as string in VARIOUS formats** and i have to **parse** them..Currently datetime string formats are : ``` Fri Sep 25 18:09:49 -0500 2009 2008-06-29T00:42:18.000Z 2011-07-16T21:46:39Z 1294989360 ``` Now i want a **generic parser** that can convert any of ...
You should look into the [`dateutil`](http://labix.org/python-dateutil) package.
Parsing datetime in Python..?
9,516,025
28
2012-03-01T12:13:58Z
9,516,358
42
2012-03-01T12:35:03Z
[ "python", "datetime", "format" ]
I have a system (developed in Python) that accepts **datetime as string in VARIOUS formats** and i have to **parse** them..Currently datetime string formats are : ``` Fri Sep 25 18:09:49 -0500 2009 2008-06-29T00:42:18.000Z 2011-07-16T21:46:39Z 1294989360 ``` Now i want a **generic parser** that can convert any of ...
As @TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically: ``` >>> from dateutil.parser import parse >>> parse("Fri Sep 25 18:09:49 -0500 2009") datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000)) >>> parse("2008-06-29T00:42:18.00...
pyodbc - How to perform a select statement using a variable for a parameter
9,518,148
5
2012-03-01T14:40:40Z
9,521,382
23
2012-03-01T17:55:37Z
[ "python", "sql", "variables", "select", "pyodbc" ]
I'm trying to iterate through all the rows in a table named Throughput, but for a specific DeviceName (which I have stored in data['DeviceName']. I've tried the following, but it doesn't work: ``` for row in cursor.execute("select * from Throughput where DeviceName=%s"), %(data['DeviceName']): ``` EDIT: also tried th...
You are also able to [parameterize](http://code.google.com/p/pyodbc/wiki/GettingStarted#Parameters) statements: ``` ... cursor.execute("select * from Throughput where DeviceName = ?", data['DeviceName']) ... ``` This a better approach for the following reasons: * Protection against SQL injection (you should always v...
Restricting values for curve_fit (scipy.optimize)
9,518,290
6
2012-03-01T14:48:04Z
9,518,691
7
2012-03-01T15:13:58Z
[ "python", "scipy", "curve-fitting" ]
I'm trying to fit a logistic growth curve to my data using curve\_fit using the following function as the input. ``` def logistic(x, y0, k, d, a, b): if b > 0 and a > 0: y = (k * pow(1 + np.exp(d - (a * b * x) ), (-1/b) )) + y0 elif b >= -1 or b < 0 or a < 0: y = (k * pow(1 - np.exp(d - (a * b ...
When the parameters fall out of the admissible range, return a wildly huge number (far from the data to be fitted). This will (hopefully) penalize this choice of parameters so much that `curve_fit` will settle on some other admissible set of parameters as optimal: ``` def logistic(x, y0, k, d, a, b): if b > 0 and ...
Big file compression with python
9,518,705
8
2012-03-01T15:14:36Z
9,519,016
12
2012-03-01T15:33:31Z
[ "python", "data-compression" ]
I want to compress big text files with python (I am talking about >20Gb files). I am not any how an expert so I tried to gather the info I found and the following seems to work : ``` import bz2 with open('bigInputfile.txt', 'rb') as input: with bz2.BZ2File('bigInputfile.txt.bz2', 'wb', compresslevel = 9) as outpu...
Your script seems correct, but can be abbreviated: ``` from shutil import copyfileobj with open('bigInputfile.txt', 'rb') as input: with bz2.BZ2File('bigInputfile.txt.bz2', 'wb', compresslevel=9) as output: copyfileobj(input, output) ```
How to split a string on whitespace and retain offsets and lengths of words
9,518,806
10
2012-03-01T15:20:30Z
9,518,903
7
2012-03-01T15:26:43Z
[ "python", "string" ]
I need to split a string into words, but also get the starting and ending offset of the words. So, for example, if the input string is: ``` input_string = "ONE ONE ONE \t TWO TWO ONE TWO TWO THREE" ``` I want to get: ``` [('ONE', 0, 2), ('ONE', 5, 7), ('ONE', 9, 11), ('TWO', 17, 19), ('TWO', 21, 23), ('ONE', 25,...
``` def split_span(s): for match in re.finditer(r"\S+", s): span = match.span() yield match.group(0), span[0], span[1] - 1 ```
How to split a string on whitespace and retain offsets and lengths of words
9,518,806
10
2012-03-01T15:20:30Z
9,518,913
18
2012-03-01T15:27:25Z
[ "python", "string" ]
I need to split a string into words, but also get the starting and ending offset of the words. So, for example, if the input string is: ``` input_string = "ONE ONE ONE \t TWO TWO ONE TWO TWO THREE" ``` I want to get: ``` [('ONE', 0, 2), ('ONE', 5, 7), ('ONE', 9, 11), ('TWO', 17, 19), ('TWO', 21, 23), ('ONE', 25,...
The following will do it: ``` import re s = 'ONE ONE ONE \t TWO TWO ONE TWO TWO THREE' ret = [(m.group(0), m.start(), m.end() - 1) for m in re.finditer(r'\S+', s)] print(ret) ``` This produces: ``` [('ONE', 0, 2), ('ONE', 5, 7), ('ONE', 9, 11), ('TWO', 17, 19), ('TWO', 21, 23), ('ONE', 25, 27), ('TWO', 29, 31), ...
Select distinct in Django
9,518,947
2
2012-03-01T15:29:11Z
9,519,113
9
2012-03-01T15:39:17Z
[ "python", "django", "python-2.6" ]
What am I doing wrong here? ``` [app.system_name for app in App.objects.all().distinct('system_name')] ``` Gives me: ``` [u'blog', u'files', u'calendar', u'tasks', u'statuses', u'wiki', u'wiki', u'blog ', u'files', u'blog', u'ideas', u'calendar', u'wiki', u'wiki', u'statuses', u'ta sks', u'survey', u'blog'] ``` As ...
1. Specifying fields in `distinct` is only supported in Django 1.4+. If you're running 1.3, it's just ignoring it. 2. If you *are* running Django 1.4, you must add an `order_by` clause that includes and starts with all the fields in `distinct`. 3. Even then, specifying fields with `distinct` is only support on PostgreS...
Porting Python to an embedded system
9,519,346
23
2012-03-01T15:52:05Z
9,519,408
21
2012-03-01T15:55:20Z
[ "python", "embedded" ]
I am working with an ARM Cortex M3 on which I need to port Python (without operating system). What would be my best approach? I just need the core Python and basic I/O.
Golly, that's kind of a tall order. There are so many services of a kernel that Python depends upon, and that you'd have to provide yourself. I'd think you'd be far better off looking for a lightweight OS -- maybe [Minix 3](http://www.minix3.org/)? -- to put on your embedded processor. Failing that, I'd be horribly te...
Porting Python to an embedded system
9,519,346
23
2012-03-01T15:52:05Z
9,542,736
13
2012-03-03T02:03:05Z
[ "python", "embedded" ]
I am working with an ARM Cortex M3 on which I need to port Python (without operating system). What would be my best approach? I just need the core Python and basic I/O.
You should definitely look at eLua: <http://www.eluaproject.net> "Embedded power, driven by Lua Quickly prototype and develop embedded software applications with the power of Lua and run them on a wide range of microcontroller architectures"
Porting Python to an embedded system
9,519,346
23
2012-03-01T15:52:05Z
9,566,846
9
2012-03-05T12:42:52Z
[ "python", "embedded" ]
I am working with an ARM Cortex M3 on which I need to port Python (without operating system). What would be my best approach? I just need the core Python and basic I/O.
There are a few projects that have attempted to port Python to the situation you mention, take a look at [python-on-a-chip](http://code.google.com/p/python-on-a-chip/), [PyMite](http://wiki.python.org/moin/PyMite) or tinypy. These are aimed at lower power microcontrollers without an OS and tend to focus on slightly old...
Editing programs “while they are running”? How?
9,519,384
14
2012-03-01T15:53:59Z
9,523,698
9
2012-03-01T20:39:20Z
[ "java", "python", "clojure", "lisp", "scheme" ]
This question is a corollary to: [Editing programs “while they are running”? Why?](http://stackoverflow.com/questions/5074781/editing-programs-while-they-are-running-why "foo") I'm only recently being exposed to the world of Clojure and am fascinated by [a](http://overtone.github.com/) [few](http://www.youtube.com...
Some language implementations have that for a long time, especially many Lisp variants and Smalltalk. Lisp has identifiers as a data structure, called *symbols*. These symbols can be reassigned and they are looked up at runtime. This principle is called *late binding*. Symbols name functions and variables. Additional...
how do i redirect the output of nosetests to a textfile?
9,519,717
4
2012-03-01T16:11:33Z
9,519,878
8
2012-03-01T16:19:34Z
[ "python", "nosetests" ]
I've tried "nosetests p1.py > text.txt" and it is not working. What is the proper way to pipe this console output?
Try: ``` nosetests -s p1.py > text.txt 2>&1 ``` Last --obvious--tip: If you are not in the test file directory, add before the .py file.
Python Regex to find a string in double quotes within a string
9,519,734
9
2012-03-01T16:12:29Z
9,519,934
26
2012-03-01T16:23:07Z
[ "python", "regex" ]
A code in python using regex that can perform something like this ``` Input: Regex should return "String 1" or "String 2" or "String3" Output: String 1,String2,String3 ``` Thanks
Here's all you need to do: ``` def doit(text): import re matches=re.findall(r'\"(.+?)\"',text) # matches is now ['String 1', 'String 2', 'String3'] return ",".join(matches) doit('Regex should return "String 1" or "String 2" or "String3" ') # result: 'String 1,String 2,String3' ``` As pointed out by Li-...
paramiko.SSHException: Error reading SSH protocol banner
9,520,609
7
2012-03-01T17:03:38Z
9,604,193
7
2012-03-07T15:23:08Z
[ "python", "sftp", "paramiko" ]
I am using Paramiko and trying to connect to my SFTP server. Here is the code I wrote: ``` class SFTPUploader: def __init__(self, host, username, password, port): transport = paramiko.Transport((host, port)) print transport transport.connect(username = username, password = password) ...
That error is generated when paramiko doesn't receive a protocol banner, or the server sends something invalid. If the server is otherwise working correctly, this may be due to some network restrictions. You can use `-vvv` as an option to the openssh client to get more information about how it's connecting, and you ca...
What is Python's equivalent of "perl -V"
9,520,841
13
2012-03-01T17:19:21Z
9,521,657
15
2012-03-01T18:17:22Z
[ "python", "perl", "configuration", "version", "system" ]
The output produced by running `perl -V` is packed with useful information (see example below). Is there anything like it for Python? --- Example output: ``` % perl -V Summary of my perl5 (revision 5 version 10 subversion 1) configuration: Platform: osname=linux, osvers=2.6.32-5-amd64, archname=x86_64-linux-g...
``` python -c 'import sysconfig, pprint; pprint.pprint(sysconfig.get_config_vars())' ```
mkvirtualenv --no-site-packages command getting "command not found" error
9,520,887
14
2012-03-01T17:22:37Z
9,520,937
25
2012-03-01T17:25:33Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I have virtualenv and virtualenvwrapper installed, but when trying to setup an application, I enter `mkvirtualenv --no-site-packages` I get the following error: `-bash: mkvirtualenv: command not found` I am not sure how to troubleshoot this. As a beginner, I'd be grateful for any help.
You need to enable `virtualenvwrapper` as described in [its docs](http://www.doughellmann.com/docs/virtualenvwrapper/install.html#shell-startup-file). > Shell Startup File > > Add three lines to your shell startup file (`.bashrc`, `.profile`, etc.) > to set the location where the virtual environments should live, the ...
Running Python in background on OS X
9,522,324
10
2012-03-01T19:05:21Z
9,523,030
24
2012-03-01T19:55:18Z
[ "python", "osx", "daemon" ]
Is there any way to keep my Python script (with an endless 'while' loop) running in the background on OS X? Also, for the same purpose, is there any way to have "autorun" python script on a USB drive?
If you want to have the script running as a daemon process which starts automatically, you can use [launchctl](https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/launchctl.1.html) and a plist file. For example, Bob has a simple python script which writes the word 'foo' to a file ever...
Get built-in function from the function name
9,522,627
3
2012-03-01T19:26:57Z
9,522,660
9
2012-03-01T19:28:52Z
[ "python" ]
How can I get the int(), float(), dict(), etc. callables from their names? For example, I'm trying to save Python values to xml and storing the variable type as a string. Is there a way to get the callable from the string when converting from string back to the Python type? Normally I would do something like getattr(m...
> Normally I would do something like `getattr(myobj, 'str')`, but there is no module to use as the first argument for these built-in conversion functions. Wrong, there is: ``` import __builtin__ my_str = getattr(__builtin__, "str") ``` (In Python 3.x: `import builtins`)
Adding attributes to instance methods in Python
9,523,370
8
2012-03-01T20:17:59Z
9,523,891
8
2012-03-01T20:52:56Z
[ "python", "methods", "instance", "instance-methods" ]
I would like to add an attribute to an instance method in one of my classes. I tried the answer given in [this question](http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function), but this answer only works for functions -- as far as I can tell. As an example, I wou...
In Python 3 your code would work, but in Python 2 there is some wrapping that takes place when methods are looked up. # Class vs Instance * class level: storing `counter` with the function (either directly, or by using a mutable default) effectively makes it a class level attribute as there is only ever one of the fu...
Count indexes using "for" in Python
9,524,209
15
2012-03-01T21:13:45Z
9,524,228
34
2012-03-01T21:14:56Z
[ "python", "for-loop", "count", "indexing" ]
I need to do in Python the same as: ``` for (i = 0; i < 5; i++) {cout << i;} ``` but I don't know how to use FOR in Python to get the index of the elements in a list.
If you have some given list, and want to iterate over its items *and* indices, you can use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate): ``` for index, item in enumerate(my_list): print index, item ``` If you only need the indices, you can use [`range()`](http://docs.python.org/library...
Count indexes using "for" in Python
9,524,209
15
2012-03-01T21:13:45Z
9,524,250
8
2012-03-01T21:16:34Z
[ "python", "for-loop", "count", "indexing" ]
I need to do in Python the same as: ``` for (i = 0; i < 5; i++) {cout << i;} ``` but I don't know how to use FOR in Python to get the index of the elements in a list.
use [enumerate](http://docs.python.org/library/functions.html#enumerate): ``` >>> l = ['a', 'b', 'c', 'd'] >>> for index, val in enumerate(l): ... print "%d: %s" % (index, val) ... 0: a 1: b 2: c 3: d ```
Count indexes using "for" in Python
9,524,209
15
2012-03-01T21:13:45Z
9,524,479
9
2012-03-01T21:34:37Z
[ "python", "for-loop", "count", "indexing" ]
I need to do in Python the same as: ``` for (i = 0; i < 5; i++) {cout << i;} ``` but I don't know how to use FOR in Python to get the index of the elements in a list.
Just use ``` for i in range(0, 5): print i ``` to iterate through your data set and print each value. For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. <http://docs.python.org/library/functions.html#xrange>
Rectangular bounding box around blobs in a monochrome image using python
9,525,313
6
2012-03-01T22:38:17Z
9,527,529
12
2012-03-02T03:21:26Z
[ "python", "image-processing", "numpy", "scipy", "python-imaging-library" ]
I have a few monochrome images (black and white not greyscale) with a few weirdly shaped objects. I'm trying to extract each object using python27, PIL, scipy & numpy and the following method: 1. Fit a bounding box around each joined-up object 2. "Extract" each object as an array - for each object / bounding box I've...
This uses [Joe Kington's `find_paws` function](http://stackoverflow.com/questions/4087919/how-can-i-improve-my-paw-detection). ``` import numpy as np import scipy.ndimage as ndimage import scipy.spatial as spatial import scipy.misc as misc import matplotlib.pyplot as plt import matplotlib.patches as patches class BBo...
Python: Converting from Tuple to String?
9,525,399
8
2012-03-01T22:44:38Z
9,525,517
21
2012-03-01T22:55:27Z
[ "python", "string", "tuples" ]
let's say that I have string: ``` s = "Tuple: " ``` and Tuple (stored in a variable named tup): ``` (2, a, 5) ``` I'm trying to get my string to contain the value "Tuple: (2, a, 5)". I noticed that you can't just concatenate them. Does anyone know the most straightforward way to do this? Thanks.
This also works: ``` >>> s = "Tuple: " + str(tup) >>> s "Tuple: (2, 'a', 5)" ```
How to write If statements for all 2^N boolean conditions (python)
9,525,575
4
2012-03-01T23:02:07Z
9,525,644
9
2012-03-01T23:07:30Z
[ "python", "algorithm" ]
I have a function which needs to execute a query based on the query instances inputted.. but as the conditions are increasing it is becoming tedious for me to list all of them. For example: suppose i have two conditions initially: ``` if (cond_1 == True and cond_2 == False): do something elif cond_1 == True and c...
Do you need to always write all all 2^n possibilities? And are all things you have to do different (so also 2^n actions?) However I can give some hints: Don't use '== True' or '== False' What you wrote equals: ``` if cond_1 and not cond_2: do something elif cond_1 and cond_2: do something else elif not c...
How to write If statements for all 2^N boolean conditions (python)
9,525,575
4
2012-03-01T23:02:07Z
9,525,659
7
2012-03-01T23:09:33Z
[ "python", "algorithm" ]
I have a function which needs to execute a query based on the query instances inputted.. but as the conditions are increasing it is becoming tedious for me to list all of them. For example: suppose i have two conditions initially: ``` if (cond_1 == True and cond_2 == False): do something elif cond_1 == True and c...
You should [never test a boolean variable with `== True` or `== False`](http://programmers.stackexchange.com/questions/12807/make-a-big-deal-out-of-true). Instead, just using the boolean values is enough. If you want to cover virtually every combination of truth values, you may also want to nest, like this: ``` if con...
django-tables2 specify different properties for different rows
9,525,670
3
2012-03-01T23:10:52Z
9,690,086
8
2012-03-13T18:42:18Z
[ "python", "css", "checkbox", "django-tables2" ]
I would like to create a table with *django-tables2* such that different rows have different properties. By default I get either ``` <tr class="odd"> ``` or ``` <tr class="even"> ``` How can I specify my own class for some of the rows? Similarly, if I have a CheckBoxColumn and I specify some data for this column,...
Well, let me post my own solution. I have copied the standard template *table.html* and edited it. I only changed one line: ``` <tbody> {% for row in table.page.object_list|default:table.rows %} {# support pagination #} {% block table.tbody.row %} <tr class="{{ row.tr_class }}"> <!-- CLASS FOR EACH ROW -...
Python datetime formatting without zero-padding
9,525,944
25
2012-03-01T23:41:09Z
9,526,003
25
2012-03-01T23:46:19Z
[ "python", "datetime", "formatting", "zero-pad" ]
Is there a format for printing Python datetimes that won't use zero-padding on dates and times? Format I'm using now: ``` mydatetime.strftime('%m/%d/%Y %I:%M%p') ``` **Result:** 02/29/2012 05:03PM **Desired:** 2/29/2012 5:03PM What format would represent the month as '2' instead of '02', and time as '5:03PM' inst...
The formatting options available with `datetime.strftime()` will all zero-pad. You could of course roll you own formatting function, but the easiest solution in this case might be to post-process the result of `datetime.strftime()`: ``` s = mydatetime.strftime('%m/%d/%Y %I:%M%p').lstrip("0").replace(" 0", " ") ``` (T...
Python datetime formatting without zero-padding
9,525,944
25
2012-03-01T23:41:09Z
9,526,118
51
2012-03-02T00:00:10Z
[ "python", "datetime", "formatting", "zero-pad" ]
Is there a format for printing Python datetimes that won't use zero-padding on dates and times? Format I'm using now: ``` mydatetime.strftime('%m/%d/%Y %I:%M%p') ``` **Result:** 02/29/2012 05:03PM **Desired:** 2/29/2012 5:03PM What format would represent the month as '2' instead of '02', and time as '5:03PM' inst...
The new string formatting system provides an alternative to `strftime`. It's quite readable -- indeed, it might be preferable to `strftime` on that account. Not to mention the fact that it doesn't zero-pad: ``` >>> '{d.month}/{d.day}/{d.year}'.format(d=datetime.datetime.now()) '3/1/2012' ``` Since you probably want z...
Python datetime formatting without zero-padding
9,525,944
25
2012-03-01T23:41:09Z
29,980,406
25
2015-05-01T01:32:42Z
[ "python", "datetime", "formatting", "zero-pad" ]
Is there a format for printing Python datetimes that won't use zero-padding on dates and times? Format I'm using now: ``` mydatetime.strftime('%m/%d/%Y %I:%M%p') ``` **Result:** 02/29/2012 05:03PM **Desired:** 2/29/2012 5:03PM What format would represent the month as '2' instead of '02', and time as '5:03PM' inst...
The other alternate to avoid the "all or none" leading zero aspect above is to place a minus in front of the field type: ``` mydatetime.strftime('%-m/%d/%Y %-I:%M%p') ``` Then this: '4/10/2015 03:00AM' Becomes: '4/10/2015 3:00AM' You can optionally place a minus in front of the day if desired.
Get consecutive capitalized words using regex
9,525,993
7
2012-03-01T23:45:18Z
9,526,027
17
2012-03-01T23:49:16Z
[ "python", "regex" ]
I am having trouble with my regex for capturing consecutive capitalized words. Here is what I want the regex to capture: ``` "said Polly Pocket and the toys" -> Polly Pocket ``` Here is the regex I am using: ``` re.findall('said ([A-Z][\w-]*(\s+[A-Z][\w-]*)+)', article) ``` It returns the following: ``` [('Polly P...
Use a positive look-ahead: ``` ([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+) ``` Assert that the current word, to be accepted, needs to be followed by another word with a capital letter in it. Broken down: ``` ( # begin capture [A-Z] # one uppercase letter \ First Word [a-z]+ # ...
Best practice for setting the default value of a parameter that's supposed to be a list in Python?
9,526,465
22
2012-03-02T00:42:22Z
9,526,480
32
2012-03-02T00:43:46Z
[ "python", "default-value", "pylint" ]
I have a Python function that takes a list as a parameter. If I set the parameter's default value to an empty list like this: ``` def func(items=[]): print items ``` Pylint would tell me "Dangerous default value [] as argument". So I was wondering what is the best practice here?
Use `None` as a default value: ``` def func(items=None): if items is None: items = [] print items ``` The problem with a mutable default argument is that it will be shared between all invocations of the function -- see the "important warning" in the [relevant section of the Python tutorial](http://doc...
How to retrieve original @classmethod, @staticmethod or @property
9,527,057
2
2012-03-02T02:11:09Z
9,527,450
8
2012-03-02T03:10:03Z
[ "python" ]
I understand that @decorator.decorator doesn't allow to decorate above @staticmethod, @classmethod (and perhaps also @property). I understand the usage: ``` class A(object): @classmethod @mydecorator def my_method(cls): pass ``` But, in a debugging module, I still want to try to do it dynamically. So I wa...
Considering: ``` >>> def original():pass >>> classmethod(original).__func__ == original True >>> staticmethod(original).__func__ == original True >>> property(original).fget == original True ``` Your function should be something like: ``` import decorator def mydecorator(f, *d_args, **d_kwargs): if (isinstance...
how to loop from 0000 to 9999 and convert the number to the relative string?
9,527,990
3
2012-03-02T04:29:58Z
9,528,020
11
2012-03-02T04:32:53Z
[ "python", "string", "numbers" ]
i want to get some string, range from 0000 to 9999, that's to say, i want to print the following string: ``` 0000 0001 0002 0003 0004 0005 0006 .... 9999 ``` i tried to use `print "\n".join([str(num) for num in range(0, 9999)])`, but failed, i get the following number: ``` 0 1 2 3 4 5 6 ... 9999 ``` i want python t...
One way to get what you want is to use string formatting: ``` >>> for i in xrange(10): ... '{0:04}'.format(i) ... '0000' '0001' '0002' '0003' '0004' '0005' '0006' '0007' '0008' '0009' ``` So to do what you want, do this: ``` print "\n".join(['{0:04}'.format(num) for num in xrange(0, 10000)]) ```
Value for epsilon in Python
9,528,421
27
2012-03-02T05:26:40Z
9,528,486
62
2012-03-02T05:32:47Z
[ "python", "comparison", "floating-point", "epsilon" ]
Is there a standard value for (or method for obtaining) epsilon in Python? I need to compare floating point values and want to compare against the smallest possible difference. In C++ there's a function provided **`numeric_limits::epsilon( )`** which gives the epsilon value for any given data type. Is there an equival...
The information is available in [`sys.float_info`](http://docs.python.org/py3k/library/sys.html#sys.float_info), which corresponds to float.h in C99. ``` >>> import sys >>> sys.float_info.epsilon 2.220446049250313e-16 ```
Value for epsilon in Python
9,528,421
27
2012-03-02T05:26:40Z
9,528,651
16
2012-03-02T05:51:21Z
[ "python", "comparison", "floating-point", "epsilon" ]
Is there a standard value for (or method for obtaining) epsilon in Python? I need to compare floating point values and want to compare against the smallest possible difference. In C++ there's a function provided **`numeric_limits::epsilon( )`** which gives the epsilon value for any given data type. Is there an equival...
As [strcat posted](http://stackoverflow.com/a/9528486/177018), there is `sys.float_info.epsilon`. But don't forget the pitfalls of using it as an absolute error margin for floating point comparisons. E.g. for large numbers, rounding error could exceed epsilon. If you think you need a refresher, the standard reference...
Parsing hostname and port from string or url
9,530,950
7
2012-03-02T09:37:29Z
9,531,210
7
2012-03-02T09:56:02Z
[ "python", "regex", "parsing" ]
I can be given a string in any of these formats: * url: e.g <http://www.acme.com:456> * string: e.g www.acme.com:456, www.acme.com 456, or www.acme.com I would like to extract the host and if present a port. If the port value is not present I would like it to default to 80. I have tried [urlparse](http://docs.python...
The reason it fails for: ``` www.acme.com 456 ``` is because it is not a valid URI. Why don't you just: 1. Replace the space with a `:` 2. Parse the resulting string by using the standard `urlparse` method Try and make use of default functionality as much as possible, especially when it comes to things like parsing...
Parsing hostname and port from string or url
9,530,950
7
2012-03-02T09:37:29Z
17,769,986
16
2013-07-21T07:17:21Z
[ "python", "regex", "parsing" ]
I can be given a string in any of these formats: * url: e.g <http://www.acme.com:456> * string: e.g www.acme.com:456, www.acme.com 456, or www.acme.com I would like to extract the host and if present a port. If the port value is not present I would like it to default to 80. I have tried [urlparse](http://docs.python...
You can use urlparse to get hostname from URL string: ``` from urlparse import urlparse print urlparse("http://www.website.com/abc/xyz.html").hostname # prints www.website.com ```
How to handle a HTTP GET request to a file in Tornado?
9,531,092
4
2012-03-02T09:48:29Z
9,637,895
12
2012-03-09T16:51:44Z
[ "python", "http", "web", "chat", "tornado" ]
I'm using Ubuntu and have a directory called "webchat", under this directory there are 4 files: webchat.py, webchat.css, webchat.html, webchat.js. When creating a HTTP server using Tornado, i map the root ("/") to my python code: 'webchat.py' as follow: ``` import os,sys import tornado.ioloop import tornado.web impor...
Tornado has a default static file handler, but it maps url to /static/, will it be ok if you must access your static file at /static/webchat.css ? If you are ok with this, I strongly suggest that you handle static file this way. If you want your static file at root path, have a glance look at web.StaticFileHandler. ...
What is the origin of __author__?
9,531,136
17
2012-03-02T09:51:19Z
9,531,279
15
2012-03-02T10:00:37Z
[ "python", "metadata" ]
Where does the convention of using private metadata variables like `__author__` within a module come from? [This](http://mail.python.org/pipermail/python-dev/2001-March/013328.html) Python mailinglist thread seems to hint at some discussion about it in 2001, but by the sound of it the convention was already out in the...
My guess is, it's from the old times when packaging meta data was not common then. In PEP 8 one is encouraged to use the \_\_version\_\_ top level variable to hold the revision id of the versioning system in use. This dates back to 2001-05-01. PEP 396 is superseding this for module \_\_version\_\_ attributes. For \_\_...
Problems using subprocess.call() in Python 2.7.2 on Windows
9,531,683
9
2012-03-02T10:26:06Z
9,532,379
13
2012-03-02T11:15:00Z
[ "python", "python-2.7" ]
I'm trying the following and its failing with an error. I've tried to run it from Python shell/from a script/ on the windows console by invoking python on console. Nothing seems to work. Always the same error. ``` from subprocess import call >>>pat = "d:\info2.txt" >>> call(["type",pat]) >>>Traceback (most recent ca...
Add `shell=True` to [call](http://docs.python.org/library/subprocess.html#subprocess.call): ``` >>> import subprocess >>> subprocess.call('dir', shell=True) 0 ``` As you see, it gives as value the return code, not the output of `dir`. Also, it waits till the command completes, so doing ``` >>> subprocess.call('date'...
How to use multiple threads
9,532,264
12
2012-03-02T11:06:20Z
9,532,410
7
2012-03-02T11:17:46Z
[ "python", "multithreading" ]
I have this code: ``` import thread def print_out(m1, m2): print m1 print m2 print "\n" for num in range(0, 10): thread.start_new_thread(print_out, ('a', 'b')) ``` I want to create 10 threads, each thread runs the function `print_out`, but I failed. The errors are as follows: ``` Unhandled exceptio...
First of all, you should use the higher level `threading` module and specifically the `Thread` class. The `thread` module is not what you need. As you extend this code, you most likely will also want to wait for the threads to finish. Following is a demonstration of how to use the `join` method to achieve that: ``` i...
Check whether a path is valid in Python without creating a file at the path's target
9,532,499
37
2012-03-02T11:26:38Z
9,532,586
21
2012-03-02T11:33:19Z
[ "python", "filesystems" ]
I have a path (including directory and file name). I need to test if the file-name is a valid, e.g. if the file-system will allow me to create a file with such a name. The file-name *has some unicode characters* in it. It's safe to assume the directory segment of the path is valid and accessible (I was trying to m...
``` if os.path.exists(filePath): #the file is there elif os.access(os.path.dirname(filePath), os.W_OK): #the file does not exists but write privileges are given else: #can not write there ``` Note that `path.exists` can fail for more reasons than just `the file is not there` so you might have to do finer t...
Check whether a path is valid in Python without creating a file at the path's target
9,532,499
37
2012-03-02T11:26:38Z
34,102,855
33
2015-12-05T08:26:56Z
[ "python", "filesystems" ]
I have a path (including directory and file name). I need to test if the file-name is a valid, e.g. if the file-system will allow me to create a file with such a name. The file-name *has some unicode characters* in it. It's safe to assume the directory segment of the path is valid and accessible (I was trying to m...
# tl;dr Call the `is_path_exists_or_creatable()` function defined below. Strictly Python 3. That's just how we roll. # A Tale of Two Questions The question of "How do I test pathname validity and, for valid pathnames, the existence or writability of those paths?" is clearly two separate questions. Both are interest...
Python 3.x tkinter importing error
9,532,547
8
2012-03-02T11:30:36Z
9,532,870
10
2012-03-02T11:55:28Z
[ "python", "user-interface", "python-3.x", "tkinter", "importerror" ]
I'm using Ubuntu 11.10. When importing tkinter I get these following error, though it seems I've installed python-tk somehow. Please help. ``` shishir@dewsworld:~$ python3.2 Python 3.2.2 (default, Sep 5 2011, 22:09:30) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ...
The error message is wrong. Install `python3-tk` instead.
Ignore part of a python tuple
9,532,576
17
2012-03-02T11:32:56Z
9,532,649
27
2012-03-02T11:39:12Z
[ "python", "tuples", "iterable-unpacking" ]
If I have a tuple such as `(1,2,3,4)` and I want to assign 1 and 3 to variables a and b I could obviously say ``` myTuple = (1,2,3) a = my_tuple[0] b = myTuple[2] ``` Or something like ``` (a,_,b,_) = myTuple ``` Is there a way I could unpack the values, but ignore one or more of them of them?
I personally would write: ``` a, _, b = myTuple ``` This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.
Ignore part of a python tuple
9,532,576
17
2012-03-02T11:32:56Z
9,532,729
10
2012-03-02T11:44:11Z
[ "python", "tuples", "iterable-unpacking" ]
If I have a tuple such as `(1,2,3,4)` and I want to assign 1 and 3 to variables a and b I could obviously say ``` myTuple = (1,2,3) a = my_tuple[0] b = myTuple[2] ``` Or something like ``` (a,_,b,_) = myTuple ``` Is there a way I could unpack the values, but ignore one or more of them of them?
Your solution is fine in my opinion. If you really have a problem with assigning \_ then you could define a list of indexes and do: ``` a = (1, 2, 3, 4, 5) idxs = [0, 3, 4] a1, b1, c1 = (a[i] for i in idxs) ```
plot is not defined
9,532,903
7
2012-03-02T11:57:17Z
9,532,976
11
2012-03-02T12:03:20Z
[ "python" ]
I started to use matplotlib library to get a graph. But when I use "plot(x,y)" it returns me that "plot is not defined". To import , I used the following command: `from matplotlib import *` Any Suggestions?
Change that import to ``` from matplotlib.pyplot import * ``` Note that this style of imports (`from X import *`) is generally discouraged. I would recommend using the following instead: ``` import matplotlib.pyplot as plt plt.plot([1,2,3,4]) ```
plot is not defined
9,532,903
7
2012-03-02T11:57:17Z
9,534,079
8
2012-03-02T13:26:40Z
[ "python" ]
I started to use matplotlib library to get a graph. But when I use "plot(x,y)" it returns me that "plot is not defined". To import , I used the following command: `from matplotlib import *` Any Suggestions?
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space: ``` import matplotlib.pyplot matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx") matplotlib.pyplot.show() ```...
Which is the relationship between CPU time measured by Python profiler and, real, user and sys time?
9,533,179
11
2012-03-02T12:20:29Z
9,534,446
11
2012-03-02T13:54:00Z
[ "python", "time", "profiling", "profiler", "cprofile" ]
Using the python built-in profiler with a script runninng in one processor (and no multithreading) ``` time python -m cProfile myscript.py ``` the CPU time reported by the profiler is 345.710 CPU seconds ``` 24184348 function calls (24183732 primitive calls) in 345.710 CPU seconds ``` and the *real*, *user* and *sy...
[This answers](http://stackoverflow.com/a/556411/842837) beautifully details on the meaning of real, user and sys timings. To quote: * 'Real' is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for e...
Which is the relationship between CPU time measured by Python profiler and, real, user and sys time?
9,533,179
11
2012-03-02T12:20:29Z
17,354,083
7
2013-06-27T22:10:53Z
[ "python", "time", "profiling", "profiler", "cprofile" ]
Using the python built-in profiler with a script runninng in one processor (and no multithreading) ``` time python -m cProfile myscript.py ``` the CPU time reported by the profiler is 345.710 CPU seconds ``` 24184348 function calls (24183732 primitive calls) in 345.710 CPU seconds ``` and the *real*, *user* and *sy...
I've been puzzled by the same problem. The answer is that cProfile uses wallclock time. And its output has been historically wrong but is now fixed (the 'CPU' in 'CPU seconds' has been removed). I don't know exactly when, but Python 2.6.6 in Debian 6.0 has the bug while Python 2.7.3 in Debian 7.0 is fine. This is puz...
Python logging to StringIO handler
9,534,245
9
2012-03-02T13:38:50Z
9,534,960
14
2012-03-02T14:31:48Z
[ "python", "unit-testing", "logging", "stringio" ]
I have a python test in which I want to test if the logging works properly. For example I have a function that creates a user and at the end the logging writes to log file the response. ``` logger = logging.getLogger('mylogger') logger.setLevel(logging.DEBUG) handler = logging.handlers.WatchedFileHandler('mylogfile.lo...
Here is an example that works, make sure you set the level of your log, and flush the buffer. ``` class MyTest(unittest.TestCase): def setUp(self): self.stream = StringIO() self.handler = logging.StreamHandler(self.stream) self.log = logging.getLogger('mylogger') self.log.setLevel(l...
numpy.genfromtxt produces array of what looks like tuples, not a 2D array—why?
9,534,408
19
2012-03-02T13:51:08Z
9,534,653
26
2012-03-02T14:10:52Z
[ "python", "import", "numpy", "genfromtxt" ]
I'm running `genfromtxt` like below: ``` date_conv = lambda x: str(x).replace(":", "/") time_conv = lambda x: str(x) a = np.genfromtxt(input.txt, delimiter=',', skip_header=4, usecols=[0, 1] + radii_indices, converters={0: date_conv, 1: time_conv}) ``` Where `input.txt` is from [this gist](https://gist.github....
What is returned is called a **structured ndarray**, see eg here: <http://docs.scipy.org/doc/numpy/user/basics.rec.html>. This is because your data are not homogeneous, i.e. not all elements have the same type: the data contain both strings (the first two columns) and floats. Numpy arrays have to be homogeneous (see [h...
How to document Python function parameters with sphinx-apidoc
9,534,513
11
2012-03-02T13:59:20Z
9,534,564
8
2012-03-02T14:02:51Z
[ "python", "python-sphinx", "documentation-generation", "api-doc" ]
I'm trying to clean up my python code documentation, and decided to use [sphinx-doc](http://sphinx.pocoo.org/domains.html#python-roles) because it looks good. I like how I can reference other classes and methods with tags like: ``` :class:`mymodule.MyClass` About my class. :meth:`mymodule.MyClass.myfunction` And my co...
Typically "function variables" are called parameters ;). It's documented here: <http://sphinx.pocoo.org/domains.html#signatures> And the answer is `:param ________` **EDIT** Disclaimer: I've never used or heard of sphinx... This post is mostly a "what words to search for." Hope it helped.
Intersect 2 lists, store result in a tuple in python
9,534,559
4
2012-03-02T14:02:40Z
9,534,636
8
2012-03-02T14:09:38Z
[ "python", "list", "tuples" ]
I thought what I had was a common problem, but I could not find any help either in Google nor in SO. I have 2 lists that contain objects of class `Marker`. A `Marker` consists of variables `name`, `position` and `type`. I want to intersect the two lists, create tuples of markers of the same type and store them in a ne...
Change the `and` to `for`: ``` g_markerList = [ (marker1,marker2) for marker1 in marker1List for marker2 in marker2List if marker1.type == marker2.type ] ```
get path from a module name
9,534,608
4
2012-03-02T14:06:41Z
9,534,649
9
2012-03-02T14:10:40Z
[ "python", "python-2.7" ]
Im sure there is a simple way to get a modules path from the modulename, right? I.e. I want to retrieve /path/to/module from path.to.module preferably in python 2.7. I dont intend to import the module and I have the modulename as a string.
This is fairly easy after importing a module: ``` import os print os.__file__ ``` prints ``` /usr/lib/python2.7/os.pyc ``` on my machine. To do this *before* importing a module, you can use `imp.find_module()`: ``` imp.find_module("os")[1] ```
Printing Lists as Tabular Data
9,535,954
89
2012-03-02T15:32:55Z
9,536,020
8
2012-03-02T15:37:02Z
[ "python", "table", "printing", "formatting" ]
I am quite new to Python and I am now struggling with formatting my data nicely for printed output. I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so: ``` teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0...
I think [this](http://ginstrom.com/scribbles/2007/09/04/pretty-printing-a-table-in-python/) is what you are looking for. It's a simple module that just computes the maximum required width for the table entries and then just uses [rjust](http://www.tutorialspoint.com/python/string_rjust.htm) and [ljust](http://www.tuto...
Printing Lists as Tabular Data
9,535,954
89
2012-03-02T15:32:55Z
9,536,060
35
2012-03-02T15:39:19Z
[ "python", "table", "printing", "formatting" ]
I am quite new to Python and I am now struggling with formatting my data nicely for printed output. I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so: ``` teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0...
``` >>> import pandas >>> pandas.DataFrame(data, teams_list, teams_list) Man Utd Man City T Hotspur Man Utd 1 2 1 Man City 0 1 0 T Hotspur 2 4 2 ```
Printing Lists as Tabular Data
9,535,954
89
2012-03-02T15:32:55Z
9,536,084
71
2012-03-02T15:40:32Z
[ "python", "table", "printing", "formatting" ]
I am quite new to Python and I am now struggling with formatting my data nicely for printed output. I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so: ``` teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0...
Some ad-hoc code for Python 2.7: ``` row_format ="{:>15}" * (len(teams_list) + 1) print row_format.format("", *teams_list) for team, row in zip(teams_list, data): print row_format.format(team, *row) ``` This relies on [`str.format()`](http://docs.python.org/py3k/library/stdtypes.html#str.format) and the [Format S...
Printing Lists as Tabular Data
9,535,954
89
2012-03-02T15:32:55Z
26,005,077
21
2014-09-23T21:33:16Z
[ "python", "table", "printing", "formatting" ]
I am quite new to Python and I am now struggling with formatting my data nicely for printed output. I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so: ``` teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0...
Python actually makes this quite easy. Something like ``` for i in range(10): print '%-12i%-12i' % (10 ** i, 20 ** i) ``` will have the output ``` 1 1 10 20 100 400 1000 8000 10000 160000 100000 3200000 1000000 640...
Printing Lists as Tabular Data
9,535,954
89
2012-03-02T15:32:55Z
26,937,531
99
2014-11-14T19:34:08Z
[ "python", "table", "printing", "formatting" ]
I am quite new to Python and I am now struggling with formatting my data nicely for printed output. I have one list that is used for two headings, and a matrix that should be the contents of the table. Like so: ``` teams_list = ["Man Utd", "Man City", "T Hotspur"] data = np.array([[1, 2, 1], [0, 1, 0...
There are some light and useful python packages for this purpose: **1. tabulate**: <https://pypi.python.org/pypi/tabulate> ``` >>> from tabulate import tabulate >>> print tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']) Name Age ------ ----- Alice 24 Bob 19 ``` tabulate has many opti...
Python Save to file
9,536,714
12
2012-03-02T16:22:25Z
9,536,741
42
2012-03-02T16:24:14Z
[ "python", "python-2.7" ]
I would like to save a string to a file with a python program named `Failed.py` Here is what I have so far: ``` myFile = open('today','r') ips = {} for line in myFile: parts = line.split(' ') if parts[1] == 'Failure': if parts[0] in ips: ips[pars[0]] += 1 else: ips[pa...
``` file_ = open('Failed.py', 'w') file_.write('whatever') file_.close() ``` Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block: ``` with open('Failed.py', 'w') as file_: file_.write('whatever') ```
Python Save to file
9,536,714
12
2012-03-02T16:22:25Z
9,536,767
10
2012-03-02T16:26:09Z
[ "python", "python-2.7" ]
I would like to save a string to a file with a python program named `Failed.py` Here is what I have so far: ``` myFile = open('today','r') ips = {} for line in myFile: parts = line.split(' ') if parts[1] == 'Failure': if parts[0] in ips: ips[pars[0]] += 1 else: ips[pa...
You need to open the file again using `open()`, but this time passing `'w'` to indicate that you want to write to the file. I would also recommend using `with` to ensure that the file will be closed when you are finished writing to it. ``` with open('Failed.txt', 'w') as f: for ip in [k for k, v in ips.iteritems()...
Django-South DataMigration - App available in forwards() but not backwards()?
9,536,901
6
2012-03-02T16:34:51Z
9,537,718
10
2012-03-02T17:30:22Z
[ "python", "django", "migration", "database-migration", "django-south" ]
I am writing a django south migration that depends on the model in another app, so I have included `--freeze OTHERAPPNAME` when I ran `python manage.py datamigration …` However in the `forwards()` function I can access the other model fine (with `orm['otherappname.MyModelName']`), however in the `backwards()` step (...
The backwards migration actually uses the frozen ORM of the *previous* migration. It's logical when you think about it, but it's admittedly not very intuitive. Moral: freeze the models you'll need in your datamigration in the schemamigration that proceeds it.
Replace NaN's in NumPy array with closest non-NaN value
9,537,543
12
2012-03-02T17:17:14Z
9,537,766
15
2012-03-02T17:33:57Z
[ "python", "arrays", "numpy", null ]
I have a NumPy array `a` like the following: ``` >>> str(a) '[ nan nan nan 1.44955726 1.44628034 1.44409573\n 1.4408188 1.43657094 1.43171624 1.42649744 1.42200684 1.42117704\n 1.42040255 1.41922908 nan nan nan nan\n nan nan]' ``` I wa...
> I want to replace each NaN with the closest non-NaN value... there will be no NaN's in the middle of the numbers The following will do it: ``` ind = np.where(~np.isnan(a))[0] first, last = ind[0], ind[-1] a[:first] = a[first] a[last + 1:] = a[last] ``` This is a straight `numpy` solution requiring no Python loops,...
Replace NaN's in NumPy array with closest non-NaN value
9,537,543
12
2012-03-02T17:17:14Z
9,537,830
18
2012-03-02T17:38:21Z
[ "python", "arrays", "numpy", null ]
I have a NumPy array `a` like the following: ``` >>> str(a) '[ nan nan nan 1.44955726 1.44628034 1.44409573\n 1.4408188 1.43657094 1.43171624 1.42649744 1.42200684 1.42117704\n 1.42040255 1.41922908 nan nan nan nan\n nan nan]' ``` I wa...
As an alternate solution (this will linearly interpolate for arrays `NaN`s in the middle, as well): ``` import numpy as np # Generate data... data = np.random.random(10) data[:2] = np.nan data[-1] = np.nan data[4:6] = np.nan print data # Fill in NaN's... mask = np.isnan(data) data[mask] = np.interp(np.flatnonzero(m...
"TemplateSyntaxError: 'humanize' is not a valid tag library:" in DJango
9,538,588
6
2012-03-02T18:36:03Z
9,538,739
21
2012-03-02T18:49:01Z
[ "python", "django", "django-registration" ]
While setting up the django-registration module I have run into a bit of trouble. Everything works correctly as far as rendering templates. After trying to test-register I am hit with this error. I do have **Django.contrib.humanize** in the settings.py file. Any help is appreciated
As the docs say: > To activate these filters, add 'django.contrib.humanize' to your INSTALLED\_APPS setting. So perhaps you should have "django." not "Django." ? See [Django docs on django.contrib.humanize](https://docs.djangoproject.com/en/dev/ref/contrib/humanize/) Also do you have "{% load humanize %}" in the tem...
Recursive depth of python dictionary
9,538,875
5
2012-03-02T19:00:30Z
9,538,917
9
2012-03-02T19:04:31Z
[ "python", "recursion", "dictionary" ]
G'day, I am trying to find the recursive depth of a function that trawls a dictionary and I'm a bit lost... Currently I have something like: ``` myDict = {'leve1_key1': {'level2_key1': {'level3_key1': {'level4_key_1': {'level5_key1': 'level5_value1'}}}}} ``` And I want to know just how nested the most nested dicti...
Be sure to assign the result of the recursive call to *depth*. Also, as @amit says, consider using *max* so that you can handle dicts with multiple key value pairs (a treelike structure). ``` def dict_depth(d, depth=0): if not isinstance(d, dict) or not d: return depth return max(dict_depth(v, depth+1)...
python increment ipaddress
9,539,006
4
2012-03-02T19:12:42Z
9,539,079
8
2012-03-02T19:18:48Z
[ "python", "networking" ]
I would like to increment the ip address by a fixed value. precisely this is what I am trying to achieve, I have an ip address say, 192.168.0.3 and I want to increment it by 1 which would result in 192.168.0.4 or even by a fixed value, x so that it will increment my ip address by that number. so, I can have a host lik...
You could use `struct` module to unpack the result of `inet_aton()` e.g., ``` import struct, socket # x.x.x.x string -> integer ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0] print(ip2int("192.168.0.4")) # -> 3232235524 ``` In reverse: ``` int2ip = lambda n: socket.inet_ntoa(struct.pack('!I'...
How to dynamically change base class of instances at runtime?
9,539,052
44
2012-03-02T19:16:23Z
9,541,560
19
2012-03-02T22:59:41Z
[ "python", "inheritance", "dynamic" ]
[This article](http://www.linuxjournal.com/node/4540/print) has a snippet showing usage of `__bases__` to dynamically change the inheritance hierarchy of some Python code, by adding a class to an existing classes collection of classes from which it inherits. Ok, that's hard to read, code is probably clearer: ``` class...
Ok, again, this is not something you should normally do, this is for informational purposes only. Where Python looks for a method on an instance object is determined by the `__mro__` attribute of the class which defines that object (the **M** ethod **R** esolution **O** rder attribute). Thus, if we could modify the `_...
How to dynamically change base class of instances at runtime?
9,539,052
44
2012-03-02T19:16:23Z
9,639,512
7
2012-03-09T18:59:27Z
[ "python", "inheritance", "dynamic" ]
[This article](http://www.linuxjournal.com/node/4540/print) has a snippet showing usage of `__bases__` to dynamically change the inheritance hierarchy of some Python code, by adding a class to an existing classes collection of classes from which it inherits. Ok, that's hard to read, code is probably clearer: ``` class...
I've been struggling with this too, and was intrigued by your solution, but Python 3 takes it away from us: ``` AttributeError: attribute '__dict__' of 'type' objects is not writable ``` I actually have a legitimate need for a decorator that replaces the (single) superclass of the decorated class. It would requir...
Python calling shell commands. What type of shell is started?
9,539,331
4
2012-03-02T19:38:26Z
9,539,372
7
2012-03-02T19:41:42Z
[ "python", "shell" ]
I have the following python function that allows me to run shell commands from within a python script: ``` import subprocess def run_shell_command(cmd,cwd=None): retVal = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, cwd=cwd); retVal = retVal.stdout.read().strip('\n'); return(retVal);...
It's `/bin/sh` on POSIX. See the source code `subprocess.py` (quoting Python 2.7 here): ``` def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c...
Run Python/Django Management Command from a UnitTest/WebTest
9,539,441
11
2012-03-02T19:47:34Z
9,539,486
34
2012-03-02T19:51:29Z
[ "python", "django", "unit-testing", "webtest" ]
We have a bunch of commands in our Django site, some that are administrative and some that run on cron jobs that I can't figure out how to test. They pretty much look like this: ``` # Saved in file /app/management/commands/some_command.py # Usage: python manage.py some_command from django.core.management.base import N...
[Django documentation on management commands](https://docs.djangoproject.com/en/dev/ref/django-admin/#call-command) might help, it describes how to call them from python code. Basically you need something like this: ``` from django.core import management management.call_command( ... ) ```
How can I make portable python desktop application?
9,539,566
11
2012-03-02T19:57:17Z
9,539,758
8
2012-03-02T20:14:49Z
[ "python", "desktop-application" ]
The requirement is to make an application portable, meaning no installer. I looked at py2exe and I am afraid I need to run install if I want to run it under Windows. So my question is, can I make a portable python desktop application without any installation (all dependencies and libs are packaged), dragging from USB ...
You can use this method with [py2exe](http://www.py2exe.org): <http://www.py2exe.org/index.cgi/SingleFileExecutable> Basically, you use [NSIS](http://nsis.sourceforge.net/) to package all of the required files and folders into a single executable. When you run it, the required files are expanded to a temporary directo...
Python function with optional arguments
9,539,921
30
2012-03-02T20:30:08Z
9,539,945
39
2012-03-02T20:32:31Z
[ "python", "function", "arguments" ]
I am trying to improve a function in Python. It takes several arguments, some of which could be missing. ``` def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None): #code ``` The arguments d through h are string type, and have different meaning - and it is important that I can pass `a...
Try calling it like: `obj.some_function( '1', 2, '3', g="foo", h="bar" )`. After the required positional arguments, you can specify specific optional arguments by name.
Python function with optional arguments
9,539,921
30
2012-03-02T20:30:08Z
9,539,977
55
2012-03-02T20:35:13Z
[ "python", "function", "arguments" ]
I am trying to improve a function in Python. It takes several arguments, some of which could be missing. ``` def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None): #code ``` The arguments d through h are string type, and have different meaning - and it is important that I can pass `a...
Just use the \*args parameter, which allows you to pass as many arguments as you want after your `a,b,c`. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading. ``` def myfunc(a,b, *args, **kwargs): for ar in args: print ar myfunc(a,b,c,d,e,f) ``` And it will print `c,d,e,f` -...
Rename an environment with virtualenvwrapper
9,540,040
84
2012-03-02T20:39:55Z
12,549,306
144
2012-09-23T02:39:26Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I have an environment called `doors` and I would like to rename it to `django` for the [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/). I've noticed that if I just rename the folder `~/.virtualenvs/doors` to `django`, I can now call `workon django`, but the environment still says `(doors)h...
You can use: ``` cpvirtualenv oldenv newenv rmvirtualenv oldenv ``` So in your case: ``` cpvirtualenv doors django rmvirtualenv doors ```
Which database engine to choose for Django app?
9,540,154
14
2012-03-02T20:49:11Z
9,540,312
20
2012-03-02T21:01:21Z
[ "python", "database", "django", "sqlite3" ]
I'm new to Django and have only been using sqlite3 as a database engine in Django. Now one of the applications I'm working on is getting pretty big, both in terms of models' complexity and requests/second. How do database engines supported by Django compare in terms of performance? Any pitfalls in using any of them? A...
If you are going to use a relational database, the most popular in the Django community seems to be PostgreSQL. It's my personal favorite. But, MongoDB seems to be getting pretty popular in the Python/Django community as well (I have never done a project with it, though). There are a lot of successful projects out ther...
Which database engine to choose for Django app?
9,540,154
14
2012-03-02T20:49:11Z
9,540,695
7
2012-03-02T21:35:33Z
[ "python", "database", "django", "sqlite3" ]
I'm new to Django and have only been using sqlite3 as a database engine in Django. Now one of the applications I'm working on is getting pretty big, both in terms of models' complexity and requests/second. How do database engines supported by Django compare in terms of performance? Any pitfalls in using any of them? A...
MySQL and Postgres are the two most common DB backends used in the Django community and have comparable performance. I would agree that Postgres is more popular in the Django community though I don't have any hard numbers to back that up. I certainly don't mean to pick on MySQL but I would say there are some common pit...
How does web2py query expressions work?
9,540,712
5
2012-03-02T21:37:05Z
9,541,189
7
2012-03-02T22:22:09Z
[ "python", "web2py" ]
I just recently had a chance to take a look at web2py framework and although I have some prior experience with Django and more so with plain Python, I couldn't make sense out of the Query system that web2py employs. Let's take this example from [web2py book](http://www.web2py.com/books/default/chapter/29/6) ``` db = ...
The other answers have it, but just to provide a little more web2py-specific detail: ``` db.mytable.myfield > 'A' ``` `db.mytable.myfield` is an instance of the web2py DAL `Field` class, which inherits from the DAL `Expression` class. The `Expression` class itself overloads a number of Python operators, such as `==`,...
How to copy a python class?
9,541,025
19
2012-03-02T22:06:04Z
9,541,120
17
2012-03-02T22:15:25Z
[ "python" ]
`deepcopy` from `copy` not copies class: ``` >>> class A(object): >>> ARG = 1 >>> B = deepcopy(A) >>> A().ARG >>> 1 >>> B().ARG >>> 1 >>> A.ARG = 2 >>> B().ARG >>> 2 ``` Is it only way? ``` B(A): pass ```
The right way to "copy" a class, is, as you surmise, inheritance: ``` class B(A): pass ```
How to copy a python class?
9,541,025
19
2012-03-02T22:06:04Z
13,379,957
21
2012-11-14T13:42:09Z
[ "python" ]
`deepcopy` from `copy` not copies class: ``` >>> class A(object): >>> ARG = 1 >>> B = deepcopy(A) >>> A().ARG >>> 1 >>> B().ARG >>> 1 >>> A.ARG = 2 >>> B().ARG >>> 2 ``` Is it only way? ``` B(A): pass ```
In general, inheritance is the right way to go, as the other posters have already pointed out. However, if you really want to recreate the same type with a different name and without inheritance then you can do it like this: ``` class B(object): x = 3 CopyOfB = type('CopyOfB', B.__bases__, dict(B.__dict__)) b =...
How to use urllib2.urlopen to make POST request without data argument
9,541,058
10
2012-03-02T22:10:23Z
9,542,235
28
2012-03-03T00:28:06Z
[ "python", "facebook-graph-api", "urllib2", "urlopen" ]
I am trying to use urllib2.urlopen to perform GET and POST requests via the Facebook Graph API. I noticed from here: [Facebook Graph API and Django](http://stackoverflow.com/questions/2690723/facebook-graph-api-and-django) that I can perform GET request fairly easily. And from here: [how to send a post request using d...
It sounds like you want to send an empty POST request, even though urllib2.urlopen() only sends a post when you specify the data parameter. It seems like it actually sends an empty POST if you set data="", and GET request only when data=None: ``` urllib2.urlopen("http://127.0.0.1:8000", data="") "POST / HTTP/1.1" 501...
Printing a variable in an embedded Python interpreter
9,541,353
4
2012-03-02T22:37:17Z
9,541,411
7
2012-03-02T22:43:18Z
[ "python", "c", "interpreter", "python-c-api", "python-embedding" ]
I have written a small C program that embeds Python. I'm setting it up correctly using Py\_Initialize() and Py\_Finalize(), and am able to run scripts either using PyRun\_SimpleString or PyRun\_SimpleFile. However, I don't know how mimic the behavior of Python's own interpreter when printing variables. Specifically: ...
To run the interpreters interactive loop, you should use the function [`PyRun_InteractiveLoop()`](http://docs.python.org/c-api/veryhigh.html#PyRun_InteractiveLoop). Otherwise, your code will behave as if it were written in a Python script file, not entered interactively. **Edit**: Here's the full code of a simple inte...
name 'self' is not defined when doing an unittest?
9,541,397
4
2012-03-02T22:41:42Z
9,541,912
7
2012-03-02T23:41:28Z
[ "python", "unit-testing" ]
**Edit** So I did try again, with a new file called `test2.py` and it works. I packaged `repoman` , and `test.py` is in the `src` folder. I modified `test.py` after I created and installed my `repoman egg`. I think that's the problem. But thanks for the help. Do you guys think that's the exact reason? --- ``` import...
I'm not sure where the problem is coming from -- whether it's a copying error or the wrong test.py is being executed [update: or some mixed tabs-and-spaces issue, I can never figure out when those get flagged and when they don't] -- but the root cause is almost certainly an indentation error. Note that the error messa...
urllib2 - post request
9,541,677
12
2012-03-02T23:11:40Z
9,551,497
14
2012-03-04T01:25:40Z
[ "python", "urllib2", "http-request" ]
I try to perform a simple POST-request with urllib2. However the servers response indicates that it receives a simple GET. I checked the type of the outgoing request, but it is set to POST. To check whether the server behaves like I expect it to, I tried to perform a GET request with the (former POST-) data concaten...
## Things you need to check: * Are you sure you are posting to the right URL? * Are you sure you can retrieve results without being logged in? * Show us some example output for different post values. You can find correct post URL using Firefox's [Firebug](http://getfirebug.com/) or Google Chromes [DevTools](https://c...
Attach a txt file in Python smtplib
9,541,837
21
2012-03-02T23:30:10Z
9,541,945
29
2012-03-02T23:44:56Z
[ "python", "email", "smtp" ]
I am sending a plain text email as follows: ``` import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_message(): msg = MIMEMultipart('alternative') s = smtplib.SMTP('smtp.sendgrid.net', 587) s.login(USERNAME, PASSWORD) toEmail, fromEmail = to@emai...
The same way, using `msg.attach`: ``` from email.mime.text import MIMEText filename = "text.txt" f = file(filename) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) ```
Networkx graph clustering
9,542,035
8
2012-03-02T23:56:56Z
11,811,071
7
2012-08-04T18:31:43Z
[ "python", "cluster-analysis", "graphviz", "data-visualization", "networkx" ]
in Networkx, how can I cluster nodes based on nodes color? E.g., I have 100 nodes, some of them are close to black, while others are close to white. In the graph layout, I want nodes with similar color stay close to each other, and nodes with very different color stay away from each other. How can I do that? Basically,...
Ok, lets build us adjacency matrix W for that graph following the simple procedure: if both of adjacent vertexes i-th and j-th are of the same color then weight of the edge between them W\_{i,j} is big number (which you will tune in your experiments later) and else it is some small number which you will figure out anal...
izip_longest with looping instead of fillvalue
9,542,358
5
2012-03-03T00:48:57Z
9,542,376
11
2012-03-03T00:53:37Z
[ "python" ]
Not sure how to look around for this, but from `itertools` the function [izip\_longest](http://docs.python.org/library/itertools.html#itertools.izip_longest) does this: `izip_longest('ABCD', 'xy', fillvalue='-')` --> `Ax By C- D-` I was hoping an iterable library would have something to do this: `izip_longest_better...
Something like this? ``` >>> import itertools >>> >>> a = 'ABCDE' >>> b = 'xy' >>> >>> list(itertools.izip_longest(a, b, fillvalue='-')) [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-'), ('E', '-')] >>> list(itertools.izip(a, itertools.cycle(b))) [('A', 'x'), ('B', 'y'), ('C', 'x'), ('D', 'y'), ('E', 'x')] ``` etc. ...
Shell piping with subprocess in Python
9,542,389
9
2012-03-03T00:57:00Z
9,542,573
8
2012-03-03T01:31:17Z
[ "python", "shell", "subprocess", "pipe" ]
I read every thread I found on StackOverflow on invoking shell commands from Python using `subprocess`, but I couldn't find an answer that applies to my situation below: I would like to do the following from Python: 1. Run shell command `command_1`. Collect the output in variable `result_1` 2. **Shell pipe** `result_...
You can do: ``` pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE) pipe.stdin.write(result_1) pipe.communicate() ``` instead of the line with the pipe.
Get path from open file in Python
9,542,435
28
2012-03-03T01:05:41Z
9,542,458
41
2012-03-03T01:09:38Z
[ "python" ]
If I have an opened file, is there an `os` call to get the complete path as a string? ``` f = open('/Users/Desktop/febROSTER2012.xls') ``` From `f`, how would I get `"/Users/Desktop/febROSTER2012.xls"` ?
The key here is the `name` attribute of the `f` object representing the opened file. You get it like that: ``` >>> f = open('/Users/Desktop/febROSTER2012.xls') >>> f.name '/Users/Desktop/febROSTER2012.xls' ``` Does it help?
How to change the 'tag' when logging to syslog from 'Unknown'?
9,542,465
12
2012-03-03T01:11:00Z
11,250,792
11
2012-06-28T18:30:27Z
[ "python", "django", "osx-lion" ]
I'm logging to syslog fine but can't work out how to specify the 'tag'. The logging currently posts this: ``` Mar 3 11:45:34 TheMacMini Unknown: INFO FooBar ``` but I want that 'Unknown' to be set to something. eg: ``` Mar 3 11:45:34 TheMacMini Foopybar: INFO FooBar ``` If I use `logger` from the command line it ...
# Simple Way of Tagging Log Messages Do this: `logging.info("TagName: FooBar")` and you message will be tagged! You just need to start all your messages with "TagName: ". And this is of course not very elegant. # Better Solution Setup your logger: ``` log = logging.getLogger('name') address=('log-server',logging.ha...
Python: Find in list
9,542,738
210
2012-03-03T02:03:34Z
9,542,768
484
2012-03-03T02:10:21Z
[ "python", "find" ]
I have come across this delightful: ``` item = someSortOfSelection() if item in myList: doMySpecialFunction(item) ``` but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string). is it the most 'pythonic' way of finding an item in a list: `if x in l:`?
As for your first question: that code is perfectly fine and should work if `item` equals one of the elements inside `myList`. Maybe you try to find a string that does not *exactly* match one of the items or maybe you are using a float value which suffers from inaccuracy. As for your second question: There's actually s...