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
python format string unused named arguments
17,215,400
14
2013-06-20T13:50:18Z
17,215,621
11
2013-06-20T13:59:16Z
[ "python", "string", "string-formatting" ]
Let's say I have: ``` action = '{bond}, {james} {bond}'.format(bond='bond', james='james') ``` this wil output: ``` 'bond, james bond' ``` Next we have: ``` action = '{bond}, {james} {bond}'.format(bond='bond') ``` this will output: ``` KeyError: 'james' ``` Is there some workaround to prevent this error to ha...
You could use a [template string](http://docs.python.org/2/library/string.html#template-strings) with the `safe_substitute` method. ``` from string import Template tpl = Template('$bond, $james $bond') action = tpl.safe_substitute({'bond': 'bond'}) ```
SQLite insert statement failing silently using Flask
17,215,698
2
2013-06-20T14:02:43Z
17,216,743
8
2013-06-20T14:46:16Z
[ "python", "sqlite", "flask" ]
I'm following along with the Flask/SQLite tutorial on the Flask website: <http://flask.pocoo.org/docs/patterns/sqlite3/> All of my select queries are working fine, but when I try an insert statement nothing happens. I get no error, but I also don't get an inserted row in my database. I'm not sure how to debug this whe...
Are you committing after the INSERT? ``` g.db.execute('insert into photos (is_favorite, galleries_id, filename) values (?, ?, ?)', [is_favorite, galleries_id, filename]) g.db.commit() ```
Convert julian day into date
17,216,169
2
2013-06-20T14:22:06Z
17,216,581
8
2013-06-20T14:39:11Z
[ "python", "bash", "awk", "julian-date" ]
I have files named day00000.nc, day00001.nc, day00002.nc, ...day00364.nc for several years. They represent the 365 or 366 days. I want to rename my files like this day20070101.nc, day20070102.nc , ...day20071231.nc How can I do that ? Thank you
Use the [datetime](http://docs.python.org/2/library/datetime.html) module to get date from day of the year. I am assuming the year is 2007 as in your examples, since your filenames do not seem to have an year value. Feel free to replace the hardcoded `2007` in the code with a variable if required. ``` import datetime ...
Pip install python package into a specific directory other than the default install location
17,216,689
9
2013-06-20T14:43:46Z
23,435,273
13
2014-05-02T19:07:59Z
[ "python", "ubuntu-12.04", "pip", "enthought" ]
The default location where pip installes packages on my Ubuntu system is '/usr/local/lib/pytho2.7/dist-packages/' which I think is the default in general. I am using Enthought python distribution (EPD not canopy) and would like to install a package into EPD as I usually work with the python from the EPD distribution on...
This line works for me: ``` pip install package_name -t path/to/my/directory ``` And should work for everyone, as mentioned in the [documentation](https://pip.pypa.io/en/latest/reference/pip_install.html#cmdoption-t).
How to decompress a .xz file which has multiple folders/files inside, in a single go?
17,217,073
8
2013-06-20T14:59:01Z
17,217,564
18
2013-06-20T15:20:47Z
[ "python", "lzma" ]
I'm trying to uncompress a .xz file which has a few foders and files inside. I don't see a direct way to do this using lzma module. This is what I'm seeing for a decompress method : ``` In [1]: import lzma In [2]: f = lzma.decompress("test.tar.xz") ---------------------------------------------------------------------...
## Python 3.3 ``` import tarfile with tarfile.open('test.tar.xz') as f: f.extractall('.') ``` ## Python 2.7 Need [lzma](https://pypi.python.org/pypi/pyliblzma) in Python 2.7 ``` import contextlib import lzma import tarfile with contextlib.closing(lzma.LZMAFile('test.tar.xz')) as xz: with tarfile.open(file...
What does the == operator actually do on a Python dictionary?
17,217,225
10
2013-06-20T15:05:53Z
17,217,255
10
2013-06-20T15:07:04Z
[ "python", "dictionary" ]
Consider: ``` >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True ``` According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries. What is actually happening here? Is Python recursively checking each element of the dicti...
Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the s...
What does the == operator actually do on a Python dictionary?
17,217,225
10
2013-06-20T15:05:53Z
17,217,332
10
2013-06-20T15:10:32Z
[ "python", "dictionary" ]
Consider: ``` >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True ``` According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries. What is actually happening here? Is Python recursively checking each element of the dicti...
From [docs](http://docs.python.org/2/reference/expressions.html#not-in): > Mappings (dictionaries) compare equal if and only if their sorted > (key, value) lists compare equal .[[5]](http://docs.python.org/2/reference/expressions.html#id24) Outcomes other than equality are > resolved consistently, but are not otherwis...
Print all Unique Values in a Python Dictionary
17,218,139
5
2013-06-20T15:47:43Z
17,218,160
7
2013-06-20T15:48:34Z
[ "python", "dictionary" ]
I'm struggling with a minor problem in Python (my program is in version 3.2.3 right now). I have a dictionary that looks like this (this is just an example, actually taken from another post here): ``` [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"s...
Use a `set()`: ``` from itertools import chain unique_values = set(chain.from_iterable(d.values() for d in dictionaries_list)) for value in unique_values: print(value) print(len(unique_values)) ``` Use `.itervalues()` on Python 2 for a little more efficiency. Because you have a *list* of dictionaries, we need t...
Print all Unique Values in a Python Dictionary
17,218,139
5
2013-06-20T15:47:43Z
17,218,164
16
2013-06-20T15:48:55Z
[ "python", "dictionary" ]
I'm struggling with a minor problem in Python (my program is in version 3.2.3 right now). I have a dictionary that looks like this (this is just an example, actually taken from another post here): ``` [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"s...
Use `set` here as they only contain unique items. ``` >>> lis = [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}] >>> s = set( val for dic in lis for val in dic.values()) >>> s set(['movies', 'news', 'music',...
python 3.3: struct.pack won't accept strings
17,218,357
7
2013-06-20T15:58:20Z
17,218,463
9
2013-06-20T16:04:12Z
[ "python", "python-3.x" ]
I'm trying to use struct.pack to write a padded string to a file but it seems with the 3.x interpreters this doesn't work anymore. An example of how I'm using it: ``` mystring = anotherString+" sometext here" output = struct.pack("30s", mystring); ``` This seems to be okay in earlier versions of python but with 3 it ...
Yes, up until 3.1 `struct.pack()` erroneously would implicitly encode strings to UTF-8 bytes; this was fixed in Python 3.2. See [issue 10783](http://bugs.python.org/issue10783). The conclusion was that the implicit conversion was a Bad Idea, and it was reverted while the developers still had a chance to do so: > I pr...
Python flask jinja image file not found
17,218,745
8
2013-06-20T16:19:28Z
17,219,420
7
2013-06-20T16:55:01Z
[ "python", "flask", "jinja2" ]
Newbie question. I am using Flask, a webframe for Python. Flask uses Jinja to render the template. I do not know which version of Jinja Flask uses, nor do I know how to retrieve the Jinja version or the Flask version. I use Python version 2.7. The template contains an image in the css/image directory. This image is v...
See [this section](http://flask.pocoo.org/docs/quickstart/#static-files) of the Flask documentation. The correct way to refer to the static file from your template is: ``` <img src="{{ url_for('static', filename = 'css/images/icons/resultset_previous.png') }}" width="16" height="16" alt="previous" title="Previous" bo...
Python flask jinja image file not found
17,218,745
8
2013-06-20T16:19:28Z
17,220,327
15
2013-06-20T17:44:12Z
[ "python", "flask", "jinja2" ]
Newbie question. I am using Flask, a webframe for Python. Flask uses Jinja to render the template. I do not know which version of Jinja Flask uses, nor do I know how to retrieve the Jinja version or the Flask version. I use Python version 2.7. The template contains an image in the css/image directory. This image is v...
For Flask, you should keep the static files usually under a folder "static" and then use the url\_for function. Lets say your project is called "myproject" and using your example, it should look something like: ``` myproject/ app.py templates/ static/ css/ images/ icons/...
Display a countdown for the python sleep function
17,220,128
2
2013-06-20T17:33:52Z
17,220,172
8
2013-06-20T17:36:53Z
[ "python", "time", "sleep", "stopwatch", "countdowntimer" ]
I am using time.sleep(10) in my program. Can display the countdown in the shell when I run my program? ``` >>>run_my_program() tasks done, now sleeping for 10 seconds ``` and then I want it to do 10,9,8,7.... is this possible?
you could always do ``` #do some stuff print 'tasks done, now sleeping for 10 seconds' for i in xrange(10,0,-1): time.sleep(1) print i ``` This snippet has the slightly annoying feature that each number gets printed out on a newline. To avoid this, you can ``` import sys for i in xrange(10,0,-1): time.sl...
How efficient is Python's 'in' or 'not in' operators?
17,220,296
2
2013-06-20T17:43:18Z
17,220,436
7
2013-06-20T17:50:46Z
[ "python", "iteration", "complexity-theory" ]
I have a list of over 100000 values and I am iterating over these values and checking if each one is contained in another list of random values (of the same size). I am doing this by using `if item[x] in randomList`. How efficient is this? Does python do some sort of hashing for each container or is it internally doin...
`in` is implemented by the `__contains__` magic method of the object it applies to, so the efficiency is dependent upon that. For instance, `set`, `dict` and `frozenset` will be hash based lookups, while `list` will require a linear search. However, `xrange` (or `range` in Python 3.x) has a `__contains__` method that d...
a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib
17,220,997
6
2013-06-20T18:23:17Z
17,221,642
7
2013-06-20T18:59:00Z
[ "python", "cgi", "web-scraping", "firebug", "urllib" ]
I am very new to Python (and web scraping). Let me ask you a question. Many website actually do not report its specific URLs in Firefox or other browsers. For example, Social Security Admin shows popular baby names with ranks (since 1880), but the url does not change when I change the year from 1880 to 1881. It is con...
You can still use `urllib`. The button performs a POST to the current url. Using Firefox's [Firebug](https://getfirebug.com/) I took a look at the network traffic and found they're sending 3 parameters: `member`, `top`, and `year`. You can send the same arguments: ``` import urllib url = 'http://www.ssa.gov/cgi-bin/po...
How to add a custom decorator to a fabric task
17,221,608
4
2013-06-20T18:57:34Z
17,737,706
7
2013-07-19T03:35:58Z
[ "python", "decorator", "fabric" ]
Well, I must admit I'm new to fabric and even python but I'm interested in doing it the right way, so... I want to decorate some of my tasks with a `prepare` function which adds some vars to `env` depending on those already given. Have a look: ``` from fabric.api import * import fabstork.project.base as base import fa...
``` from fabric.decorators import task from functools import wraps def custom_decorator(func): @wraps(func) def decorated(*args, **kwargs): print "this function is decorated." return func(*args, **kwargs) return decorated @task @custom_decorator def some_function(): print "this is func...
String split formatting in python 3
17,222,355
4
2013-06-20T19:37:03Z
17,222,409
10
2013-06-20T19:41:34Z
[ "python", "formatting", "newline" ]
I'm trying to format this string below where one row contains five words. However, I keep getting this as the output: > I love cookies yes I do Let s see a dog First, I am not getting 5 words in one line, but instead, everything in one line. Second, why does the "Let's" get split? I thought in splitting the string u...
As a start, don't call a variable "string" since it shadows the [module](http://docs.python.org/3/library/string.html#module-string) with the same name Secondly, use [`split()`](http://docs.python.org/3/library/stdtypes.html#str.split) to do your word-splitting ``` >>> s = """I love cookies. yes I do. Let's see a dog...
Returning distinct rows in SQLAlchemy with SQLite
17,223,174
11
2013-06-20T20:28:29Z
17,223,926
12
2013-06-20T21:15:22Z
[ "python", "sqlite", "sqlalchemy" ]
SQLAlchemy's [Query.distinct](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.distinct) method is behaving inconsistently: ``` >>> [tag.name for tag in session.query(Tag).all()] [u'Male', u'Male', u'Ninja', u'Pirate'] >>> session.query(Tag).distinct(Tag.name).count() 4 >>> session.query...
According to the docs: > When present, the Postgresql dialect will render a DISTINCT ON > (>) construct. So, passing column expressions to `distinct()` works for PostgreSQL only (because there is `DISTINCT ON`). In the expression `session.query(Tag).distinct(Tag.name).count()` sqlalchemy ignores `Tag.name` and produ...
Python multiprocessing: is it possible to have a pool inside of a pool?
17,223,301
7
2013-06-20T20:35:30Z
17,229,030
9
2013-06-21T06:34:53Z
[ "python", "multiprocessing" ]
I have a module A that does a basic map/reduce by taking data and sending it to modules B, C, D, etc for analysis and then joining their results together. But it appears that modules B, C, D, etc cannot themselves create a multiprocessing pool, or else I get ``` AssertionError: daemonic processes are not allowed to h...
> is it possible to have a pool inside of a pool? Yes, it is possible though it might not be a good idea unless you want to raise [an army of zombies](http://mail.python.org/pipermail/python-list/2011-March/600145.html). From [Python Process Pool non-daemonic?](http://stackoverflow.com/a/8963618/4279): ``` import mul...
How to ensure that messages get delivered?
17,224,331
5
2013-06-20T21:42:18Z
17,224,332
8
2013-06-20T21:42:18Z
[ "python", "rabbitmq", "message", "pika" ]
How do you ensure that messages get delivered with [Pika](https://github.com/pika/pika)? By default it will not provide you with an error if the message was not delivered succesfully. In this example several messages can be sent before pika acknowledges that the connection was down. ``` import pika connection = pika...
When using [Pika](https://github.com/pika/pika) the `channel.confirm_delivery()` flag needs to be set before you start publishing messages. This is important so that Pika will confirm that each message has been sent successfully before sending the next message. This will however increase the time it takes to send messa...
scipy ImportError on travis-ci
17,224,389
15
2013-06-20T21:45:23Z
17,254,588
13
2013-06-22T19:36:50Z
[ "python", "scipy", "travis-ci" ]
I'm setting up Travis-CI for the first time. I install scipy in what I believe is the standard way: ``` language: python python: - "2.7" # command to install dependencies before_install: - sudo apt-get -qq update - sudo apt-get -qq install python-numpy python-scipy python-opencv - sudo apt-get -qq install libh...
I found two ways around this difficulty: 1. As @unutbu suggested, build your own virtual environment and install everything using pip inside that environment. I got the build to pass, but installing scipy from source this way is very slow. 2. Following the approach used by the pandas project in [this .travis.yml file ...
Python 2.7 - Write and read a list from file
17,225,287
25
2013-06-20T23:05:20Z
17,225,333
73
2013-06-20T23:09:50Z
[ "python", "file", "list", "python-2.7", "save" ]
This is a slightly weird request but I am looking for a way to write a list to file and then read it back some other time. I have no way to remake the lists so that they are correctly formed/formatted as the example below shows. My lists have data like the following: ``` test data here this is one group :) test dat...
If you don't need it to be human-readable/editable, the easiest solution is to just use `pickle`. To write: ``` with open(the_filename, 'wb') as f: pickle.dump(my_list, f) ``` To read: ``` with open(the_filename, 'rb') as f: my_list = pickle.load(f) ``` --- If you *do* need them to be human-readable, we n...
python appending a value to a sublist
17,225,694
3
2013-06-20T23:51:21Z
17,225,716
13
2013-06-20T23:53:37Z
[ "python", "list", "append" ]
I'm running into a problem in my program and I'm not sure what I'm doing wrong. To start I created an empty list of lists. For example: ``` >>> Lists = [[]]*12 ``` which gives: ``` >>> Lists [[], [], [], [], [], [], [], [], [], [], [], []] ``` However, when trying to append a value to an individual sublist it adds ...
List objects are mutable, so you're actually making a list with 12 references to *one* list. Use a list comprehension and make 12 distinct lists: ``` Lists = [[] for i in range(12)] ``` Sorry, I can't find the original duplicate of this exact question
Simple cross import in python
17,226,016
5
2013-06-21T00:34:40Z
17,226,057
11
2013-06-21T00:40:42Z
[ "python", "import", "cross-reference" ]
I want to separate code in different class and put them to different files. However those class are dependent on each other. **main.py:** ``` from lib import A, B def main(): a = A() b = B() a.hello() b.hello() if __name__ == '__main__': main() ``` **lib/\_*init*\_.py**: ``` from a import A fr...
Instead of importing the modules on top, you could import the other module within the hello function. ``` class B(): def __init__(self): print "B" def hello(self): import lib.A print "hello B" a = A() ```
Python: wildcard subset import
17,226,390
7
2013-06-21T01:30:50Z
17,226,922
7
2013-06-21T02:40:27Z
[ "python", "import", "wildcard" ]
We have all been told using `from module import *` is a bad idea. However, is there a way to import a **subset** of the contents of `module` using a wildcard? For example: module.py: ``` MODULE_VAR1 = "hello" MODULE_VAR2 = "world" MODULE_VAR3 = "The" MODULE_VAR4 = "quick" MODULE_VAR5 = "brown" ... MODULE_VAR10 = "la...
You can have a helper function for that - and it can be done without magic: ``` import re def matching_import(pattern, module, globals): for key, value in module.__dict__.items(): if re.findall(pattern, key): globals[key] = value ``` Now, you can do for example: ``` from utils import matchin...
Django humanize outside of template?
17,226,779
7
2013-06-21T02:22:00Z
17,226,840
16
2013-06-21T02:30:00Z
[ "python", "django", "django-templates" ]
I know I can use the humanize module to convert date/time to a friendlier format. I was wondering if I can convert those things in a views.py function (meaning outside of a django template).
Yes you can Lets say you want to call `naturalday` in `views.py` you would do ``` from django.contrib.humanize.templatetags.humanize import naturalday natural_day = naturalday(value) ``` You can refer to the [source code here](https://github.com/django/django/blob/master/django/contrib/humanize/templatetags/humanize...
Why does simple echo in subprocess not working
17,226,912
6
2013-06-21T02:38:53Z
17,226,978
8
2013-06-21T02:51:46Z
[ "python", "linux", "subprocess" ]
I'm trying to perform simple echo operation using subprocess: ``` import subprocess import shlex cmd = 'echo $HOME' proc = subprocess.Popen(shlex.split(cmd), shell=True, stdout=subprocess.PIPE) print proc.communicate()[0] ``` But it prints nothing. Even if I change the command to `echo "hello, world"` it still print...
On Unix `shell=True` implies that 2nd and following arguments are for the shell itself, use a string to pass a command to the shell: ``` import subprocess cmd = 'echo $HOME' proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) print proc.communicate()[0], ``` You could also write it as: ``` import subpr...
How to dynamically generate XML file for RSS Feed?
17,229,544
2
2013-06-21T07:08:12Z
17,254,864
8
2013-06-22T20:11:18Z
[ "python", "rss" ]
I want to create a RSS Feed generator. The generator is supposed to read data from my database and generate RSS feeds for them. I want to write a script that would automatically generate the `xml` file for validation. So if a typical `xml` file for RSS feed looks like this: ``` <item> <title>Entry Title</title> ...
Since this is python. Its good to be using `PyRSS2Gen`. Its easy to use and generates the xml really nicely. <https://pypi.python.org/pypi/PyRSS2Gen>
eval() does not assign variable at runtime
17,230,005
6
2013-06-21T07:37:04Z
17,230,027
11
2013-06-21T07:38:02Z
[ "python", "string", "eval" ]
I use `eval()` to assign a list to a var: ``` eval('mylist = [1,2,3]') ``` but when I run it , I got a SyntaxError. What's wrong with it? If I cannot do assignment in the `eval()`, how do I assign a var in the runtime.
Use `exec` for statements: ``` >>> exec 'lis = [1,2,3]' >>> lis [1, 2, 3] ``` `eval` works only on expressions, like `2*2`,`4+5` etc `eval` and `exec` are okay if the string is coming from a known source, but don't use them if the string is coming from an unknown source(user input). Read : [Be careful with exec and...
python: order of AND execution
17,231,945
4
2013-06-21T09:34:15Z
17,231,974
7
2013-06-21T09:35:42Z
[ "python", "boolean-logic" ]
If I have the following: ``` if a(my_var) and b(my_var): do something ``` Can I assume that `b()` is only evaluated if `a()` is `True`? Or might it do `b()` first? Asking because evaluating `b()` will cause an exception when `a()` is `False`.
`b()` will only be evaluated if `a(my_var)` is `True`, yes. The `and` operator short-circuits if `a(my_var)` is falsey. From the [boolean operators documentation](http://docs.python.org/2/reference/expressions.html#boolean-operations): > The expression `x and y` first evaluates `x`; if `x` is false, its value is retu...
Creating tables in matplotlib
17,232,683
13
2013-06-21T10:11:36Z
17,237,728
8
2013-06-21T14:27:33Z
[ "python", "table", "matplotlib" ]
I'm trying to make a table using matplotlib and I've managed to get my data in but I'm struggling with the final formatting. I need to edit the size of the figure to include all my data as some is getting chopped off. Here is my current code: ``` for struct, energy, density in clust_data: fig=plt.figure() ax =...
You should be able to solve your problems doing the following: * Figure size (**edit**): + Measure how high and wide is a cell (e.g. `hcell=0.3`, `wcell=1`) + Get/know the number of rows and columns (in your case `len(clust_data)+1` and 3) + create the figure with the correct size (you might want some extra pad...
Django Nose how to write this test?
17,232,747
7
2013-06-21T10:14:54Z
17,271,359
13
2013-06-24T08:46:32Z
[ "python", "django", "unit-testing", "testing", "nose" ]
I'm completely new to **testing** in Django. I have started by installing **nose** and **selenium** and now I want to test the following code *(below)* It sends an SMS message. This is the actual code: **views.py** ``` @login_required def process_all(request): """ I process the sending for a single or bulk m...
First of all, you don't need `selenium` for testing views. Selenium is a tool for high-level in-browser testing - it's good and useful when you are writing UI tests simulating a real user. Nose is a tool that `makes testing easier` by providing features like automatic test discovery, supplies a number of helper functi...
Haystack Multiple Indices - indexed same even there are different search_indexes
17,233,752
3
2013-06-21T11:07:36Z
19,362,503
7
2013-10-14T14:25:33Z
[ "python", "django", "django-haystack" ]
I have the following search ``` class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) destination = indexes.FacetIntegerField( model_attr='hotel__destination__id') country = indexes.FacetIntegerField(model_attr='hotel__country__id') ...
You can exclude indexes using key `EXCLUDED_INDEXES`: ``` HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', 'EXCLUDED_INDEXES': ['my_destination_app....
Passing a Python list to php
17,235,467
3
2013-06-21T12:40:06Z
17,235,651
7
2013-06-21T12:49:05Z
[ "php", "python", "parameter-passing" ]
I'm very new to php and I've been spending quite some type understanding how to pass arguments from Python to php and conversely. I now know how to pass single variables, but I am still stuck and can't seem to find an answer to this one: Php calls a Python script (that part works) that returns a list of strings. I'd l...
For instance: **myscript.py** ``` import json D = {'foo':1, 'baz': 2} print json.dumps(D) ``` **myscript.php** ``` <?php $result = json_decode(exec('python myscript.py'), true); echo $result['foo']; ```
Unable to return a value from a function
17,235,978
6
2013-06-21T13:05:12Z
17,236,017
8
2013-06-21T13:06:48Z
[ "python", "python-2.7" ]
I have a small piece of code to understand how to return values that can be used in other sections of the code. In the following i only want to return the variable z, or the value snooze. But it does not work. Please can someone help me to understand why this will not work? ``` import time def sleepy(reps, snooze): ...
`z` is a local variable in your `sleepy()` function; it is not visible outside of that function. Your function does return the value of `z`; assign it: ``` slept = sleepy(10, 0.001) print slept ``` I used a different name here to illustrate that `slept` is a different variable.
Reading from a text file with python - first line being missed
17,237,464
3
2013-06-21T14:12:42Z
17,237,486
7
2013-06-21T14:13:57Z
[ "python", "file-io" ]
I have a file called test which has the contents: ``` a b c d e f g ``` I am using the following python code to read this file line by line and print it out: ``` with open('test.txt') as x: for line in x: print(x.read()) ``` The result of this is to print out the contents of the text file except for the...
Because `for line in x` iterates through every line. ``` with open('test.txt') as x: for line in x: # By this point, line is set to the first line # the file cursor has advanced just past the first line print(x.read()) # the above prints everything after the first line # fil...
Python3 Singleton metaclass method not working
17,237,857
3
2013-06-21T14:33:35Z
17,237,903
8
2013-06-21T14:35:51Z
[ "python", "python-3.x", "singleton", "metaclass" ]
I saw a lot of methods of making a singleton in Python and I tried to use the metaclass implementation with Python 3.2 (Windows), but it doesn"t seem to return the same instance of my singleton class. ``` class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._inst...
The metaclass syntax [has changed](http://www.python.org/dev/peps/pep-3115/) in Python3. See [the documentaition](http://docs.python.org/3.2/reference/datamodel.html#customizing-class-creation). ``` class MyClass(metaclass=Singleton): pass ``` And it works: ``` >>> MyClass() is MyClass() True ```
Changing console_script entry point interpreter for packaging
17,237,878
7
2013-06-21T14:34:41Z
17,329,493
10
2013-06-26T20:07:42Z
[ "python", "setuptools", "distutils" ]
I'm packaging some python packages using a well known third party packaging system, and I'm encountering an issue with the way entry points are created. When I install an entry point on my machine, the entry point will contain a shebang pointed at whatever python interpreter, like so: in **/home/me/development/test/s...
You can customize the console\_scripts' shebang line by setting 'sys.executable' (learned this from a [debian bug report](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=548392)). That is to say... ``` sys.executable = '/bin/custom_python' setup( entry_points={ 'console_scripts': [ ... etc... ] } ...
Returning a row from a CSV, if specified value within the row matches condition
17,238,567
4
2013-06-21T15:07:24Z
17,238,748
7
2013-06-21T15:16:07Z
[ "python", "csv", "python-2.7", "dictionary" ]
Ahoy, I'm writing a Python script to filter some large CSV files. I only want to keep rows which meet my criteria. My input is a CSV file in the following format > ``` > Locus Total_Depth Average_Depth_sample Depth_for_17 > chr1:6484996 1030 1030 1030 > chr1:6484997 14 ...
Use list comprehension. ``` import csv with open("filepath", 'rb') as f: reader = csv.DictReader(f) rows = [row for row in reader if row['Total_Depth'] != '0'] for row in rows: print row ``` [DictReader](http://docs.python.org/2/library/csv.html#csv.DictReader)
opencv, BGR2HSV creates lots of artifacts
17,239,253
3
2013-06-21T15:43:19Z
28,201,863
7
2015-01-28T20:32:53Z
[ "python", "opencv", "image-processing", "hsv" ]
![enter image description here](http://i.stack.imgur.com/kVsEa.png) This image is just an example. Top right is the original image, top left is the hue, bottom left the saturation and bottom right is the value. As can be easily seen both H and S are filled with artifacts. I want to reduce the brightness so the result ...
I feel there is a misunderstanding in your question. While the answer of Boyko Peranov is certainly true, there are no problems with the images you provided. The logic behind it is the following: your camera takes pictures in the RGB color space, which is by definition a cube. When you convert it to the HSV color space...
python: how to plot one line in different colors
17,240,694
7
2013-06-21T17:04:41Z
17,241,345
11
2013-06-21T17:47:23Z
[ "python", "matplotlib" ]
I have two list as below: ``` latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879] lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925] ``` now I want to plot this as a line, separate each 10 of those 'latt' and 'lont' records as a period and ...
There are several different ways to do this. The "best" approach will depend mostly on how many line segments you want to plot. If you're just going to be plotting a handful (e.g. 10) line segments, then just do something like: ``` import numpy as np import matplotlib.pyplot as plt def uniqueish_color(): """Ther...
Pandas - how to get the data frame index as an array
17,241,004
69
2013-06-21T17:25:25Z
17,241,104
21
2013-06-21T17:32:23Z
[ "python", "pandas" ]
Do you know how to get the index column of an dataframe as an array? I have a list of accession numbers in the "Accession" column of a CSV file, which I imported into Pandas, and during the import, I set the index to the "Accession" column. Now, I need the "Accession" column to be a set of labels in a later step, but I...
You can use `df.index` to access the index object and then get the values in a list using `df.index.tolist()`.
Pandas - how to get the data frame index as an array
17,241,004
69
2013-06-21T17:25:25Z
17,242,374
81
2013-06-21T18:51:13Z
[ "python", "pandas" ]
Do you know how to get the index column of an dataframe as an array? I have a list of accession numbers in the "Accession" column of a CSV file, which I imported into Pandas, and during the import, I set the index to the "Accession" column. Now, I need the "Accession" column to be a set of labels in a later step, but I...
You should use the `values` attribute: ``` In [1]: df = pd.DataFrame(index=['a', 'b']) In [2]: df.index.values Out[2]: array(['a', 'b'], dtype=object) ``` *This accesses how the data is already stored, so there's no need for a conversion. Note: This attribute is also available for many other pandas' objects.*
Pandas - how to get the data frame index as an array
17,241,004
69
2013-06-21T17:25:25Z
29,774,704
8
2015-04-21T14:11:44Z
[ "python", "pandas" ]
Do you know how to get the index column of an dataframe as an array? I have a list of accession numbers in the "Accession" column of a CSV file, which I imported into Pandas, and during the import, I set the index to the "Accession" column. Now, I need the "Accession" column to be a set of labels in a later step, but I...
If you are dealing with a multi-index dataframe, you may be interested in extracting only the column of one name of the multi-index. You can do this as ``` df.index.get_level_values('name_sub_index') ``` and of course `name_sub_index` must be an element of the `FrozenList` `df.index.names`
Filling a queue and managing multiprocessing in python
17,241,663
8
2013-06-21T18:07:34Z
17,242,221
11
2013-06-21T18:41:06Z
[ "python", "queue", "multiprocessing", "pool" ]
I'm having this problem in python: * I have a queue of URLs that I need to check from time to time * if the queue is filled up, I need to process each item in the queue * Each item in the queue must be processed by a single process (multiprocessing) So far I managed to achieve this "manually" like this: ``` while 1:...
You could use the blocking capabilities of [`queue`](http://docs.python.org/2/library/multiprocessing.html#pipes-and-queues) to spawn multiple process at startup (using [`multiprocessing.Pool`](http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool)) and letting them sleep until some data are...
Opencv polylines function in python throws exception
17,241,830
8
2013-06-21T18:17:29Z
17,242,059
7
2013-06-21T18:31:00Z
[ "python", "opencv", "numpy", "points" ]
I'm trying to draw an arbitrary quadrilateral over an image using the polylines function in opencv. When I do I get the following error > OpenCV Error: Assertion failed (p.checkVector(2, CV\_32S) >= 0) in > polylines, file > /tmp/buildd/ros-fuerte-opencv2-2.4.2-1precise-20130312-1306/modules/core/src/d > rawing.cpp, l...
This function is not enough well documented and the error are also not very useful. In any case, [`cv2.polylines`](http://docs.opencv.org/modules/core/doc/drawing_functions.html#polylines) expects a list of points, just change your line to this: ``` import cv2 import numpy as np img = np.zeros((768, 1024, 3), dtype='...
Opencv polylines function in python throws exception
17,241,830
8
2013-06-21T18:17:29Z
18,817,152
8
2013-09-15T20:26:10Z
[ "python", "opencv", "numpy", "points" ]
I'm trying to draw an arbitrary quadrilateral over an image using the polylines function in opencv. When I do I get the following error > OpenCV Error: Assertion failed (p.checkVector(2, CV\_32S) >= 0) in > polylines, file > /tmp/buildd/ros-fuerte-opencv2-2.4.2-1precise-20130312-1306/modules/core/src/d > rawing.cpp, l...
The problem in my case was that `numpy.array` created `int64`-bit numbers by default. So I had to explicitly convert it to `int32`: ``` points = np.array([[910, 641], [206, 632], [696, 488], [458, 485]]) # points.dtype => 'int64' cv2.polylines(img, np.int32([points]), 1, (255,255,255)) ``` (Looks like a bug in cv2 py...
for loop in python is 10x slower than matlab
17,242,684
5
2013-06-21T19:13:21Z
17,242,928
7
2013-06-21T19:29:46Z
[ "python", "matlab", "for-loop" ]
I run python 2.7 and matlab R2010a on the same machine, doing nothing, and it gives me 10x different in speed I looked online, and heard it should be the same order. Python will further slow down as if statement and math operator in the for loop My question: is this the reality? or there is some other way let them in...
The reason this is happening is related to the [JIT](http://www.matlabtips.com/matlab-is-no-longer-slow-at-for-loops/) compiler, which is optimizing the MATLAB for loop. You can disable/enable the JIT accelerator using `feature accel off` and `feature accel on`. When you disable the accelerator, the times change dramat...
Python: subprocess and running a bash script with multiple arguments
17,242,828
9
2013-06-21T19:23:20Z
17,243,334
19
2013-06-21T19:57:48Z
[ "python", "bash", "arguments", "subprocess", "popen" ]
How do I go about running a bash script using the subprocess module, to which I must give several arguments? This is what I'm currently using: ``` subprocess.Popen(['/my/file/path/programname.sh', 'arg1 arg2 %s' % arg3], \ shell = True) ``` The bash script seems not to be taking any of the parameters in. Any ins...
Pass arguments as a list, see [the very first code example in the docs](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module): ``` import subprocess subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3]) ``` If `arg3` is not a string; convert it to string before passing...
Python list comprehension with multiple variables
17,243,129
3
2013-06-21T19:42:48Z
17,243,155
8
2013-06-21T19:44:13Z
[ "python", "list", "list-comprehension" ]
I am trying to get a list with a specific output from an index in another list, for example: ``` L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)] multiple_index = [entry[0, 3, 4] for entry in L] #----> I know this specific code is wrong ``` I would love it if the above code could output: ``` [(0, 3, 4), ...
Use [`operator.itemgetter()`](http://docs.python.org/2/library/operator.html#operator.itemgetter): ``` from operator import itemgetter multiple_index = map(itemgetter(0, 3, 4), L) ``` or in a list comprehension: ``` multiple_index = [itemgetter(0, 3, 4)(i) for i in L] ```
operator.itemgetter or lambda
17,243,620
16
2013-06-21T20:16:23Z
17,243,726
21
2013-06-21T20:22:55Z
[ "python", "python-2.7", "python-3.x" ]
I was curious if there was any indication of which of `operator.itemgetter(0)` or `lambda x:x[0]` is better to use, specifically in `sorted()` as the `key` keyword argument as that's the use that springs to mind first. Are there any known performance differences? Are there any PEP related preferences or guidance on the...
The performance of itemgetter is slightly better: ``` >>> f1 = lambda: sorted(w, key=lambda x: x[1]) >>> f2 = lambda: sorted(w, key=itemgetter(1)) >>> timeit(f1) 21.33667682500527 >>> timeit(f2) 16.99106214600033 ```
Finding label location in a DataFrame Index (pandas
17,244,049
10
2013-06-21T20:46:40Z
17,244,095
21
2013-06-21T20:49:15Z
[ "python", "pandas" ]
I have a dataframe that looks like so, ``` In [69]: import pandas as pnd d = pnd.Timestamp('2013-01-01 16:00') dates = pnd.bdate_range(start=d, end = d+pnd.DateOffset(days=10), normalize = False) df = pnd.DataFrame(index=dates, columns=['a']) df['a'] = 6 print df a 2013-01-01 16:00:00 6 2013-01...
You're looking for the index method `get_loc`: ``` In [11]: df.index.get_loc(ds) Out[11]: 1 ```
reading struct in python from created struct in c
17,244,488
7
2013-06-21T21:21:16Z
17,246,128
7
2013-06-22T00:27:23Z
[ "python", "c" ]
I am very new at using Python and very rusty with C, so I apologize in advance for how dumb and/or lost I sound. I have function in C that creates a .dat file containing data. I am opening the file using Python to read the file. One of the things I need to read are a struct that was created in the C function and print...
You could use [`ctypes.Structure`](https://docs.python.org/2/library/ctypes.html#ctypes.Structure) or [`struct.Struct`](https://docs.python.org/2/library/struct.html#struct.Struct) to specify format of the file. To read structures from the file produced by [C code in @perreal's answer](http://stackoverflow.com/a/172446...
How to update XML file with lxml
17,245,310
6
2013-06-21T22:37:12Z
17,245,460
7
2013-06-21T22:55:38Z
[ "python", "xml", "lxml" ]
I want to update xml file with new information by using lxml library. For example, I have this code: ``` >>> from lxml import etree >>> >>> tree = etree.parse('books.xml') ``` where 'books.xml' file, has this content: <http://www.w3schools.com/dom/books.xml> I want to update this file with new book: ``` >>> new_ent...
Here you go, get the root of the tree, append your new element, save the tree as a string to a file: ``` from lxml import etree tree = etree.parse('books.xml') new_entry = etree.fromstring('''<book category="web" cover="paperback"> <title lang="en">Learning XML 2</title> <author>Erik Ray</author> <year>2006</year> <...
Read and Write CSV files including unicode with Python 2.7
17,245,415
36
2013-06-21T22:49:31Z
17,245,651
24
2013-06-21T23:20:17Z
[ "python", "csv", "python-2.7", "unicode", "export" ]
I am new to Python, and I have a question about how to use Python to read and write CSV files. My file contains like Germany, French, etc. According to my code, the files can be read correctly in Python, but when I write it into a new CSV file, the unicode becomes some strange characters. The data is like: ![enter ima...
There is an example at the end of the [csv module documentation](http://docs.python.org/2.7/library/csv.html) that demonstrates how to deal with Unicode. Below is copied directly from that [example](http://docs.python.org/2.7/library/csv.html#examples). Note that the strings read or written will be Unicode strings. Don...
Read and Write CSV files including unicode with Python 2.7
17,245,415
36
2013-06-21T22:49:31Z
17,246,997
29
2013-06-22T03:13:47Z
[ "python", "csv", "python-2.7", "unicode", "export" ]
I am new to Python, and I have a question about how to use Python to read and write CSV files. My file contains like Germany, French, etc. According to my code, the files can be read correctly in Python, but when I write it into a new CSV file, the unicode becomes some strange characters. The data is like: ![enter ima...
Make sure you encode and decode as appropriate. This example will roundtrip some example text in utf-8 to a csv file and back out to demonstrate: ``` # -*- coding: utf-8 -*- import csv tests={'German': [u'Straße',u'auslösen',u'zerstören'], 'French': [u'français',u'américaine',u'épais'], 'Chines...
Read and Write CSV files including unicode with Python 2.7
17,245,415
36
2013-06-21T22:49:31Z
24,035,677
17
2014-06-04T11:02:08Z
[ "python", "csv", "python-2.7", "unicode", "export" ]
I am new to Python, and I have a question about how to use Python to read and write CSV files. My file contains like Germany, French, etc. According to my code, the files can be read correctly in Python, but when I write it into a new CSV file, the unicode becomes some strange characters. The data is like: ![enter ima...
Another alternative: is to use the code from the unicodecsv package ... <https://pypi.python.org/pypi/unicodecsv/> ``` >>> import unicodecsv as csv >>> from io import BytesIO >>> f = BytesIO() >>> w = csv.writer(f, encoding='utf-8') >>> _ = w.writerow((u'é', u'ñ')) >>> _ = f.seek(0) >>> r = csv.reader(f, encoding='...
Python readlines() usage and efficient practice for reading
17,246,260
17
2013-06-22T00:48:23Z
17,246,267
7
2013-06-22T00:49:34Z
[ "python", "performance", "memory", "python-2.6", "readlines" ]
I have a problem to parse 1000's of text files(around 3000 lines in each file of ~400KB size ) in a folder. I did read them using readlines, ``` for filename in os.listdir (input_dir) : if filename.endswith(".gz"): f = gzip.open(file, 'rb') else: f = open(file, 'rb') file_c...
Read line by line, not the whole file: ``` for line in open(file_name, 'rb'): # process line here ``` Even better use `with` for automatically closing the file: ``` with open(file_name, 'rb') as f: for line in f: # process line here ``` The above will read the file object using an iterator, one line...
Python readlines() usage and efficient practice for reading
17,246,260
17
2013-06-22T00:48:23Z
17,246,300
41
2013-06-22T00:55:10Z
[ "python", "performance", "memory", "python-2.6", "readlines" ]
I have a problem to parse 1000's of text files(around 3000 lines in each file of ~400KB size ) in a folder. I did read them using readlines, ``` for filename in os.listdir (input_dir) : if filename.endswith(".gz"): f = gzip.open(file, 'rb') else: f = open(file, 'rb') file_c...
The short version is: [The efficient way to use `readlines()` is to not use it. Ever.](http://stupidpythonideas.blogspot.com/2013/06/readlines-considered-silly.html) --- > I read some doc notes on `readlines()`, where people has claimed that this `readlines()` reads whole file content into memory and hence generally ...
Does Python all(list) use short circuit evaluation?
17,246,388
6
2013-06-22T01:12:30Z
17,246,413
12
2013-06-22T01:16:29Z
[ "python", "evaluation", "short-circuiting" ]
I wish to use the Python all() function to help me compute something, but this something could take substantially longer if the all() does not evaluate as soon as it hits a False. I'm thinking it probably is short-circuit evaluated, but I just wanted to make sure. Also, is there a way to tell in Python how the function...
Yes, it short-circuits: ``` >>> def test(): ... yield True ... print('one') ... yield False ... print('two') ... yield True ... print('three') ... >>> all(test()) one False ``` ## From the [docs](http://docs.python.org/2/library/functions.html#all): Return True if all elements of the iterable...
What exactly is the difference between shallow copy, deepcopy and normal assignment operation?
17,246,693
72
2013-06-22T02:15:56Z
17,246,743
23
2013-06-22T02:25:26Z
[ "python" ]
``` import copy a=”deepak” b=1,2,3,4 c=[1,2,3,4] d={1:10,2:20,3:30} a1=copy.copy(a) b1=copy.copy(b) c1=copy.copy(c) d1=copy.copy(d) print "immutable - id(a)==id(a1)",id(a)==id(a1) print "immutable - id(b)==id(b1)",id(b)==id(b1) print "mutable - id(c)==id(c1)",id(c)==id(c1) print "mutable - id(d)==id(d1)",id...
For immutable objects, there is no need for copying because the data will never change, so Python uses the same data, ids are always the same. For mutable objects, since they can potentially change, [shallow] copy creates a new object. Deep copy is related to nested structures, if you have list of lists, then deepcopy...
What exactly is the difference between shallow copy, deepcopy and normal assignment operation?
17,246,693
72
2013-06-22T02:15:56Z
17,246,744
136
2013-06-22T02:25:38Z
[ "python" ]
``` import copy a=”deepak” b=1,2,3,4 c=[1,2,3,4] d={1:10,2:20,3:30} a1=copy.copy(a) b1=copy.copy(b) c1=copy.copy(c) d1=copy.copy(d) print "immutable - id(a)==id(a1)",id(a)==id(a1) print "immutable - id(b)==id(b1)",id(b)==id(b1) print "mutable - id(c)==id(c1)",id(c)==id(c1) print "mutable - id(d)==id(d1)",id...
Normal assignment operations will simply point the new variable towards the existing object. The [docs](http://docs.python.org/2/library/copy.html) explain the difference between shallow and deep copies: > The difference between shallow and deep copying is only relevant for > compound objects (objects that contain oth...
How to find all <li>'s within a specific <ul> class?
17,246,963
2
2013-06-22T03:05:56Z
17,246,983
7
2013-06-22T03:10:25Z
[ "python", "python-2.7", "beautifulsoup" ]
**Environment:** Beautiful Soup 4 Python 2.7.5 **Logic:** 'find\_all' `<li>` instances that are within a `<ul>` with a class of `my_class` eg: ``` <ul class='my_class'> <li>thing one</li> <li>thing two</li> </ul> ``` Clarification: Just get the 'text' between the `<li>` tags. **Python Code:** (The find\_all bel...
This? ``` >>> html = """<ul class='my_class'> ... <li>thing one</li> ... <li>thing two</li> ... </ul>""" >>> from bs4 import BeautifulSoup as BS >>> soup = BS(html) >>> for ultag in soup.find_all('ul', {'class': 'my_class'}): ... for litag in ultag.find_all('li'): ... print litag.text ... thing one th...
How to run a python script from IDLE interactive shell?
17,247,471
38
2013-06-22T05:03:02Z
17,247,565
15
2013-06-22T05:18:43Z
[ "python", "shell", "command-line", "python-idle" ]
How do I run a python script from within the IDLE interactive shell? The following throws an error: ``` >>> python helloworld.py SyntaxError: invalid syntax ```
The IDLE shell window is not the same as a terminal shell (e.g. running `sh` or `bash`). Rather, it is just like being in the Python interactive interpreter (`python -i`). The easiest way to run a script in IDLE is to use the `Open` command from the `File` menu (this may vary a bit depending on which platform you are r...
How to run a python script from IDLE interactive shell?
17,247,471
38
2013-06-22T05:03:02Z
21,650,698
56
2014-02-08T19:21:05Z
[ "python", "shell", "command-line", "python-idle" ]
How do I run a python script from within the IDLE interactive shell? The following throws an error: ``` >>> python helloworld.py SyntaxError: invalid syntax ```
Built-in function: [execfile](https://docs.python.org/2/library/functions.html#execfile) ``` execfile('helloworld.py') ``` Deprecated since 2.6: [popen](https://docs.python.org/2/library/os.html?highlight=popen#os.popen) ``` import os os.popen('python helloworld.py') # Just run the program os.popen('python helloworl...
How to tell Python to automatically use the proxy setting in Windows XP like R's internet2 option?
17,247,981
5
2013-06-22T06:27:19Z
17,248,931
8
2013-06-22T08:48:46Z
[ "python", "proxy" ]
I am not super technical person. But I know that in Windows if I install R using the internet2 option then I can download whatever package I want in it. I install Python and everytime I try to download a package or install a package (e.g. using easy\_install) it fails. What can I do to make Python automatically detec...
Set up environment variable `http_proxy` / `https_proxy` to `http://your-proxy-server-address:proxy-port` > The urlopen() function works transparently with proxies which do not > require authentication. In a Unix or Windows environment, set the > http\_proxy, or ftp\_proxy environment variables to a URL that > identif...
Pretty print by default in Python REPL
17,248,383
16
2013-06-22T07:26:36Z
17,248,460
7
2013-06-22T07:34:20Z
[ "python", "read-eval-print-loop" ]
How can i enable pretty print on the REPL by default? Currently I do it by using `pprint.pprint()` function. ``` >>> pprint.pprint(data) {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0, 'THUMBNAIL': ''} ``` But I want pretty print by default ``` >...
Use [IPython](http://ipython.org/) shell: ``` In [10]: data = {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0,} In [11]: data Out[11]: {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0} ...
Pretty print by default in Python REPL
17,248,383
16
2013-06-22T07:26:36Z
17,248,483
17
2013-06-22T07:37:38Z
[ "python", "read-eval-print-loop" ]
How can i enable pretty print on the REPL by default? Currently I do it by using `pprint.pprint()` function. ``` >>> pprint.pprint(data) {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0, 'THUMBNAIL': ''} ``` But I want pretty print by default ``` >...
Use [sys.displayhook](http://docs.python.org/2/library/sys#sys.displayhook) ``` import pprint import sys orig_displayhook = sys.displayhook def myhook(value): if value != None: __builtins__._ = value pprint.pprint(value) __builtins__.pprint_on = lambda: setattr(sys, 'displayhook', myhook) __buil...
Avoid HTML escaping in bottle (python)
17,248,836
6
2013-06-22T08:35:19Z
17,249,031
7
2013-06-22T09:01:39Z
[ "python", "bottle" ]
I'm making a songs lyrics webapp in Bottle (python), and I'm testing all the data is correct before inserting it to the database, so, for now, I basically have a form that has "song name", "artist", "lyrics" (in a textarea) and that's it. When the form submits it loads a page containing the three input values mentione...
You need to place the exclamation mark *right after* the opening `{{` for bottle to recognize it: ``` <div>Letra: {{! letra['letra'] }}</div> ``` Preferably, you want to omit the spaces there altogether, to be on the safe side: ``` <div>Letra: {{!letra['letra']}}</div> ```
List all available routes in Flask, along with corresponding functions' docstrings
17,249,953
13
2013-06-22T10:57:12Z
17,250,154
19
2013-06-22T11:19:08Z
[ "python", "flask" ]
I'm writing a small API, and wanted to print a list of all available methods along with the corresponding "help text" (from the function's docstring). Starting off from [this answer](http://stackoverflow.com/a/13318415/2511466), I wrote the following: ``` from flask import Flask, jsonify app = Flask(__name__) @app.r...
There is `app.view_functions`. I think that is exactly what you want. ``` from flask import Flask, jsonify app = Flask(__name__) @app.route('/api', methods = ['GET']) def this_func(): """This is a function. It does nothing.""" return jsonify({ 'result': '' }) @app.route('/api/help', methods = ['GET']) def h...
Checking if a Django user has a password set
17,250,226
10
2013-06-22T11:27:13Z
17,250,296
15
2013-06-22T11:36:09Z
[ "python", "django", "django-users" ]
I setup if statement to see if the current user has a password set. For some reason it just won't work. I have tried: ``` {% if not user.password %} {% if user.password == None %} {% if user.password is None %} ``` I have 2 user accounts (different browsers open), one with a password in one, and one without in the ot...
Use [user.has\_usable\_password](https://docs.djangoproject.com/en/dev/ref/contrib/auth/#django.contrib.auth.models.User.has_usable_password) ``` >>> a = User.objects.create_user('user1', '[email protected]') >>> b = User.objects.create_user('user2', '[email protected]', password='secret') >>> a.has_usable_password() ...
Change OptionMenu based on what is selected in another OptionMenu
17,252,096
9
2013-06-22T15:03:05Z
17,252,390
15
2013-06-22T15:35:43Z
[ "python", "dynamic", "tkinter", "optionmenu" ]
I am currently trying to make two `OptionMenu`s, where the second will be updated dynamically based on what is selected in the first `OptionMenu`. For example, I would like to make `OptionMenu_A` with list ``` [North America, Europe, Asia] ``` * If `Asia` is selected, then `OptionMenu_B` will change to something lik...
Yes, it is possible. With `StringVar.trace` you can check when the first option has been changed. Then delete all the options of the second OptionMenu and populate it with the corresponding options. If you have a data structure like a dictionary behind this, it can be very easy to map the correspondences: ``` import s...
Matplotlib, adding text with more than one line. Adding text that can follow the curve
17,252,790
4
2013-06-22T16:18:54Z
17,252,890
9
2013-06-22T16:32:00Z
[ "python", "text", "matplotlib", "curve" ]
I have added text to a plot, coded in each line, and then adjusted it look decent, increase or decrease the width, or change the placement. However, is there a way to have Python know where you want the text and how you want it set? Then I could add the text and Python would work out the details. For example, take a l...
You can use line separators `\n`: ``` pylab.text(1, 1.5, '$r_1 = 1.0$ AU\n' +\ '$r_2 = 1.524$ AU\n' +\ '$\\Delta \\nu = 75^{\\circ}$', fontsize = 11, color = 'r') ``` `pylab.text()` uses data coordinates by default, but you can use relative positions `(0,0)` to the lower-left ...
Create many to many on one table
17,252,816
5
2013-06-22T16:22:23Z
17,253,539
9
2013-06-22T17:41:16Z
[ "python", "flask-sqlalchemy" ]
Flask-SQLAlchemy gives an [example](http://pythonhosted.org/Flask-SQLAlchemy/models.html#many-to-many-relationships) of how to create a many to many relationship. It is done between two different tables. Is it possible to create a many to many relationship on the same table? For example a sister can have many sisters,...
You are trying to build what is called an [adjacency list](http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#adjacency-list-relationships). That is you have a table with foreign key to itself. In your specific case it is a [self referencial many to many relationship](http://docs.sqlalchemy.org/en/rel_0_8/or...
Difference between 'not x' and 'x==None' in python
17,252,951
9
2013-06-22T16:38:49Z
17,252,997
12
2013-06-22T16:43:50Z
[ "python" ]
Can `not x` and `x==None` give different answers if `x` is a class instance ? I mean how is `not x` evaluated if `x` is a class instance ?
yes it **can** give different answers. ``` x == None ``` will call the [`__eq__()`](http://docs.python.org/2/reference/datamodel.html#object.__eq__) method to valuate the operator and give the result implemented compared to the `None` singleton. ``` not x ``` will call the [`__nonzero__()`](http://docs.python.org/2...
AttributeError with Django REST Framework and MongoEngine
17,253,164
4
2013-06-22T16:59:42Z
17,254,286
11
2013-06-22T19:00:23Z
[ "python", "django", "mongoengine", "django-rest-framework" ]
I am trying to use Django and the Django REST Framework together with MongoEngine but it doesn't seem to work for me. I don't know where things go wrong ... perhaps someone can help me out. Here is the code: models.py ``` from mongoengine import * class Lady(Document): firstname = StringField() lastname = St...
Finally got the solution. I needed to explicitly set **many=False** to make it work. So this works fine: ``` from core.models import * from core.serializers import * tiger = Lady(firstname='Tiger', lastname="Lily") serial = LadySerializer(tiger, many=False) serial.data ``` and yields: ``` {'firstname': u'Tiger', 'l...
Why does range in python "stop short"?
17,253,920
2
2013-06-22T18:19:26Z
17,253,978
8
2013-06-22T18:25:22Z
[ "python", "range" ]
OK, teaching python to the kids. We just wrote our first little program: ``` b = 0 for a in range (1, 10) b = b + 1 print a, b ``` Stops at 9, 9. They asked "why is that" and I can't say that I know the answer. My code *always* involves files, and my "for row in reader" doesn't stop one line short, so I don'...
It's just usually more useful than the alternatives. * `range(10)` returns exactly 10 items (if you want to repeat something 10 times) * `range(10)` returns exactly the indices in a list of 10 items * `range(0, 5) + range(5, 10) == range(0, 10)`, which makes it easier to reason about ranges
Unable to create models on Flask-admin
17,254,840
8
2013-06-22T20:09:07Z
17,256,424
14
2013-06-22T23:46:38Z
[ "python", "flask", "flask-sqlalchemy", "flask-extensions" ]
I'm creating a simple blog on Flask and I'm trying to implement Flask-Admin to manage my posts. If I go to the admin area I can see a list of all my post from the DB but when I try to create a new one I got the next error: ``` Failed to create model. __init__() takes exactly 4 arguments (1 given) ``` This is my post ...
Take a look at the relevant part in the source code for Flask-Admin [here](https://github.com/mrjoes/flask-admin/blob/master/flask_admin/contrib/sqlamodel/view.py#L763). The model is created without passing any arguments: ``` model = self.model() ``` So you should support a constructor that takes no arguments as...
Importing variables from another file (python)
17,255,737
39
2013-06-22T22:04:40Z
17,255,749
21
2013-06-22T22:06:06Z
[ "python", "file", "variables", "import" ]
How can I import variables from one file to another? example: file1 has the variables **x1** and **x2** how to pass them to file2 ? How can I import **all** of the variables from one to another?
Import `file1` inside `file2`: To import all variables from file1 without flooding file2's namespace, use: ``` import file1 #now use file1.x1, file2.x2, ... to access those variables ``` To import all variables from file1 to file2's namespace( not recommended): ``` from file1 import * #now use x1, x2.. ``` From t...
Importing variables from another file (python)
17,255,737
39
2013-06-22T22:04:40Z
17,255,770
46
2013-06-22T22:09:52Z
[ "python", "file", "variables", "import" ]
How can I import variables from one file to another? example: file1 has the variables **x1** and **x2** how to pass them to file2 ? How can I import **all** of the variables from one to another?
``` from file1 import * ``` will import all objects and methods in file1
Importing variables from another file (python)
17,255,737
39
2013-06-22T22:04:40Z
26,891,192
7
2014-11-12T15:56:47Z
[ "python", "file", "variables", "import" ]
How can I import variables from one file to another? example: file1 has the variables **x1** and **x2** how to pass them to file2 ? How can I import **all** of the variables from one to another?
Best to import **x1** and **x2** explicitly: ``` from file1 import x1, x2 ``` This allows you to avoid unnecessary namespace conflicts with variables and functions from `file1` while working in `file2`. But if you really want, you can import **all** the variables: ``` from file1 import * ```
AssertionError: View function mapping is overwriting an existing endpoint function: main
17,256,602
10
2013-06-23T00:21:28Z
17,256,830
17
2013-06-23T01:10:32Z
[ "python", "flask" ]
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
Your view names need to be unique even if they are pointing to the same view method. ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods = ['GET']) app.add_url_rule('/<page>/', view_func=Main.as_view('page'), methods = ['GET']) ```
Include intermediary (through model) in responses in Django Rest Framework
17,256,724
47
2013-06-23T00:47:09Z
17,263,583
58
2013-06-23T17:53:15Z
[ "python", "django", "django-rest-framework" ]
I have a question about dealing with m2m / through models and their presentation in django rest framework. Let's take a classic example: models.py: ``` from django.db import models class Member(models.Model): name = models.CharField(max_length = 20) groups = models.ManyToManyField('Group', through = 'Members...
How about..... On your MemberSerializer, define a field on it like: ``` groups = MembershipSerializer(source='membership_set', many=True) ``` and then on your membership serializer you can create this: ``` class MembershipSerializer(serializers.HyperlinkedModelSerializer): id = serializers.Field(source='group....
Django unique, null and blank CharField giving 'already exists' error on Admin page
17,257,031
3
2013-06-23T01:52:24Z
21,934,494
9
2014-02-21T12:26:25Z
[ "python", "django", "django-admin", "django-models" ]
I've been getting the most weird error ever. I have a Person model ``` class Person(models.Model): user = models.OneToOneField(User, primary_key=True) facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True) twitter_id = models.CharField(max_length=225, unique=True, null=True, bla...
This is an old one but I had a similar issue just now and though I would provide an alternative solution. I am in a situation where I need to be able to have a CharField with null=True, blank=True and unique=True. If I submit an empty string in the admin panel it will not submit because the blank string is not unique....
Running Jar files from Python
17,257,694
6
2013-06-23T04:19:43Z
17,257,736
7
2013-06-23T04:30:55Z
[ "java", "python" ]
I want to make a program that can execute jar files and print whatever the jar file is doing in my python program but without using the windows command line, I have searched all over the web but nothing is coming up with how to do this. My program is a Minecraft server wrapper and I want it to run the `server.jar` fil...
First you have to execute the program. A handy function for doing so: ``` def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return iter(p.stdout.readline, b'') ``` It will return an iterable with all the lines of...
Python os.rename and os.walk together
17,257,878
2
2013-06-23T05:07:38Z
17,257,945
7
2013-06-23T05:22:45Z
[ "python", "filenames", "os.walk" ]
I just wrote a python script to get rid of some annoying suffixes in filenames, here's my code: ``` import os for root, dirs, files in os.walk("path"): for filename in files: if filename.endswith("[AnnoyingTag].mov"): os.rename(filename, filename[:-18]+'.mov') ``` but I got the error in t...
The preferred way to join paths is to use `os.path.join`, change this line: ``` os.rename(filename, filename[:-18]+'.mov') ``` Replace it with this: ``` os.rename(os.path.join(root, filename), os.path.join(root, filename[:-18]+'.mov')) ```
How do I make a pop up in Tkinter when a button is clicked? Python
17,261,028
3
2013-06-23T13:07:43Z
17,261,203
8
2013-06-23T13:28:47Z
[ "python", "popup", "tkinter" ]
How do I make a pop-up in Tkinter when a button is clicked? When the 'About' button is clicked, I want a pop up with the disclaimer + about text. I have tried to set up a def method but it must be very wrong because it's not working as I would like. Any help would be very much appreciated. Thank you ``` import sys f...
If you want to display the text on a new window, then create a Toplevel widget and use it as the parent of the labels for the about text and the disclaimer. By the way, Tkinter variables are not necessary if you have static text, so in this case you can simply get rid of them and replace them with multiline strings: ...
Execute .sql schema in psycopg2 in Python
17,261,061
6
2013-06-23T13:11:30Z
17,261,656
25
2013-06-23T14:20:28Z
[ "python", "postgresql", "schema", "psycopg2" ]
I have a PostgreSQL schema stored in .sql file. It looks something like: ``` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, facebook_id TEXT NOT NULL, name TEXT NOT NULL, access_token TEXT, created INTEGER NOT NULL ); ``` How shall I run this schema after connecting to the database? M...
You can just use `execute`: ``` with self.connection as cursor: cursor.execute(open("schema.sql", "r").read()) ``` though you may want to [set psycopg2 to `autocommit` mode first](http://initd.org/psycopg/docs/usage.html) so you can use the script's own transaction management. It'd be nice if psycopg2 offered a ...
How to read one single line of csv data in Python?
17,262,256
11
2013-06-23T15:25:30Z
17,262,302
29
2013-06-23T15:29:39Z
[ "python", "file", "csv", "iterator", "next" ]
There is a lot of examples of reading csv data using python, like this one: ``` import csv with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) ``` I only want to read one line of data and enter it into various variables. How do I do that? I've looked everywhere for a w...
To read only the first row of the csv file use [`next()`](https://docs.python.org/3/library/functions.html#next) on the reader object. ``` with open('some.csv', newline='') as f: reader = csv.reader(f) row1 = next(reader) # gets the first line # now do something here # if first row is the header, then you ca...
Error while using Scrapy : ['scrapy.telnet.TelnetConsole': No module named conch twisted]
17,263,509
5
2013-06-23T17:45:06Z
17,264,705
8
2013-06-23T19:54:29Z
[ "python", "scrapy", "twisted" ]
In Ubuntu 13.04, I have installed Scrapy for python-2.7, from the tarball. Executing a crawl command results in the below error: > ImportError: Error loading object 'scrapy.telnet.TelnetConsole': No module named conch I've also tried installing twisted conch using easy\_install and using the tarball. I have also remo...
On Ubuntu, you should avoid using `easy_install` wherever you can. Instead, you should be using `apt-get`, `aptitude`, "Ubuntu Software Center", or another of the distribution-provided tools. For example, this single command is all you need to install scrapy - along with every one of its dependencies that is not alrea...
what does 'if x.strip( )' mean?
17,264,226
4
2013-06-23T19:02:26Z
17,264,247
8
2013-06-23T19:04:43Z
[ "python", "if-statement", "strip" ]
So I was having problems with a code before because I was getting an empty line when I iterated through the foodList. Someone suggested using the 'if x.strip():' method as seen below. ``` for x in split: if x.strip(): foodList = foodList + [x.split(",")] ``` It works fine but I would just like to know what it ...
In Python, "empty" objects --- empty list, empty dict, and, as in this case, empty string --- are considered false in a boolean context (like `if`). Any string that is not empty will be considered true. `strip` returns the string after stripping whitespace. If the string contains only whitespace, then `strip()` will st...
Better Function Composition in Python
17,264,406
9
2013-06-23T19:22:36Z
17,264,493
8
2013-06-23T19:31:36Z
[ "python", "clojure", "functional-programming", "function-composition" ]
I work in Python. Recently, I discovered a wonderful little package called [fn](https://github.com/kachayev/fn.py). I've been using it for function composition. For example, instead of: ``` baz(bar(foo(x)))) ``` with fn, you can write: ``` (F() >> foo >> bar >> baz)(x) . ``` When I saw this, I immediately thought ...
You can't replicate the exact syntax, but you can make something similar: ``` def f(*args): result = args[0] for func in args[1:]: result = func(result) return result ``` Seems to work: ``` >>> f('a test', reversed, sorted, ''.join) ' aestt' ```
Python Pandas Conditional Sums
17,266,129
8
2013-06-23T23:06:27Z
17,266,172
9
2013-06-23T23:13:17Z
[ "python", "pandas" ]
Using sample data: ``` df = pd.DataFrame({'key1' : ['a','a','b','b','a'], 'key2' : ['one', 'two', 'one', 'two', 'one'], 'data1' : np.random.randn(5), 'data2' : np. random.randn(5)}) ``` df ``` data1 data2 key1 key2 0 0.361601 0.375297 a one 1 ...
First groupby the key1 column: ``` In [11]: g = df.groupby('key1') ``` and then for each group take the subDataFrame where key2 equals 'one' and sum the data1 column: ``` In [12]: g.apply(lambda x: x[x['key2'] == 'one']['data1'].sum()) Out[12]: key1 a 0.093391 b 1.468194 dtype: float64 ``` To explain wh...
Trouble with basemap subplots
17,266,873
3
2013-06-24T01:19:07Z
17,267,100
9
2013-06-24T02:02:42Z
[ "python", "matplotlib" ]
I need to make a plot with n number of basemap subplots. But when I am doing this the all the values are plotted on the first subplot. My data is a set of 'n' matrixes, stored in `data_all`. ``` f, map = plt.subplots(n,sharex=True, sharey=True, figsize=(20,17)) plt.subplots_adjust(left=None, bottom=None, right=None,...
I can't test it at the moment, but basically, you just need to tell basemap which axes to use. For example: ``` import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap fig, axes = plt.subplots(nrows=4, ncols=3) for ax in axes.flat: map_ax = Basemap(ax=ax) map_ax.drawcoastlines() plt.show() `...
Python Google Maps Driving Time
17,267,807
5
2013-06-24T03:55:22Z
17,284,276
14
2013-06-24T20:14:48Z
[ "python", "google-maps", "google-maps-api-3" ]
I need to get driving time between two sets of coordinates using Python. The only wrappers for the Google Maps API I have been able to find either use Google Maps API V2 (deprecated) or do not have the functionality to provide driving time. I'm using this in a local application and do not want to be bound to using Java...
Using URL requests to the Google Distance Matrix API and a json interpreter you can do this: ``` import simplejson, urllib orig_coord = orig_lat, orig_lng dest_coord = dest_lat, dest_lng url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&language=en-EN&sensor=false...
Finding occurrences of a word in a string in python 3
17,268,958
6
2013-06-24T06:07:26Z
17,268,979
10
2013-06-24T06:09:29Z
[ "python", "string", "count", "match" ]
I'm trying to find the number of occurrences of a word in a string. ``` word = "dog" str1 = "the dogs barked" ``` I used the following to count the occurrences: ``` count = str1.count(word) ``` The issue is I want an exact match. So the count for this sentence would be 0. Is that possible?
If you're going for efficiency: ``` import re count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word), input_string)) ``` This doesn't need to create any intermediate lists (unlike `split()`) and thus will work efficiently for large `input_string` values. It also has the benefit of working correctly with punc...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
17,271,838
216
2013-06-24T09:11:21Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
You can install it through Homebrew on OS X. Why would you install Python with Homebrew? > The version of Python that ships with OS X is great for learning but > it’s not good for development. The version shipped with OS X may be > out of date from the official current Python release, which is > considered the stabl...
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
18,947,390
1,619
2013-09-22T18:33:41Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
All you need to do is ``` sudo easy_install pip ```
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
19,128,120
9
2013-10-02T00:22:19Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
``` $ sudo port install py27-pip ``` Then update your PATH to include py27-pip bin directory (you can add this in ~/.bash\_profile PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH pip will be available in new terminal window.
Installing pip on Mac OS X
17,271,319
873
2013-06-24T08:44:30Z
19,607,760
17
2013-10-26T14:16:55Z
[ "python", "osx", "pip" ]
I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution. Can somebody help me install it?
You should install Brew first: ``` ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ``` Then brew install Python ``` brew install python ``` Then `pip` will work