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 |
|---|---|---|---|---|---|---|---|---|---|
Check if a program exists from a python script | 11,210,104 | 14 | 2012-06-26T14:54:33Z | 11,210,185 | 21 | 2012-06-26T14:59:03Z | [
"python"
] | How do I check if a program exists from a python script?
Let's say you want to check if `wget` or `curl` are available. We'll assume that they should be in path.
It would be the best to see a multiplatform solution but for the moment, Linux is enough.
Hints:
* running the command and checking for return code is not... | The easiest way is to try to run the program with the desired parameters, and handle the exception if it doesn't exist:
```
try:
subprocess.call(["wget", "your", "parameters", "here"])
except OSError as e:
if e.errno == os.errno.ENOENT:
# handle file not found error.
else:
# Something else ... |
Check if a program exists from a python script | 11,210,104 | 14 | 2012-06-26T14:54:33Z | 11,210,318 | 9 | 2012-06-26T15:05:59Z | [
"python"
] | How do I check if a program exists from a python script?
Let's say you want to check if `wget` or `curl` are available. We'll assume that they should be in path.
It would be the best to see a multiplatform solution but for the moment, Linux is enough.
Hints:
* running the command and checking for return code is not... | You could use a subprocess call to the binary needed with :
* "which" : \*nix
* "where" : Win 2003 and later (Xp has an addon)
to get the executable path (supposing it is in the environment path).
```
import os
import platform
import subprocess
cmd = "where" if platform.system() == "Windows" else "which"
try:
... |
Why does zip() drop the values of my generator? | 11,210,300 | 10 | 2012-06-26T15:04:55Z | 11,210,301 | 17 | 2012-06-26T15:04:56Z | [
"python"
] | I was writing an answer to [this question](http://stackoverflow.com/questions/11205037/detect-period-of-unknown-source) when noticed that my simple implementation didn't produce correct results. While hunting down the bug, I noticed the following:
```
In [1]: import itertools
In [2]: gen = itertools.cycle((0,1,2))
In... | This happens because `zip` evaluates iterators [from left to right](http://docs.python.org/library/functions.html#zip), meaning that, after three steps, it calls `next()` on `gen` and only then on `iter(range(3))` (or something like that) and encounters a `StopIteration`. To get around this, use the shorter (finite) it... |
Why does zip() drop the values of my generator? | 11,210,300 | 10 | 2012-06-26T15:04:55Z | 11,211,176 | 7 | 2012-06-26T15:51:23Z | [
"python"
] | I was writing an answer to [this question](http://stackoverflow.com/questions/11205037/detect-period-of-unknown-source) when noticed that my simple implementation didn't produce correct results. While hunting down the bug, I noticed the following:
```
In [1]: import itertools
In [2]: gen = itertools.cycle((0,1,2))
In... | [Your self-answer](http://stackoverflow.com/a/11210301/577088) is exactly right, and presents a very good solution -- *if* one of the arguments to `zip` is always shorter than the other. However, in situations where you don't know which will be shorter, you might find `islice` useful. `islice` also provides an easy wor... |
Importing from custom package fails in Python | 11,211,270 | 3 | 2012-06-26T15:56:09Z | 11,211,312 | 7 | 2012-06-26T15:57:42Z | [
"python"
] | So I have a `main.py file` inside `/home/richard/projects/hello-python` directory:
```
import sys
sys.path.append('/home/richard/projects/hello-python')
from Encode import Ffmpeg
x = Ffmpeg()
x.encode()
```
I have then created a package in the `/home/richard/projects/hello-python/Encode` directory:
```... | ```
from Encode.Ffmpeg import Ffmpeg
``` |
Cannot seem to use import time and import datetime in same script in Python | 11,211,650 | 5 | 2012-06-26T16:18:32Z | 11,211,716 | 8 | 2012-06-26T16:22:03Z | [
"python",
"datetime",
"time",
"sleep"
] | I'm using Python 2.7 on Windows and I am writing a script that uses both time and datetime modules. I've done this before, but python seems to be touchy about having both modules loaded and the methods I've used before don't seem to be working. Here are the different syntax I've used and the errors I am currently getti... | Don't use `from ... import *` â this is a convenience syntax for interactive use, and leads to confusion in scripts.
Here' a version that should work:
```
import time
import datetime
...
checktime = datetime.datetime.today() - datetime.timedelta(days=int(2))
checktime = checktime.timetuple()
...
filetimesecs = os.p... |
How to add Search_fields in Django | 11,212,150 | 2 | 2012-06-26T16:47:28Z | 11,212,243 | 10 | 2012-06-26T16:53:48Z | [
"python",
"django",
"django-admin"
] | I tried to add search fields in Django using python. Followings are the codes that I have used.
```
# admin.py file
from django.db import models
from blog.models import Blog
from django.contrib import admin
admin.site.register(Blog)
class Blog(models.Model):
title = models.CharField(max_length=60)
body = mod... | The search fields should be a list, not a tuple.
```
class BlogAdmin(admin.ModelAdmin):
. . .
search_fields = ['title','body']
. . .
```
Then make sure that you associate this admin object with the model.
```
admin.site.register(Blog, BlogAdmin)
```
**EDIT:**
It's hard to tell from above, but you shoul... |
Single line of code to check for a key in a 2D nested inner dictionary | 11,212,588 | 8 | 2012-06-26T17:14:40Z | 11,212,630 | 16 | 2012-06-26T17:17:05Z | [
"python"
] | Is there a single line method to check whether a Python 2d dict has an inner key/value?
Right now i do somethng like this:
```
if d.has_key(k1):
if d[k1].has_key(k2):
# do something
```
Is there a better way to do this?
Thanks | ```
if k2 in d.get(k1, {}):
# do something
```
The above fragment is nice if you don't care about whether k1 actually exists or not and merely want to know whether k2 exists inside of it if it does exist. As you can see from my code snippet, I prefer the `in` operator, but you could just as easily say
```
if d.ge... |
Single line of code to check for a key in a 2D nested inner dictionary | 11,212,588 | 8 | 2012-06-26T17:14:40Z | 11,212,644 | 10 | 2012-06-26T17:17:36Z | [
"python"
] | Is there a single line method to check whether a Python 2d dict has an inner key/value?
Right now i do somethng like this:
```
if d.has_key(k1):
if d[k1].has_key(k2):
# do something
```
Is there a better way to do this?
Thanks | You can use `in`:
```
if k1 in d and k2 in d[k1]:
```
The `has_key` method is deprecated and is removed in Python 3.x.
Related:
* ['has\_key()' or 'in'?](http://stackoverflow.com/questions/1323410/has-key-or-in) |
Can't get through a form with scrapy | 11,213,467 | 4 | 2012-06-26T18:13:02Z | 11,219,623 | 10 | 2012-06-27T04:53:32Z | [
"python",
"forms",
"web-crawler",
"scrapy"
] | I'm new with using scrapy and i'm trying to get some info from a real estate website.
The site has a home page with a search form (method GET).
I'm trying to go to the results page in my start\_requests (recherche.php), and setting all the get parameters i see in the address bar in the formdata parameter.
I also set up... | I would use [`FormRequest.from_response()`](http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.FormRequest.from_response) which does all the job for you, as you could still miss some fields:
```
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http im... |
Unbind object from session | 11,213,665 | 9 | 2012-06-26T18:24:33Z | 11,213,780 | 12 | 2012-06-26T18:31:22Z | [
"python",
"sqlalchemy"
] | Is it possible to unbind an object from an SQLAlchemy session?
I used to `deepcopy` it, but as this [seems not to be possible](http://stackoverflow.com/q/11155106/145013) when using association proxies I'm searching for another solution to remove the object from a session to add it to another one. | Expunge removes an object from the Session, sending persistent instances to the detached state, and pending instances to the transient state:
```
session.expunge(obj1)
```
UPDATE: A detached object can be attached to the same or another session by using
```
session2.add(obj1)
```
or merged
```
session2.merge(obj1)... |
What is the simplest way to programatically start a crawler in Scrapy >= 0.14 | 11,213,835 | 9 | 2012-06-26T18:34:24Z | 18,724,817 | 7 | 2013-09-10T16:57:07Z | [
"python",
"web-scraping",
"scrapy"
] | I want to start a crawler in Scrapy from a Python module. I want to essentially mimic the essence of `$ scrapy crawl my_crawler -a some_arg=value -L DEBUG`
I have the following things in place:
* a settings.py file for the project
* items and pipelines
* a crawler class which extends BaseSpider and requires arguments... | ```
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy.settings import Settings
from scrapy import log, signals
from testspiders.spiders.followall import FollowAllSpider
spider = FollowAllSpider(domain='scrapinghub.com')
crawler = Crawler(Settings())
crawler.signals.connect(reactor.sto... |
Finding double-spaces in a string - Python | 11,214,074 | 4 | 2012-06-26T18:51:05Z | 11,214,112 | 9 | 2012-06-26T18:53:36Z | [
"python",
"string",
"find",
"double"
] | Can anyone find a more Python'ic, more beautiful solution?
Iâm looping through some text lines in a file, to check if they meet certain criteria.
For some reason it was decided that separators internally in the line is â â, i.e. double space.
How do I check a text string to verify that all separators are exactl... | ```
def is_doublespace_separated(input_string):
return ' '.join(input_string.split()) == input_string.strip()
```
This works because `string.split` will split your string on any whitespace. and `string.join` joins the list with the separator `string`. In this case, we use the separator `' '` (two spaces) to re-jo... |
Closing files in openpyxl | 11,214,908 | 3 | 2012-06-26T19:49:23Z | 11,215,839 | 7 | 2012-06-26T20:59:32Z | [
"python",
"file",
"openpyxl"
] | Neither of these process, as would be expected reading the documentation:
```
worksheet.close()
workbook.close()
```
Is there a way to close files once done in openpyxl? Or is it handled automatically when the program quits? I dont want to leave spreadsheets left hanging in memory. | well you can take a look at the source code, Im currently using 1.5.5 as such
```
def load_workbook(filename, use_iterators=False):
if isinstance(filename, file):
# fileobject must have been opened with 'rb' flag
# it is required by zipfile
if 'b' not in filename.mode:
r... |
Python Dictionaries how to keep them in order | 11,215,061 | 3 | 2012-06-26T19:59:49Z | 11,215,098 | 8 | 2012-06-26T20:02:00Z | [
"python",
"list",
"dictionary"
] | I'm thinking of dictionaries as an associative array, so when I typed
```
dict1 = {'first' : 1, 'second' : 2}
```
I was hoping when I called it it would be in the order that it was written, but it wasn't. It was 'second' before 'first'. Looked it up and found that dictionaries are unordered. So that makes sense, but ... | ```
from collections import OrderedDict
OrderedDict([("first", 1), ("second", 2)])
```
That works in Python >= 2.7, IIRC. For earlier versions, there are replacements available on the internet, but keeping the keys around in a separate is probably the simplest workaround. |
ImportError: No module named OpenGL.GL | 11,215,362 | 12 | 2012-06-26T20:23:21Z | 11,215,478 | 16 | 2012-06-26T20:34:01Z | [
"python",
"opengl"
] | I'm trying to run NeHe's tutorial [here](http://nehe.gamedev.net/tutorial/adding_colour/13003/) using Python 2.7.3, but It's throwing the error `ImportError: No module named OpenGL.GL`
So how do I fix that? This is the code:
```
from OpenGL.GL import *
``` | Do you have PyOpenGL installed correctly? If you are having n00bie issues getting new modules set up correctly, I recommend installing [setuptools](http://pypi.python.org/pypi/setuptools/). Once you have setuptools installed, you will find a program in your python27/Scripts directory called "easy\_install" that you can... |
Python equivalent of Java's compareTo() | 11,215,851 | 5 | 2012-06-26T21:00:59Z | 11,215,917 | 9 | 2012-06-26T21:05:19Z | [
"python",
"oop",
"class",
"object"
] | I'm doing a project in Python (3.2) for which I need to compare user defined objects. I'm used to OOP in Java, where one would define a `compareTo()` method in the class that specifies the natural ordering of that class, as in the example below:
```
public class Foo {
int a, b;
public Foo(int aa, int bb) {
... | You can implement the special methods `__lt__`, `__gt__` etc. to implement the default operators for custom types. See more about them in the [language reference](http://docs.python.org/py3k/reference/datamodel.html#object.__lt__).
For example:
```
class Foo:
def __init__ (self, a, b):
self.a = a
... |
Why is SQLite faster than Redis in this simple benchmark? | 11,216,647 | 11 | 2012-06-26T22:07:41Z | 11,216,700 | 22 | 2012-06-26T22:14:10Z | [
"python",
"sql",
"sqlite3",
"redis"
] | I have done simple performance test on my local machine, this is python script:
```
import redis
import sqlite3
import time
data = {}
N = 100000
for i in xrange(N):
key = "key-"+str(i)
value = "value-"+str(i)
data[key] = value
r = redis.Redis("localhost", db=1)
s = sqlite3.connect("testDB")
cs = s.curso... | from the [redis documentation](http://redis.io/topics/benchmarks)
> Redis is a server: all commands involve network or IPC roundtrips. It is meaningless to compare it to embedded data stores such as SQLite, Berkeley DB, Tokyo/Kyoto Cabinet, etc ... because the cost of most operations is precisely dominated by network/... |
Why is SQLite faster than Redis in this simple benchmark? | 11,216,647 | 11 | 2012-06-26T22:07:41Z | 17,350,609 | 7 | 2013-06-27T18:27:34Z | [
"python",
"sql",
"sqlite3",
"redis"
] | I have done simple performance test on my local machine, this is python script:
```
import redis
import sqlite3
import time
data = {}
N = 100000
for i in xrange(N):
key = "key-"+str(i)
value = "value-"+str(i)
data[key] = value
r = redis.Redis("localhost", db=1)
s = sqlite3.connect("testDB")
cs = s.curso... | Just noticed that you did not pipeline the commit for redis. Using piplines the time reduces:
[---Testing SQLITE---]
[Total time of sql: 0.669369935989]
[---Testing REDIS---]
[Total time of redis: 2.39369487762] |
Why is SQLite faster than Redis in this simple benchmark? | 11,216,647 | 11 | 2012-06-26T22:07:41Z | 18,506,803 | 14 | 2013-08-29T09:16:31Z | [
"python",
"sql",
"sqlite3",
"redis"
] | I have done simple performance test on my local machine, this is python script:
```
import redis
import sqlite3
import time
data = {}
N = 100000
for i in xrange(N):
key = "key-"+str(i)
value = "value-"+str(i)
data[key] = value
r = redis.Redis("localhost", db=1)
s = sqlite3.connect("testDB")
cs = s.curso... | The current answers provide insight as to why Redis loses this particular benchmark, i.e. network overhead generated by every command executed against the server, however no attempt has been made to refactor the benchmark code to accelerate Redis performance.
The problem with your code lies here:
```
for key in data:... |
Python Strange Behavior with List & Append | 11,216,783 | 3 | 2012-06-26T22:24:18Z | 11,216,868 | 8 | 2012-06-26T22:32:20Z | [
"python",
"list",
"append"
] | The following code is an issue I encountered and am looking for an explanation. The behavior of the code different than what I expected. Below the code will be my expected output, and the actual output. One last thing to note, is that I understand this code may be 'strange', and that using range(1) is a bit odd to say ... | Compare this to your code
```
class User():
def setup(self):
self.listA = [] # instance variable
self.listB = [] # instance variable
for i in range(1):
self.listA.append('a')
self.listB.append('b')
```
Note that it's... |
Python 2.7 Combine abc.abstractmethod and classmethod | 11,217,878 | 20 | 2012-06-27T00:43:39Z | 11,218,474 | 17 | 2012-06-27T02:12:24Z | [
"python",
"google-app-engine",
"python-2.7"
] | How do I create a decorator for an abstract class method in Python 2.7?
Yes, this is similar to [this question](http://stackoverflow.com/questions/4474395/staticmethod-and-abc-abstractmethod-will-it-blend), except I would like to combine `abc.abstractmethod` and `classmethod`, instead of `staticmethod`. Also, it looks... | Here's a working example derived from the source code in Python 3.3's *abc* module:
```
from abc import ABCMeta
class abstractclassmethod(classmethod):
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
super(abstractclassmethod, self).__init__(cal... |
Python 2.7 Combine abc.abstractmethod and classmethod | 11,217,878 | 20 | 2012-06-27T00:43:39Z | 24,045,308 | 7 | 2014-06-04T18:50:04Z | [
"python",
"google-app-engine",
"python-2.7"
] | How do I create a decorator for an abstract class method in Python 2.7?
Yes, this is similar to [this question](http://stackoverflow.com/questions/4474395/staticmethod-and-abc-abstractmethod-will-it-blend), except I would like to combine `abc.abstractmethod` and `classmethod`, instead of `staticmethod`. Also, it looks... | Another possible workaround:
```
class A:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def some_classmethod(cls):
"""IMPORTANT: this is class method, override it with @classmethod!"""
pass
class B(A):
@classmethod
def some_classmethod(cls):
print cls
```
Now, one still... |
How to extract year, month, day, hour and minutes from a DateTimeField? | 11,218,305 | 5 | 2012-06-27T01:45:20Z | 11,219,705 | 7 | 2012-06-27T05:04:07Z | [
"python",
"django"
] | I would like to know how to extract the year, month, day, hour and minutes from a DateTimeField?
The datimefield I want to extract the info is called 'redemption\_date' and the code for the model is this:
```
from django.db import models
from datetime import datetime, timedelta
class Code(models.Model):
id... | [From the datetime documentation](http://docs.python.org/library/datetime.html) :
```
[...]
class datetime.datetime
A combination of a date and a time. Attributes: year, month, day, hour,
minute, second, microsecond, and tzinfo.
[...]
```
So you can extract your wanted information by directly accessing the `redempti... |
How can I use pickle to save a dict? | 11,218,477 | 59 | 2012-06-27T02:12:44Z | 11,218,504 | 143 | 2012-06-27T02:16:11Z | [
"python",
"dictionary",
"pickle"
] | I have looked through the information that the [Python docs](https://docs.python.org/3/library/pickle.html) give, but I'm still a little confused. Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it? | Try this:
```
import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle)
with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)
print a == b
``` |
How can I use pickle to save a dict? | 11,218,477 | 59 | 2012-06-27T02:12:44Z | 22,691,344 | 7 | 2014-03-27T14:54:48Z | [
"python",
"dictionary",
"pickle"
] | I have looked through the information that the [Python docs](https://docs.python.org/3/library/pickle.html) give, but I'm still a little confused. Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it? | ```
# Save a dictionary into a pickle file.
import pickle
favorite_color = {"lion": "yellow", "kitty": "red"} # create a dictionary
pickle.dump(favorite_color, open("save.p", "wb")) # save it into a file named save.p
# -------------------------------------------------------------
# Load the dictionary back from the... |
How can I use pickle to save a dict? | 11,218,477 | 59 | 2012-06-27T02:12:44Z | 33,245,595 | 12 | 2015-10-20T19:49:21Z | [
"python",
"dictionary",
"pickle"
] | I have looked through the information that the [Python docs](https://docs.python.org/3/library/pickle.html) give, but I'm still a little confused. Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it? | As Blender seems not to want to add `HIGHEST_PROTOCOL` to his answer, here is one with it:
```
import pickle
your_data = {'foo': 'bar'}
# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Load data (deserialize)
with open('fil... |
Is it possible to set some columns automatically in sqlalchemy | 11,219,887 | 2 | 2012-06-27T05:23:22Z | 11,220,928 | 8 | 2012-06-27T06:59:48Z | [
"python",
"mysql",
"sqlalchemy",
"pyramid"
] | I have a model with these 2 columns
1. created\_at: date
2. last\_updated\_at: date
Is it possible to set these values automatically whenever a insert or update happens. Or should I be calling a method inside this class to do that. | Please read the *Python-Executed Functions* section of [Column Insert/Update Defaults](http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#column-insert-update-defaults) documentation.
Your code will then look similar to the following:
```
# ...
import datetime
# ...
class MyModel(Base):
__tablename__ = "my_t... |
Python : how to append new elements in a list of list? | 11,219,949 | 6 | 2012-06-27T05:29:41Z | 11,219,967 | 12 | 2012-06-27T05:31:19Z | [
"python",
"list"
] | Here is a very simple program:
```
a = [[]]*3
print str(a)
a[0].append(1)
a[1].append(2)
a[2].append(3)
print str(a[0])
print str(a[1])
print str(a[2])
```
Here is the output I was expecting:
```
[[], [], []]
[1]
[2]
[3]
```
But instead I get this :
```
[[], [], []]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]... | You must do
```
a = [[] for i in xrange(3)]
```
not
```
a = [[]]*3
```
Now it works:
```
$ cat /tmp/3.py
a = [[] for i in xrange(3)]
print str(a)
a[0].append(1)
a[1].append(2)
a[2].append(3)
print str(a[0])
print str(a[1])
print str(a[2])
$ python /tmp/3.py
[[], [], []]
[1]
[2]
[3]
```
When you do something l... |
uWSGI Server logâ¦permission denied to read file...which file? | 11,220,355 | 7 | 2012-06-27T06:09:56Z | 13,178,861 | 8 | 2012-11-01T14:10:58Z | [
"python",
"django",
"nginx",
"uwsgi"
] | I have a server running Django/Nginx/uWSGI with uWSGI in emperor mode, and the error log for it (the vassal-level error log, not the emperor-level log) has a continual permissions error every time it spawns a new worker, like so:
> Tue Jun 26 19:34:55 2012 - Respawned uWSGI worker 2 (new pid: 9334)
>
> Error opening f... | The actual answer to this question appears to be this Ubuntu-specific bug:
<https://bugs.launchpad.net/ubuntu/+source/libjpeg-turbo/+bug/1031718>
You can work around the problem by putting the lines
```
setuid uwsgiuser
setgid uwsgiuser
```
into your upstart configuration file, and deleting the `uid` and `gid` sett... |
Why does my IDE suggest to rewrite != 0 to is not 0 | 11,220,976 | 3 | 2012-06-27T07:03:18Z | 11,221,077 | 7 | 2012-06-27T07:10:06Z | [
"python",
"pycharm"
] | My python IDE PyCharm by defaults suggests to change the following line of python:
```
if variable != 0:
```
to
```
if variable is not 0:
```
Why does it suggest this? Does it matter at all for the execution (i.e. does this behave different for any edge cases)? | It's a bug. You should not test integers by identity. Although it may work ok for small integers, it's just an implementation detail.
If you were checking `variable is False`, that would be ok. Perhaps the IDE is tripped up by the semantics |
Waiting for some time before excecuting the next segment of codes in python3.2 | 11,222,407 | 5 | 2012-06-27T08:41:06Z | 11,222,659 | 13 | 2012-06-27T08:56:28Z | [
"python",
"winapi",
"user-interface",
"python-3.x",
"pywin32"
] | I am writing a code to run a gui application(winmerge) and then send some keystrokes to it. I need to wait for some time within the program till the GUI finishes running and then send some keystrokes to it to save the report. How do i implement this? `wait()` isnt working as after invoking it i cant send keys to the sa... | ```
from time import sleep
print "hi,"
sleep(5)
print "this is printed 5 seconds later"
``` |
Python variable reference assignment | 11,222,440 | 23 | 2012-06-27T08:43:03Z | 11,222,482 | 8 | 2012-06-27T08:45:27Z | [
"python",
"reference"
] | In the code
```
y = 7
x = y
x = 8
```
Now, y will be 7 and x will be 8. But actually I wanna change y. Can I assign the reference of y and do that ?
For example, in C++ the same thing can be achieved as,
```
int y = 8;
int &x = y;
x = 9;
```
Now both y & x will be 9 | No, Python doesn't have this feature.
If you had a list (or any other mutable object) you could do what you want by mutating the object that both x and y are bound to:
```
>>> x = [7]
>>> y = x
>>> y[0] = 8
>>> print x
[8]
```
See it working online: [ideone](http://ideone.com/YmzHL) |
Python variable reference assignment | 11,222,440 | 23 | 2012-06-27T08:43:03Z | 11,222,835 | 30 | 2012-06-27T09:07:00Z | [
"python",
"reference"
] | In the code
```
y = 7
x = y
x = 8
```
Now, y will be 7 and x will be 8. But actually I wanna change y. Can I assign the reference of y and do that ?
For example, in C++ the same thing can be achieved as,
```
int y = 8;
int &x = y;
x = 9;
```
Now both y & x will be 9 | No, you cannot. As other answer point out, you can (ab?)use aliasing of mutable objects to achieve a similar effect. However, that's not the same thing as C++ references, and I want to explain what actually happens to avoid any misconceptions.
You see, in C++ (and other languages), a variable (and object fields, and e... |
AttributeError: 'list' object has no attribute 'click' - Selenium Webdriver | 11,223,011 | 4 | 2012-06-27T09:19:16Z | 11,223,369 | 9 | 2012-06-27T09:42:24Z | [
"python",
"selenium",
"webdriver"
] | I am trying to use click command in Selenium webdriver using python. But I am getting the below error. Can some one help me?
```
Traceback (most recent call last):
File "C:\Users\vikram\workspace\LDC\test.py", line 13, in <module>
driver.find_elements_by_link_text("MISCQA Misc Tests").click()
AttributeError: 'list' ob... | Thanks for helping out. I found the answer for myself. Idea given by "Dan Niero"
The problem is, I am using `driver.find_element[s]` instead of `driver.find_element`. So one s makes difference. In fact I am following the eclipse :(. Obviously `driver.find_elements_by_link_text` returns list so If i send click event it... |
Django: WSGIRequest' object has no attribute 'user' on some pages? | 11,223,597 | 18 | 2012-06-27T09:56:30Z | 11,223,949 | 13 | 2012-06-27T10:17:35Z | [
"python",
"django",
"wsgi",
"django-middleware"
] | I want to set a cookie if user is logged in or not.
**My Middleware:**
```
class UserStatus(object):
def process_response(self,request,response):
user_status = 1 if request.user.is_authenticated() else 0
max_age = (20)*52*7*24*60*60 # 20 years (After expiry, cookie gets deleted)
response.s... | According to the FineManual:
> During the response phases (process\_response() and process\_exception() middleware), the classes are applied in reverse order, from the bottom up
So I'd say you'd better add your middleware *before* the auth and session middlewares (assuming it only processes the response).
This being... |
Django: WSGIRequest' object has no attribute 'user' on some pages? | 11,223,597 | 18 | 2012-06-27T09:56:30Z | 11,223,978 | 8 | 2012-06-27T10:18:53Z | [
"python",
"django",
"wsgi",
"django-middleware"
] | I want to set a cookie if user is logged in or not.
**My Middleware:**
```
class UserStatus(object):
def process_response(self,request,response):
user_status = 1 if request.user.is_authenticated() else 0
max_age = (20)*52*7*24*60*60 # 20 years (After expiry, cookie gets deleted)
response.s... | do you have active this middleware?:
```
'django.contrib.auth.middleware.AuthenticationMiddleware'
```
And this middleware run before your middleware? |
Django: WSGIRequest' object has no attribute 'user' on some pages? | 11,223,597 | 18 | 2012-06-27T09:56:30Z | 14,793,959 | 19 | 2013-02-10T02:11:53Z | [
"python",
"django",
"wsgi",
"django-middleware"
] | I want to set a cookie if user is logged in or not.
**My Middleware:**
```
class UserStatus(object):
def process_response(self,request,response):
user_status = 1 if request.user.is_authenticated() else 0
max_age = (20)*52*7*24*60*60 # 20 years (After expiry, cookie gets deleted)
response.s... | Ran into the same issue recently, and found that it happened when a url is being accessed without the trailing slash, and the APPEND\_SLASH setting is set to true:
---
**Django processes initial request**
* CommonMiddleware.process\_request
+ Redirects to newurl, which has the trailing slash
* process\_response is... |
Django: WSGIRequest' object has no attribute 'user' on some pages? | 11,223,597 | 18 | 2012-06-27T09:56:30Z | 21,100,938 | 9 | 2014-01-13T20:42:13Z | [
"python",
"django",
"wsgi",
"django-middleware"
] | I want to set a cookie if user is logged in or not.
**My Middleware:**
```
class UserStatus(object):
def process_response(self,request,response):
user_status = 1 if request.user.is_authenticated() else 0
max_age = (20)*52*7*24*60*60 # 20 years (After expiry, cookie gets deleted)
response.s... | So it has to do with `APPEND_SLASH` being applied with via a redirect by Django Common Middleware, preventing the `process_request()` in `AuthenticationMiddleware` (which adds the `user` attribute) from being run but your `process_response` still being run.
Here's how Django Process Middleware ACTUALLY Works (from `dj... |
SQLite and Python. Values write without errors, but not in database once the program is terminated | 11,225,644 | 3 | 2012-06-27T11:56:39Z | 11,225,701 | 9 | 2012-06-27T12:00:25Z | [
"python",
"sqlite"
] | I experience a problem with Python and SQLite in a script which downloads data from the Internet and puts them into a SQLite database. In the beginning of the execution I open the connection and assign the cursor. This cursor is then sent to the methods which downloads the data and writes them to the database. So far I... | From what I see you do not call commit() at the end. This might not write any data into the database though.
From SQLITE3 Docs:
> Connection.commit()
>
> This method commits the current transaction. If
> you donât call this method, anything you did since the last call to
> commit() is not visible from other database... |
Python: Ignore xmlns in elementtree.ElementTree | 11,226,247 | 14 | 2012-06-27T12:30:26Z | 11,227,304 | 8 | 2012-06-27T13:25:56Z | [
"python",
"xml",
"xml-namespaces",
"elementtree"
] | Is there a way to ignore the XML namespace in tage names in `elementtree.ElementTree`?
I try to print all `technicalContact` tags:
```
for item in root.getiterator(tag='{http://www.example.com}technicalContact'):
print item.tag, item.text
```
And I get something like:
```
{http://www.example.com}technicalCo... | You can define a generator to recursively search through your element tree in order to find tags which end with the appropriate tag name. For example, something like this:
```
def get_element_by_tag(element, tag):
if element.tag.endswith(tag):
yield element
for child in element:
for g in get_el... |
python -c and `while` | 11,226,252 | 5 | 2012-06-27T12:30:45Z | 11,226,397 | 7 | 2012-06-27T12:37:32Z | [
"python",
"windows",
"linux",
"command-line"
] | Is there a way to loop in `while` if you start the script with `python -c`? This doesn't seem to be related to platform or python version...
**Linux**
```
[mpenning@Hotcoffee ~]$ python -c "import os;while (True): os.system('ls')"
File "<string>", line 1
import os;while (True): os.system('ls')
... | ```
python -c $'import subprocess\nwhile True: subprocess.call(["ls"])'
```
would work (note the `$'...'` and the `\n`).
But it could be that it only works under [bash](/questions/tagged/bash "show questions tagged 'bash'") - I am not sure... |
drop trailing zeros from decimal | 11,227,620 | 15 | 2012-06-27T13:42:09Z | 11,227,743 | 51 | 2012-06-27T13:48:03Z | [
"python",
"decimal"
] | I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes a useless trailing zero (though not always) that I want to get rid of. For example...
```
from decimal import Decimal
# outputs 25.0, PROBLEM! I... | You can use the [`normalize`](http://docs.python.org/2/library/decimal.html#decimal.Decimal.normalize) method to remove extra precision.
```
>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5
```
To avoid stripping zeros to the left of the decimal point, you could do this:
``... |
drop trailing zeros from decimal | 11,227,620 | 15 | 2012-06-27T13:42:09Z | 11,227,878 | 12 | 2012-06-27T13:54:51Z | [
"python",
"decimal"
] | I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes a useless trailing zero (though not always) that I want to get rid of. For example...
```
from decimal import Decimal
# outputs 25.0, PROBLEM! I... | There's probably a better way of doing this, but you could use `.rstrip('0').rstrip('.')` to achieve the result that you want.
Using your numbers as an example:
```
>>> s = str(Decimal('2.5') * 10)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
25
>>> s = str(Decimal('2.5678') * 1000)
>>> print s.rstrip('0').... |
drop trailing zeros from decimal | 11,227,620 | 15 | 2012-06-27T13:42:09Z | 18,769,210 | 13 | 2013-09-12T16:04:16Z | [
"python",
"decimal"
] | I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes a useless trailing zero (though not always) that I want to get rid of. For example...
```
from decimal import Decimal
# outputs 25.0, PROBLEM! I... | Answer from <http://docs.python.org/2/library/decimal.html#decimal-faq>
```
>>> def remove_exponent(d):
... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5.500'))
Decimal('5.5')
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
``` |
Print a dict sorted by values | 11,228,812 | 6 | 2012-06-27T14:42:57Z | 11,229,116 | 8 | 2012-06-27T14:56:13Z | [
"python",
"sorting",
"dictionary",
"loops"
] | I'm basically trying to iterate through a dict and print out the key / values from largest value to lowest. I have been searching this site and a lot of people are using lambda but I'm not really sure how its working so I'm trying to avoid it for now.
```
dictIterator = iter(sorted(bigramDict.iteritems()))
for ngram, ... | One can take advantage of the fact that sort works on tuples by considering the first element as more important than the second etc:
```
d = { "a":4, "c":3, "b":12 }
d_view = [ (v,k) for k,v in d.iteritems() ]
d_view.sort(reverse=True) # natively sort tuples by first element
for v,k in d_view:
print "%s: %d" % (k,... |
Print a dict sorted by values | 11,228,812 | 6 | 2012-06-27T14:42:57Z | 11,229,181 | 9 | 2012-06-27T14:59:12Z | [
"python",
"sorting",
"dictionary",
"loops"
] | I'm basically trying to iterate through a dict and print out the key / values from largest value to lowest. I have been searching this site and a lot of people are using lambda but I'm not really sure how its working so I'm trying to avoid it for now.
```
dictIterator = iter(sorted(bigramDict.iteritems()))
for ngram, ... | You can use the `key` parameter of `sorted` to sort by the 2nd item:
```
>>> d = { "a":4, "c":3, "b":12 }
>>> from operator import itemgetter
>>> for k, v in sorted(d.items(), key=itemgetter(1)):
print k, v
c 3
a 4
b 12
>>>
``` |
Python - Algorithm to determine if a list is symmetric | 11,228,939 | 2 | 2012-06-27T14:48:20Z | 11,229,530 | 8 | 2012-06-27T15:15:26Z | [
"python"
] | So I'm stuck on this problem where I've been asked to write an function in Python that checks to see if an n-dimensional array (is that what they're called?) is "symmetric" or not, meaning that row 1 of the array == column 1, row 2 == column 2, row 3 == column 3, etc so on and so forth. The goal is to have a function t... | This bit of code will do it all for you:
```
def symmetric(square):
square = [tuple(row) for row in square]
return square == zip(*square)
```
In your solution you're doing too much of the work yourself. Python will compare sequences for you, so an easier method is to transpose the square so its rows become co... |
Ffprobe with print json doesn't print anything | 11,229,660 | 4 | 2012-06-27T15:21:35Z | 11,233,332 | 11 | 2012-06-27T19:07:47Z | [
"python",
"ubuntu",
"ffmpeg",
"ffprobe"
] | I am trying to get information about a movie (resolution, frame rate, bit rate, codecs, duration etc) in a human readable way. I found this commnad:
```
ffprobe -v quiet -print_format json -show_format -show_streams somefile.asf
```
In this Stack Overflow question: [Get ffmpeg information in friendly way](http://stac... | Ok, the current version of ffmpeg in Ubuntu repos is not up to date.
What I did was I added this more up to date repository:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
```
And then did:
```
sudo apt-get remove ffmpeg
sudo apt-get autoremove
sudo apt-get update
sudo apt-get install ffmpeg
```
And voila.... |
Right Click in Python using ctypes | 11,229,808 | 6 | 2012-06-27T15:29:21Z | 11,229,971 | 7 | 2012-06-27T15:36:15Z | [
"python",
"ctypes",
"right-click"
] | I am a complete beginner to Python so dont understand the lingo. I want to use python to do a simple click at a specific point. I have already managed a left click using ctypes:
```
>>> import ctypes
>>> ctypes.windll.user32.SetCursorPos(x,y), ctypes.windll.user32.mouse_event(2,0,0,0,0), ctypes.windll.user32.mouse_eve... | Here are the constants that you would use for `mouse_event`
```
MOUSE_LEFTDOWN = 0x0002 # left button down
MOUSE_LEFTUP = 0x0004 # left button up
MOUSE_RIGHTDOWN = 0x0008 # right button down
MOUSE_RIGHTUP = 0x0010 # right button up
MOUSE_MIDDLEDOWN = 0x0020 # middle button down
MOUSE_MIDDLEUP ... |
What is the meaning of the nu parameter in Scikit-Learn's SVM class? | 11,230,955 | 6 | 2012-06-27T16:30:55Z | 15,599,032 | 20 | 2013-03-24T13:27:51Z | [
"python",
"machine-learning",
"scikit-learn"
] | I am following the example shown in <http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html#example-svm-plot-oneclass-py>, where a one class SVM is used for anomaly detection.
Now, this may be a notation unique to scikit-learn, but I couldn't find an explanation of how to use the parameter nu given to the ... | ## The problem with C and the introduction of nu
The problem with the parameter C is:
1. that it can take any positive value
2. that it has no direct interpretation.
It is therefore hard to choose correctly and one has to resort to cross validation or direct experimentation to find a suitable value.
In response Sch... |
Error while executing scikit-learn K-means example | 11,232,176 | 2 | 2012-06-27T17:51:53Z | 11,232,288 | 13 | 2012-06-27T17:59:20Z | [
"python",
"scikit-learn"
] | I'm trying to run a scikit-learn K-means example from scikit-learn official site:
<http://scikit-learn.org/dev/auto_examples/cluster/plot_cluster_iris.html#example-cluster-plot-cluster-iris-py>
I got all libraries installed (e.g., scipy, numpy, pylab). However, when executing the code, I got error message like this:
... | You're looking at the docs for the bleeding edge development version of scikit-learn. The stable (0.11) version of that example is [here](http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html#example-cluster-plot-cluster-iris-py). `n_clusters` will be introduced in 0.12, in older versions use `k` ... |
Logging to two files with different settings | 11,232,230 | 10 | 2012-06-27T17:54:54Z | 11,233,293 | 22 | 2012-06-27T19:05:44Z | [
"python",
"file",
"logging",
"python-3.x"
] | I am already using a basic logging config where all messages across all modules are stored in a single file. However, I need a more complex solution now:
* Two files: the first remains the same.
* The second file should have some custom format.
I have been reading the docs for the module, bu they are very complex for... | You can do something like this:
```
import logging
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
# first file logger
logger_1 = logging.getLogger('simple_logger')
hdlr_1 = logging.FileHandler('simplefile_1.log')
hdlr_1.setFormatter(formatter)
logger_1.addHandler(hdlr_1)
# second file logger
... |
Pandas pivot warning about repeated entries on index | 11,232,275 | 21 | 2012-06-27T17:58:38Z | 13,833,239 | 11 | 2012-12-12T05:14:29Z | [
"python",
"pandas"
] | On Pandas documentation of the `pivot` method, we have:
```
Examples
--------
>>> df
foo bar baz
0 one A 1.
1 one B 2.
2 one C 3.
3 two A 4.
4 two B 5.
5 two C 6.
>>> df.pivot('foo', 'bar', 'baz')
A B C
one ... | Try this,
```
df.drop_duplicates(['foo','bar'])
df.pivot('foo','bar','baz')
``` |
Pandas pivot warning about repeated entries on index | 11,232,275 | 21 | 2012-06-27T17:58:38Z | 19,600,533 | 39 | 2013-10-25T22:45:37Z | [
"python",
"pandas"
] | On Pandas documentation of the `pivot` method, we have:
```
Examples
--------
>>> df
foo bar baz
0 one A 1.
1 one B 2.
2 one C 3.
3 two A 4.
4 two B 5.
5 two C 6.
>>> df.pivot('foo', 'bar', 'baz')
A B C
one ... | As far as I can tell with updates to pandas, you have to use pivot\_table() instead of pivot().
```
pandas.pivot_table(df,values='count',index='site_id',columns='week')
``` |
Is there a better way to find if string contains digits? | 11,232,474 | 15 | 2012-06-27T18:12:30Z | 11,232,512 | 39 | 2012-06-27T18:14:47Z | [
"python",
"string"
] | I'm working with strings that contain both digits and alphanumerics, or just digits, but not just alphas. In order to test for false matches, I need to check if the strings contain at least one digit, printing an error message if it doesn't. I have been using the following code:
```
s = '0798237 sh 523-123-asdjlh'
de... | This is one of those places where a regular expression is just the thing:
```
_digits = re.compile('\d')
def contains_digits(d):
return bool(_digits.search(d))
```
Little demo:
```
>>> _digits = re.compile('\d')
>>> def contains_digits(d):
... return bool(_digits.search(d))
...
>>> contains_digits('0798237 ... |
Is there a better way to find if string contains digits? | 11,232,474 | 15 | 2012-06-27T18:12:30Z | 11,232,523 | 12 | 2012-06-27T18:15:46Z | [
"python",
"string"
] | I'm working with strings that contain both digits and alphanumerics, or just digits, but not just alphas. In order to test for false matches, I need to check if the strings contain at least one digit, printing an error message if it doesn't. I have been using the following code:
```
s = '0798237 sh 523-123-asdjlh'
de... | Use the `any` function, passing in a sequence.
If *any* element of the sequence is true (ie is a digit, in this case), then `any` returns True, else False. <https://docs.python.org/library/functions.html#any>
```
def contains_digits(s):
return any(char.isdigit() for char in s)
```
If you're concerned about perf... |
Storing Python objects in a Python list vs. a fixed-length Numpy array | 11,232,597 | 8 | 2012-06-27T18:20:40Z | 11,233,356 | 12 | 2012-06-27T19:10:06Z | [
"python",
"performance",
"numpy",
"python-3.x",
"cpython"
] | In doing some bioinformatics work, I've been pondering the ramifications of storing object instances in a Numpy array rather than a Python list, but in all the testing I've done the performance was worse in every instance. I am using CPython. Does anyone know the reason why?
Specifically:
* What are the performance i... | Don't use object arrays in numpy for things like this.
They defeat the basic purpose of a numpy array, and while they're useful in a tiny handful of situations, they're almost always a poor choice.
Yes, accessing an individual element of a numpy array in python or iterating through a numpy array in python is slower t... |
SQLAlchemy one-to-many without the child table having a primary key | 11,232,616 | 6 | 2012-06-27T18:21:52Z | 11,262,249 | 12 | 2012-06-29T12:58:50Z | [
"python",
"database",
"orm",
"sqlalchemy",
"ddl"
] | Is it possible to create a table without a primary key in SQLAlchemy? The relationship I want to define is as follows:
```
class TPost(Base):
__tablename__ = "forum_post"
id = Column(Integer, primary_key = True)
topic_id = Column(Integer, ForeignKey("forum_topic.id"))
index = Column(Integer)
page = Column(In... | I am assuming @TokenMacGuy is right, and you really are confusing the notions of `PrimaryKey`, and a `surrogate key`. In which case the answer to your question is:
* **NO**, SA does not support tables (and therefore relations to tables) without a primary key
* and **NO**, you do not need to create a surrogate key for ... |
How do I detect a max. recursion depth exceeded exception in Python? | 11,233,100 | 6 | 2012-06-27T18:51:32Z | 11,233,160 | 7 | 2012-06-27T18:55:29Z | [
"python"
] | ```
try:
recursive_function()
except RuntimeError e:
# is this a max. recursion depth exceeded exception?
```
How do I tell when the maximum recursion depth has been reached? | You can look inside the exception itself:
```
>>> def f():
... f()
...
>>> try:
... f()
... except RuntimeError as re:
... print re.args, re.message
...
('maximum recursion depth exceeded',) maximum recursion depth exceeded
```
I don't think you can distinguish between this and something merely pretendi... |
How to clean the database, dropping all records using sqlalchemy? | 11,233,128 | 13 | 2012-06-27T18:53:22Z | 11,234,195 | 13 | 2012-06-27T20:16:03Z | [
"python",
"sqlalchemy"
] | I am using SQlAlchemy. I want to delete all the records efficiently present in database but I don't want to drop the table/database.
I tried with the following code.
```
con = engine.connect()
trans = con.begin()
con.execute(table.delete())
trans.commit()
```
It seems, it is not the very efficient one since I am it... | If you models rely on the existing DB schema (usually use `autoload=True`), you cannot avoid deleting data in each table. [`MetaData.sorted_tables`](http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#sqlalchemy.schema.MetaData.sorted_tables) comes in handy:
```
for tbl in reversed(meta.sorted_tables):
engine.e... |
Generating a list of EVEN numbers in Python | 11,233,355 | 6 | 2012-06-27T19:09:53Z | 11,233,414 | 11 | 2012-06-27T19:14:46Z | [
"python",
"numbers",
"fibonacci"
] | Basically I need help in generating even numbers from a list that I have created in Python:
```
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...]
```
I have tried a couple different methods, but every time I print, there are odd numbers mixed in with... | Use a list comprehension (see: [Searching a list of objects in Python](http://stackoverflow.com/questions/598398/searching-a-list-of-objects-in-python))
```
myList = [<your list>]
evensList = [x for x in myList if x % 2 == 0]
```
This is good because it leaves list intact, and you can work with evensList as a normal ... |
how to write simultaneous subscript and superscript for a symbol with matplotlib | 11,233,407 | 2 | 2012-06-27T19:14:06Z | 11,233,485 | 7 | 2012-06-27T19:20:39Z | [
"python",
"matplotlib"
] | I'd like to get something like that: $E^{\alpha}\_{\beta}$, where there are simutaneous subscript \beta and superscript \alpha for the symbol E.
I type in matplotlib (1.2.x with python 2.7.1) the following code:
```
ax.text(0.,0.,r'E$^{\alpha}_{\beta}$')
```
and I get an error message:
```
Subscript/superscript sequ... | Move your `E` into the TeX so that the processor knows what `alpha` and `beta` are hanging off of:
```
text(0.25, 0.5, r'$E^{\alpha}_{\beta}$', size=200)
```
produces
 |
Compress Images in Python (No Archive) | 11,233,645 | 2 | 2012-06-27T19:32:49Z | 11,233,741 | 7 | 2012-06-27T19:40:00Z | [
"python",
"image",
"compression",
"archive",
"decompression"
] | I'm writing a Python script that deals with images. Is there a module that can compress an image *without* putting it into an archive, and decompress it back? (e.g. A 1MB image is now 0.8MB after compression, then 1MB after decompression).
Can I see example code of compressing and decompressing an image in Python with... | You probably want to take a look at the [Python Image Library (PIL)](http://www.pythonware.com/products/pil/), and the [PNG](http://en.wikipedia.org/wiki/Portable_Network_Graphics) and [JPEG](http://en.wikipedia.org/wiki/JPEG) formats.
The PIL [Image.save()](http://www.pythonware.com/library/pil/handbook/image.htm#Ima... |
Access static variable from static method | 11,233,729 | 8 | 2012-06-27T19:38:48Z | 11,233,730 | 13 | 2012-06-27T19:38:48Z | [
"python",
"oop",
"static-methods",
"static-variables"
] | I want to access a static variable from a static method:
```
#!/usr/bin/env python
class Messenger:
name = "world"
@staticmethod
def get_msg(grrrr):
return "hello " + grrrr.name
print Messenger.get_msg(Messenger)
```
How to do it without passing `grrrr` to a method? Is this the true OOP?..
Anyth... | Use `@classmethod` instead of `@staticmethod`. Found it just after writing the question.
In many languages (C++, Java etc.) "static" and "class" methods are synonyms. [Not in Python.](http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python) |
What is the best way to access the last entered key in a default dict in Python? | 11,233,863 | 2 | 2012-06-27T19:49:11Z | 11,233,915 | 7 | 2012-06-27T19:53:42Z | [
"python",
"python-2.7"
] | I have a default dict of dicts whose primary key is a timestamp in the string form 'YYYYMMDD HH:MM:SS.' The keys are entered sequentially. How do I access the last entered key or the key with the latest timestamp? | Use an `OrderedDict` from the `collections` module if you simply need to access the last item entered. If, however, you need to maintain continuous sorting, you need to use a different data structure entirely, or at least an auxiliary one for the purposes of indexing.
Edit: I would add that, if accessing the final ele... |
How to extend a base Flask Jinja template from a Blueprint template? | 11,233,959 | 6 | 2012-06-27T19:56:52Z | 11,234,284 | 14 | 2012-06-27T20:23:18Z | [
"python",
"flask",
"jinja"
] | I am creating a fairly large application using Flask and Jinja. Flask recommends separating large applications into smaller units using Blueprints. If I have a base layout for my entire application/website, how can I extend this from templates within my blueprints? | You simply write name of the base template layout and Flask will find it if it exists in app's templates folder and then in blueprint's templates folder.
```
{% extends 'template_name.html' %}
```
If it exists inside a folder in templates folder then
```
{% extends 'folder_name/template_name.html' %}
```
If... |
3d numpy record array | 11,234,059 | 9 | 2012-06-27T20:04:51Z | 11,235,048 | 12 | 2012-06-27T21:26:44Z | [
"python",
"numpy"
] | Is is possible to have a 3-D record array in numpy? (Maybe this is not possible, or there is simply an easier way to do things too -- I am open to other options).
Assume I want an array that holds data for 3 variables (say temp, precip, humidity), and each variable's data is actually a 2-d array of 2 years (rows) and ... | Actually, you can do something similar to this with structured arrays, but it's generally more trouble than it's worth.
What you want is basically labeled axes.
[Pandas](http://pandas.pydata.org/) (which is built on top of numpy) provides what you want, and is a better choice if you want this type of indexing. There'... |
Parsing web page in python using Beautiful Soup | 11,234,614 | 6 | 2012-06-27T20:48:54Z | 11,235,005 | 12 | 2012-06-27T21:22:44Z | [
"python",
"beautifulsoup",
"urllib"
] | I have some troubles with getting the data from the website. The website source is here:
```
view-source:http://release24.pl/wpis/23714/%22La+mer+a+boire%22+%282011%29+FRENCH.DVDRip.XviD-AYMO
```
there's sth like this:
> ## INFORMACJE O FILMIE
>
> TytuÅ............................................: La mer à boireOc... | The secret of using BeautifulSoup is to find the hidden patterns of your HTML document. For example, your loop
```
for ul in soup.findAll('p') :
print(ul)
```
is in the right direction, but it will return all paragraphs, not only the ones you are looking for. The paragraphs you are looking for, however, have the ... |
Why does Python return negative list indexes? | 11,235,213 | 5 | 2012-06-27T21:42:08Z | 11,235,227 | 18 | 2012-06-27T21:43:02Z | [
"python"
] | If I have this list with 10 elements:
```
>>> l = [1,2,3,4,5,6,7,8,9,0]
```
Why will l[10] return an IndexError, but l[-1] returns 0?
```
>>> l[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[0]
1
>>> l[-1]
0
>>> l[-2]
9
```
What I want to do is... | In Python, negative list indices indicate items counted from the right of the list (that is, `l[-n]` is shorthand for `l[len(l)-n]`).
If you find you need negative indices to indicate an error, then you can simply check for that case and raise the exception yourself (or handle it then and there):
```
index = get_some... |
setup.py not installing data files | 11,235,820 | 6 | 2012-06-27T22:44:45Z | 16,576,850 | 9 | 2013-05-15T23:53:37Z | [
"python",
"python-2.7",
"distutils"
] | I have a Python library that, in addition to regular Python modules, has some data files that need to go in /usr/local/lib/python2.7/dist-package/mylibrary.
Unfortunately, I have been unable to convince setup.py to actually install the data files there. Note that this behaviour is under install - not sdist.
Here is a... | **UPD**:
`package_data` accepts dict in format `{'package': ['list', 'of?', 'globs*']}`, so to make it work, one should specify shell globs relative to package dir, not the file paths relative to the distribution root.
`data_files` has a different mining, and, in general one should avoid using this parameter.
With se... |
Identify duplicate values in a list in Python | 11,236,006 | 20 | 2012-06-27T23:07:35Z | 11,236,042 | 33 | 2012-06-27T23:11:21Z | [
"python",
"arrays",
"list"
] | Is it possible to get which values are duplicates in a list using python?
I have a list of items:
```
mylist = [20, 30, 25, 20]
```
I know the best way of removing the duplicates is `set(mylist)`, but is it possible to know what values are being duplicated? As you can see, in this list the duplicates are the fir... | These answers are O(n), so a little more code than using `mylist.count()` but much more efficient as `mylist` gets longer
If you just want to know the duplicates, use collections.Counter
```
from collections import Counter
mylist = [20, 30, 25, 20]
[k for k,v in Counter(mylist).items() if v>1]
```
If you need to kno... |
Identify duplicate values in a list in Python | 11,236,006 | 20 | 2012-06-27T23:07:35Z | 11,236,046 | 13 | 2012-06-27T23:11:35Z | [
"python",
"arrays",
"list"
] | Is it possible to get which values are duplicates in a list using python?
I have a list of items:
```
mylist = [20, 30, 25, 20]
```
I know the best way of removing the duplicates is `set(mylist)`, but is it possible to know what values are being duplicated? As you can see, in this list the duplicates are the fir... | Here's a list comprehension that does what you want. As @Codemonkey says, the list starts at index 0, so the indices of the duplicates are 0 and 3.
```
>>> [i for i, x in enumerate(mylist) if mylist.count(x) > 1]
[0, 3]
``` |
Scrapy FormRequest sending JSON | 11,236,632 | 7 | 2012-06-28T00:36:46Z | 11,423,992 | 11 | 2012-07-11T00:42:28Z | [
"python",
"json",
"scrapy"
] | I am trying to create a FormRequest that can send content-type:application/json.
Here is what I try:
```
yield FormRequest("abc.someurl.com", formdata=json.dumps({"referenceId":123,"referenceType":456}), headers={'content-type':'application/json'}, callback=self.parseResult2)
```
If I use `json.dumps()` to process t... | FormRequest is for simulating an HTML form (e.g. application/x-www-form-urlencoded). It sounds like you are simply wanting to POST data with your Request. Since you mention a content type of 'application/json' you probably want to do something like this:
```
request = Request( url, method='POST',
b... |
Output values differ between R and Python? | 11,236,951 | 5 | 2012-06-28T01:25:03Z | 11,236,993 | 9 | 2012-06-28T01:31:49Z | [
"python",
"debugging",
"numpy",
"statistics"
] | Perhaps I am doing something wrong while [z-normalizing](http://en.wikipedia.org/wiki/Standard_score) my array. Can someone take a look at this and suggest what's going on?
**In R:**
```
> data <- c(2.02, 2.33, 2.99, 6.85, 9.20, 8.80, 7.50, 6.00, 5.85, 3.85, 4.85, 3.85, 2.22, 1.45, 1.34)
> data.mean <- mean(data)
> d... | I believe that your NumPy result is correct. I would do the normalization in a simpler way, though:
```
>>> data = np.array([2.02, 2.33, 2.99, 6.85, 9.20, 8.80, 7.50, 6.00, 5.85, 3.85, 4.85, 3.85, 2.22, 1.45, 1.34])
>>> data -= data.mean()
>>> data /= data.std()
>>> data
array([-1.01406602, -0.89253491, -0.63379126, ... |
Output values differ between R and Python? | 11,236,951 | 5 | 2012-06-28T01:25:03Z | 11,237,055 | 14 | 2012-06-28T01:42:09Z | [
"python",
"debugging",
"numpy",
"statistics"
] | Perhaps I am doing something wrong while [z-normalizing](http://en.wikipedia.org/wiki/Standard_score) my array. Can someone take a look at this and suggest what's going on?
**In R:**
```
> data <- c(2.02, 2.33, 2.99, 6.85, 9.20, 8.80, 7.50, 6.00, 5.85, 3.85, 4.85, 3.85, 2.22, 1.45, 1.34)
> data.mean <- mean(data)
> d... | The reason you're getting different results has to do with how the standard deviation/variance is calculated. R calculates using denominator `N-1`, while numpy calculates using denominator `N`. You can get a numpy result equal to the R result by using `data.std(ddof=1)`, which tells numpy to use `N-1` as the denominato... |
Python equivalent to PHP include | 11,237,002 | 3 | 2012-06-28T01:33:51Z | 11,237,018 | 7 | 2012-06-28T01:36:19Z | [
"php",
"python",
"include"
] | I need a Python equivalent of PHP's include function. I know of execfile(), but that doesn't work the same. Any ideas? | Try [`import`](http://docs.python.org/reference/simple_stmts.html#the-import-statement), with a try/except on `ImportError`:
```
try:
import modulename
except ImportError:
print 'importing modulename failed'
```
Without catching `ImportError` it is the equivalent of `require`, sorta-kinda.
Do note that pytho... |
Ctypes not finding symbols in shared library created using CMake | 11,237,072 | 6 | 2012-06-28T01:45:18Z | 11,237,254 | 9 | 2012-06-28T02:16:37Z | [
"c++",
"python",
"c",
"cmake",
"ctypes"
] | My CMake setting to create a shared lib in linux is something like
```
SET (CMAKE_CXX_FLAGS "-fPIC")
SET (LIB_UTILS_SRC
Utils.cpp
)
ADD_LIBRARY (UTILS SHARED
${LIB_UTILS_SRC}
)
```
Source Utils.cpp
```
double addTwoNumber(double x, double y)
{
return x + y;
}
```
When trying to access 'addTwoNumber' f... | Interesting, I usually use `numpy.ctypes` since I constantly have to deal with large data sets, and never had any issues but I think I know whats going on here, it's that the names are being mangled by the g++ compiler, I made it work this way:
Makefile:
```
g++ -Wall -fPIC -O2 -c Utils.cpp
g++ -shared -Wl -o libUTIL... |
Why is django's settings object a LazyObject? | 11,238,514 | 5 | 2012-06-28T05:27:21Z | 14,227,305 | 7 | 2013-01-09T02:16:07Z | [
"python",
"django",
"lazy-evaluation",
"django-settings"
] | Looking in django.conf I noticed that settings are implemented like this:
```
class LazySettings(LazyObject):
...
```
What is the rationale behind making settings objects lazy? | Check out [this section](https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#use-of-django-conf-settings) of the Django coding style. The reason is explained in there (quoted below).
In addition to performance, third-party modules can modify settings when they are imported. Accessin... |
Why does Python code run faster in a function? | 11,241,523 | 613 | 2012-06-28T09:18:34Z | 11,241,708 | 602 | 2012-06-28T09:29:12Z | [
"python",
"performance",
"profiling",
"benchmarking",
"cpython"
] | ```
def main():
for i in xrange(10**8):
pass
main()
```
This piece of code in Python runs in
```
real 0m1.841s
user 0m1.828s
sys 0m0.012s
```
However, if the for loop isn't placed within a function,
```
for i in xrange(10**8):
pass
```
then it runs for a much longer time:
```
real 0m4... | Inside a function, the bytecode is
```
2 0 SETUP_LOOP 20 (to 23)
3 LOAD_GLOBAL 0 (xrange)
6 LOAD_CONST 3 (100000000)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 6... |
Why does Python code run faster in a function? | 11,241,523 | 613 | 2012-06-28T09:18:34Z | 11,242,447 | 348 | 2012-06-28T10:15:08Z | [
"python",
"performance",
"profiling",
"benchmarking",
"cpython"
] | ```
def main():
for i in xrange(10**8):
pass
main()
```
This piece of code in Python runs in
```
real 0m1.841s
user 0m1.828s
sys 0m0.012s
```
However, if the for loop isn't placed within a function,
```
for i in xrange(10**8):
pass
```
then it runs for a much longer time:
```
real 0m4... | You might ask *why* it is faster to store local variables than globals. This is a CPython implementation detail.
Remember that CPython is compiled to bytecode, which the interpreter runs. When a function is compiled, the local variables are stored in a fixed-size array (*not* a `dict`) and variable names are assigned ... |
Why does Python code run faster in a function? | 11,241,523 | 613 | 2012-06-28T09:18:34Z | 29,460,892 | 18 | 2015-04-05T18:45:34Z | [
"python",
"performance",
"profiling",
"benchmarking",
"cpython"
] | ```
def main():
for i in xrange(10**8):
pass
main()
```
This piece of code in Python runs in
```
real 0m1.841s
user 0m1.828s
sys 0m0.012s
```
However, if the for loop isn't placed within a function,
```
for i in xrange(10**8):
pass
```
then it runs for a much longer time:
```
real 0m4... | Aside from local/global variable store times, **opcode prediction** makes the function faster.
As the other answers explain, the function uses the `STORE_FAST` opcode in the loop. Here's the bytecode for the function's loop:
```
>> 13 FOR_ITER 6 (to 22) # get next value from iterator
... |
Python accessing data in JSON object | 11,241,583 | 3 | 2012-06-28T09:22:10Z | 11,241,629 | 7 | 2012-06-28T09:24:47Z | [
"python",
"json",
"ffprobe"
] | so I do this in my script:
```
import json
info = json.loads(get_info())
print info
```
Which outputs:
```
richard@richard-desktop:~/projects/hello-python$ python main.py
{
"streams": [
{
"index": 0,
"codec_name": "mpeg2video",
"codec_long_name": "MPEG-2 video",
... | The JSON was encoded *twice*, and the result of `json.loads` is a string. Strings in python are sequences thus the first character is a `{`.
Decode the item again:
```
info = json.loads(json.loads(get_info()))
```
Now your main.py output should look like:
```
>>> result = json.loads(output)
>>> print result
{u'stre... |
Python unittests in Jenkins? | 11,241,781 | 64 | 2012-06-28T09:33:34Z | 11,254,256 | 7 | 2012-06-28T23:24:16Z | [
"python",
"unit-testing",
"jenkins",
"junit",
"xunit"
] | How do you get Jenkins to execute python unittest cases?
Is it possible to JUnit style XML output from the builtin `unittest` package? | You can install the [unittest-xml-reporting](http://pypi.python.org/pypi/unittest-xml-reporting) package to add a test runner that generates XML to the built-in `unittest`.
We use [pytest](http://pytest.org/), which has XML output built in (it's a command line option).
Either way, executing the unit tests can be done... |
Python unittests in Jenkins? | 11,241,781 | 64 | 2012-06-28T09:33:34Z | 11,463,624 | 16 | 2012-07-13T03:12:38Z | [
"python",
"unit-testing",
"jenkins",
"junit",
"xunit"
] | How do you get Jenkins to execute python unittest cases?
Is it possible to JUnit style XML output from the builtin `unittest` package? | I would second using nose. Basic XML reporting is now built in. Just use the --with-xunit command line option and it will produce a nosetests.xml file. For example:
> nosetests --with-xunit
Then add a "Publish JUnit test result report" post build action, and fill in the "Test report XMLs" field with nosetests.xml (as... |
Python unittests in Jenkins? | 11,241,781 | 64 | 2012-06-28T09:33:34Z | 19,126,329 | 87 | 2013-10-01T21:32:22Z | [
"python",
"unit-testing",
"jenkins",
"junit",
"xunit"
] | How do you get Jenkins to execute python unittest cases?
Is it possible to JUnit style XML output from the builtin `unittest` package? | # sample tests:
tests.py:
```
# tests.py
import random
try:
import unittest2 as unittest
except ImportError:
import unittest
class SimpleTest(unittest.TestCase):
@unittest.skip("demonstrating skipping")
def test_skipped(self):
self.fail("shouldn't happen")
def test_pass(self):
s... |
building scrapy spiders into my own program, i don't want to call scrapy from command line) | 11,242,019 | 7 | 2012-06-28T09:48:33Z | 11,242,654 | 7 | 2012-06-28T10:28:01Z | [
"python",
"web-scraping",
"scrapy"
] | in a similar vein to this question:
[stackoverflow: running-multiple-spiders-in-scrapy](http://stackoverflow.com/questions/10943745/running-multiple-spiders-in-scrapy)
I am wondering, can I run a entire scrapy project from within another python program? Lets just say I wanted to build a entire program that required sc... | Yep, of course you can ;)
[The idea (inspired from this blog post)](http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/) is to create a worker and then use it in your own Python script:
```
from scrapy import project, signals
from scrapy.conf import settings
from scrapy.crawler import CrawlerProcess
fro... |
Modify tick label text | 11,244,514 | 65 | 2012-06-28T12:20:00Z | 11,245,241 | 9 | 2012-06-28T13:00:58Z | [
"python",
"matplotlib"
] | I want to make some modifications to a few selected tick labels in a plot.
For example, if I do:
```
label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')
```
the font size and the orientation of the tick label is changed.
However, if try:
```
label.set_text('Foo')
`... | The axes class has a [set\_yticklabels](http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_yticklabels) function which allows you to set the tick labels, like so:
```
#ax is the axes instance
group_labels = ['control', 'cold treatment',
'hot treatment', 'another treatment',
... |
Modify tick label text | 11,244,514 | 65 | 2012-06-28T12:20:00Z | 11,250,884 | 98 | 2012-06-28T18:37:34Z | [
"python",
"matplotlib"
] | I want to make some modifications to a few selected tick labels in a plot.
For example, if I do:
```
label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')
```
the font size and the orientation of the tick label is changed.
However, if try:
```
label.set_text('Foo')
`... | Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than `1.1.0`. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may... |
Modify tick label text | 11,244,514 | 65 | 2012-06-28T12:20:00Z | 18,946,103 | 40 | 2013-09-22T16:32:56Z | [
"python",
"matplotlib"
] | I want to make some modifications to a few selected tick labels in a plot.
For example, if I do:
```
label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')
```
the font size and the orientation of the tick label is changed.
However, if try:
```
label.set_text('Foo')
`... | In newer versions of `matplotlib`, if you do not set the tick labels with a bunch of `str` values, they are `''` by default (and when the plot is draw the labels are simply the ticks values). Knowing that, to get your desired output would require something like this:
```
>>> from pylab import *
>>> axes = figure().add... |
Modify tick label text | 11,244,514 | 65 | 2012-06-28T12:20:00Z | 27,440,179 | 20 | 2014-12-12T09:08:01Z | [
"python",
"matplotlib"
] | I want to make some modifications to a few selected tick labels in a plot.
For example, if I do:
```
label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')
```
the font size and the orientation of the tick label is changed.
However, if try:
```
label.set_text('Foo')
`... | One can also do this with *pylab* and *xticks*
```
import pylab as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()
```
<http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html> |
Tkinter askquestion dialog box | 11,244,753 | 4 | 2012-06-28T12:34:20Z | 11,244,823 | 12 | 2012-06-28T12:37:55Z | [
"python",
"tkinter",
"tkmessagebox"
] | I have been trying to add an askquestion dialog box to a delete button in Tkinter. Curently I have a button that deletes the contents of a folder once it is pressed I would like to add a yes/no confirmation question.
```
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def deleteme():
tkMessageBox.askquestio... | The problem is your `if`-statement. You need to get the result from the dialog (which will be `'yes'` or `'no'`) and compare with that. Note the 2nd and 3rd line in the code below.
```
def deleteme():
result = tkMessageBox.askquestion("Delete", "Are You Sure?", icon='warning')
if result == 'yes':
print... |
Formatting console Output | 11,245,381 | 2 | 2012-06-28T13:09:06Z | 11,245,781 | 7 | 2012-06-28T13:30:26Z | [
"python",
"text-formatting",
"console-output"
] | I'm having trouble making python print out texts properly aligned. I have tried everything I knew, but still the same result and it's very annoying!.
Here is what I'm getting in the console

Here is the Code I have.
```
print " FileName\t\t\t\t\tStat... | Use `%45s` to make a right justified field that is 45 characters long. And use `%-45s` to make a left justified string. Also consider extracting your line printing into a function - that way you'll be able to change it easily in one place. Like this:
```
# fake setup
PASS = ["foo.exe", "bar.exe", "really_long_filenam... |
Django filter events occurring today | 11,245,483 | 11 | 2012-06-28T13:14:10Z | 11,264,402 | 17 | 2012-06-29T15:15:00Z | [
"python",
"django"
] | I'm struggling to logically represent the following in a Django filter. I have an 'event' model, and a location model, which can be represented as:
```
class Location(models.Model):
name = models.CharField(max_length=255)
class Event(models.Model):
start_date = models.DateTimeField()
end_date = models.Dat... | You'll need two distinct `datetime` thresholds - `today_start` and `today_end`:
```
from datetime import datetime, timedelta, time
today = datetime.now().date()
tomorrow = today + timedelta(1)
today_start = datetime.combine(today, time())
today_end = datetime.combine(tomorrow, time())
```
Anything happening today mu... |
Python: Queue.Empty Exception Handling | 11,247,439 | 9 | 2012-06-28T15:00:28Z | 11,247,726 | 16 | 2012-06-28T15:17:50Z | [
"python",
"exception-handling",
"queue"
] | After a short debate with someone about exception handling in Python - sparked by the handling of a queue object - I thought I'd throw it out there...
# METHOD 1:
```
import Queue
q = Queue.Queue()
try:
task=q.get(False)
#Opt 1: Handle task here and call q.task_done()
except Queue.Empty:
#Handle empty q... | Method 2 is wrong because you are doing an operation in two steps when it could be done in one. In method 2, you check if the queue is empty, and then later (very soon, but still later), try to get the item. What if you have two threads pulling items from the queue? The get() could still fail with an empty queue. What ... |
What is the easiest way to remove all packages installed by pip? | 11,248,073 | 160 | 2012-06-28T15:36:44Z | 11,248,097 | 10 | 2012-06-28T15:37:50Z | [
"python",
"django",
"pip"
] | I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip? | The quickest way is to remake the virtualenv completely. I'm assuming you have a requirements.txt file that matches production, if not:
```
# On production:
pip freeze > reqs.txt
# On your machine:
rmvirtualenv MYENV
mkvirtualenv MYENV
pip install -r reqs.txt
``` |
What is the easiest way to remove all packages installed by pip? | 11,248,073 | 160 | 2012-06-28T15:36:44Z | 11,250,821 | 278 | 2012-06-28T18:32:29Z | [
"python",
"django",
"pip"
] | I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip? | I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv:
```
pip freeze | xargs pip uninstall -y
```
---
In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):... |
What is the easiest way to remove all packages installed by pip? | 11,248,073 | 160 | 2012-06-28T15:36:44Z | 11,672,492 | 46 | 2012-07-26T15:15:15Z | [
"python",
"django",
"pip"
] | I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip? | I think this works with the latest
```
virtualenv --clear MYENV
``` |
What is the easiest way to remove all packages installed by pip? | 11,248,073 | 160 | 2012-06-28T15:36:44Z | 34,118,237 | 7 | 2015-12-06T14:01:59Z | [
"python",
"django",
"pip"
] | I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip? | On Windows if your `path` is configured correctly, you can use:
```
pip freeze > unins && pip uninstall -y -r unins && del unins
```
It should be a similar case for Unix-like systems:
```
pip freeze > unins && pip uninstall -y -r unins && rm unins
```
Just a warning that this isn't completely solid as you may run i... |
What is the easiest way to remove all packages installed by pip? | 11,248,073 | 160 | 2012-06-28T15:36:44Z | 37,642,437 | 9 | 2016-06-05T13:25:34Z | [
"python",
"django",
"pip"
] | I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production.
Is there a quick and easy way to do this with pip? | ### Method 1 (with `pip freeze`)
```
pip freeze | xargs pip uninstall -y
```
### Method 2 (with `pip list`)
```
pip list | awk '{print $1}' | xargs pip uninstall -y
```
### Method 3 (with `virtualenv`)
```
virtualenv --clear MYENV
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.