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 |
|---|---|---|---|---|---|---|---|---|---|
Log the values of argparse in python | 11,571,794 | 3 | 2012-07-20T01:51:54Z | 11,571,812 | 7 | 2012-07-20T01:54:30Z | [
"python",
"logging",
"argparse"
] | I am trying to use both argparse and logging modules in python. I have a program that I run that has a lot of possible options and I've successfully implemented the argparse module to handle this task.
I'd like to keep a record of the values each option has when the program is run and send it to a log file. I tried th... | You can use `vars` to get the attributes of your parsed arguments:
```
for arg, value in sorted(vars(args).items()):
logging.info("Argument %s: %r", arg, value)
```
This is detailed in [the docs](http://docs.python.org/library/argparse.html#the-namespace-object). |
Why does Python have "else" in "for-else" and "while-else"? | 11,572,164 | 6 | 2012-07-20T02:49:30Z | 11,572,172 | 19 | 2012-07-20T02:50:57Z | [
"python",
"python-3.x"
] | I am a Python beginner. I find that the "else" in âfor-elseâ and "while-else" is completely unnecessary. Because "for" and "while" will finally run to "else", and we can use the usual lines instead.
For example:
```
for i in range(1, 5):
print i
else:
print 'over'
```
And
```
for i in range(1, 5):
p... | You are wrong about the semantics of for/else. The else clause runs only if the loop completed, for example, if a break statement wasn't encountered.
The typical for/else loop looks like this:
```
for x in seq:
if cond(x):
break
else:
print "Didn't find an x I liked!"
```
Think of the "else" as pairi... |
How to download a file via FTP with Python ftplib | 11,573,817 | 29 | 2012-07-20T06:15:58Z | 11,573,946 | 34 | 2012-07-20T06:28:45Z | [
"python",
"ftplib"
] | I have the following code which easily connects to the FTP server and opens a zip file. I want to download that file into the local system. How to do that?
```
# Open the file for writing in binary mode
print 'Opening local file ' + filename
file = open(filename, 'wb')
# Download the file a chunk at a time
# Each chu... | ```
ftp.retrbinary('RETR %s' % filename, file.write)
``` |
How to download a file via FTP with Python ftplib | 11,573,817 | 29 | 2012-07-20T06:15:58Z | 11,573,992 | 17 | 2012-07-20T06:33:22Z | [
"python",
"ftplib"
] | I have the following code which easily connects to the FTP server and opens a zip file. I want to download that file into the local system. How to do that?
```
# Open the file for writing in binary mode
print 'Opening local file ' + filename
file = open(filename, 'wb')
# Download the file a chunk at a time
# Each chu... | ```
A = filename
ftp = ftplib.FTP("IP")
ftp.login("USR Name", "Pass")
ftp.cwd("/Dir")
try:
ftp.retrbinary("RETR " + filename ,open(i, 'wb').write)
except:
print "Error"
``` |
IPython import failure and python sys.path in general | 11,573,844 | 13 | 2012-07-20T06:18:50Z | 11,575,429 | 9 | 2012-07-20T08:13:57Z | [
"python",
"virtualenv",
"ipython"
] | I'm following this [post](http://isbullsh.it/2012/04/Embed-ipython-in-virtualenv/) to make one ipython rule all the virtualenvs.
From what I understand, the main idea of the post is that when in a virtualenv, ipython can not find its modules.
```
(a-virtualenv)me@pc:~$ ipython
Traceback (most recent call last):
Fil... | IPython seems to work now!
Because ipython can not find simplegeneric. I tried to locate simplegeneric and found simplegeneric is in '/usr/lib/pymodules/python2.7'. After '/usr/lib/pymodules/python2.7' being added, ipython works fine.
Jeff Tratner's comment really helps! |
IPython import failure and python sys.path in general | 11,573,844 | 13 | 2012-07-20T06:18:50Z | 17,175,233 | 7 | 2013-06-18T17:29:55Z | [
"python",
"virtualenv",
"ipython"
] | I'm following this [post](http://isbullsh.it/2012/04/Embed-ipython-in-virtualenv/) to make one ipython rule all the virtualenvs.
From what I understand, the main idea of the post is that when in a virtualenv, ipython can not find its modules.
```
(a-virtualenv)me@pc:~$ ipython
Traceback (most recent call last):
Fil... | If you install `ipython3` using `apt-get`, you would not face any problems like that.
Instead of `ipython`, you should type `ipython3` on the terminal.
For Python 2 use `ipython2`. |
JSONP web service with python | 11,574,850 | 8 | 2012-07-20T07:32:16Z | 11,575,180 | 7 | 2012-07-20T07:57:42Z | [
"python",
"json"
] | I'm writing an AJAX function that requests data from my JSON Python webservice. My AJAX request looks like:
```
url = "http://localhost:8001/blah"
$.ajax({
url: url,
type: 'get',
dataType: 'jsonp',
success: function(data) {
console.log('hi')
}
});
```
For now, my python w... | What happens when you use Jquery's JSONP datatype, is that a callback function name is sent as a GET param as part of your URL, so you're actually querying something like "http://localhost:8001/blah?callback=json125348274839".
Your response from your web server should look like this:
```
return "%s({'a':1, 'b':2 ... |
Overload int() in Python | 11,575,393 | 4 | 2012-07-20T08:10:37Z | 11,575,472 | 8 | 2012-07-20T08:17:15Z | [
"python",
"class",
"operator-overloading"
] | Say I have a basic class in Python 3 which represents some number-like data-type. I want to make it so when I have an instance, x, of this class I can call int(x) and have it call my conversion function to return the integer portion.
I'm sure this is simple, but I can't seem to find out how to do it. | You override the `__int__` magic method as per the following example...
```
class Test:
def __init__(self, i):
self.i = i
def __int__(self):
return self.i * 2
t = Test(5)
print( int(t) )
# 10
``` |
How can I save my secret keys and password securely in my version control system? | 11,575,398 | 100 | 2012-07-20T08:11:06Z | 11,575,435 | 11 | 2012-07-20T08:14:23Z | [
"python",
"django",
"git",
"version-control"
] | I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's *bad practice* to keep *secrets* (like private keys and database passwords) in a VCS repository.
But passwords--like any other setting--seem like they should be versioned. So ... | An option would be to put project-bound credentials into an encrypted container (TrueCrypt or Keepass) and push it.
*Update as answer from my comment below:*
Interesting question btw. I just found this: [github.com/shadowhand/git-encrypt](https://github.com/shadowhand/git-encrypt) which looks very promising for autom... |
How can I save my secret keys and password securely in my version control system? | 11,575,398 | 100 | 2012-07-20T08:11:06Z | 11,575,518 | 8 | 2012-07-20T08:20:40Z | [
"python",
"django",
"git",
"version-control"
] | I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's *bad practice* to keep *secrets* (like private keys and database passwords) in a VCS repository.
But passwords--like any other setting--seem like they should be versioned. So ... | I suggest using configuration files for that and to not version them.
You can however version examples of the files.
I don't see any problem of sharing development settings. By definition it should contain no valuable data. |
How can I save my secret keys and password securely in my version control system? | 11,575,398 | 100 | 2012-07-20T08:11:06Z | 11,576,388 | 15 | 2012-07-20T09:14:07Z | [
"python",
"django",
"git",
"version-control"
] | I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's *bad practice* to keep *secrets* (like private keys and database passwords) in a VCS repository.
But passwords--like any other setting--seem like they should be versioned. So ... | The cleanest way in my opinion is to use environment variables. You won't have to deal with *.dist* files for example, and the project state on the production environment would be the same as your local machine's.
I recommend reading [The Twelve-Factor App](http://www.12factor.net/config)'s config chapter, the others ... |
How can I save my secret keys and password securely in my version control system? | 11,575,398 | 100 | 2012-07-20T08:11:06Z | 11,667,433 | 42 | 2012-07-26T10:33:19Z | [
"python",
"django",
"git",
"version-control"
] | I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's *bad practice* to keep *secrets* (like private keys and database passwords) in a VCS repository.
But passwords--like any other setting--seem like they should be versioned. So ... | Heroku pushes [the use of environment variables](https://devcenter.heroku.com/articles/config-vars) for settings and secret keys:
> The traditional approach for handling such config vars is to put them under source - in a properties file of some sort. This is an error-prone process, and is especially complicated for o... |
How can I save my secret keys and password securely in my version control system? | 11,575,398 | 100 | 2012-07-20T08:11:06Z | 11,679,005 | 81 | 2012-07-26T22:31:55Z | [
"python",
"django",
"git",
"version-control"
] | I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's *bad practice* to keep *secrets* (like private keys and database passwords) in a VCS repository.
But passwords--like any other setting--seem like they should be versioned. So ... | You're exactly right to want to encrypt your sensitive settings file while still maintaining the file in version control. As you mention, the best solution would be one in which Git will transparently encrypt certain sensitive files when you push them so that locally (i.e. on any machine which has your certificate) you... |
How can I save my secret keys and password securely in my version control system? | 11,575,398 | 100 | 2012-07-20T08:11:06Z | 25,654,190 | 7 | 2014-09-03T21:47:39Z | [
"python",
"django",
"git",
"version-control"
] | I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's *bad practice* to keep *secrets* (like private keys and database passwords) in a VCS repository.
But passwords--like any other setting--seem like they should be versioned. So ... | [BlackBox](https://github.com/StackExchange/blackbox) was recently released by StackExchange and while I have yet to use it, it seems to exactly address the problems and support the features requested in this question.
From the description on <https://github.com/StackExchange/blackbox>:
> Safely store secrets in a VC... |
What exactly are "containers" in python? (And what are all the python container types?) | 11,575,925 | 26 | 2012-07-20T08:45:12Z | 11,576,019 | 35 | 2012-07-20T08:51:11Z | [
"python",
"containers"
] | The python documentation frequently speaks of "containers". [E.g.](http://docs.python.org/library/json.html?highlight=container#basic-usage) :
> If check\_circular is False (default: True), then the circular
> reference check for **container types** will be skipped and a circular
> reference will result in an Overflow... | Containers are any object that holds an arbitrary number of other objects. Generally, containers provide a way to access the contained objects and to iterate over them.
Examples of containers include `tuple`, `list`, `set`, `dict`; these are the *built-in containers*. More container types are available in the [`collec... |
Parse HTML and preserve original content | 11,576,461 | 13 | 2012-07-20T09:18:49Z | 11,583,283 | 11 | 2012-07-20T16:20:30Z | [
"python",
"html",
"ruby",
"node.js",
"html-parsing"
] | I have lots of HTML files. I want to replace some elements, keeping all the other content unchanged. For example, I would like to execute this jQuery expression (or some equivalent of it):
```
$('.header .title').text('my new content')
```
on the following HTML document:
```
<div class=header><span class=title>Foo</... | I highly recommend the [pyquery](http://packages.python.org/pyquery/) package, for python. It is a jquery-like interface layered ontop of the extremely reliable [lxml](http://lxml.de/) package, a python binding to libxml2.
I believe this does exactly what you want, with a quite familiar interface.
```
from pyquery im... |
Change x axes scale in matplotlib | 11,577,665 | 32 | 2012-07-20T10:38:25Z | 11,579,834 | 45 | 2012-07-20T12:56:25Z | [
"python",
"matplotlib"
] | I created this plot using Matlab

Using matplotlib, the x-axies draws large numbers such as 100000, 200000, 300000. I would like to have something like 1, 2, 3 and a 10^5 to indicate that it's actually 100000, 200000, 300000.
Is there a simple way to... | Try using [`matplotlib.pyplot.ticklabel_format`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ticklabel_format):
```
import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
```
This applies scientific notation (i.e. `a x 10^b`) to your x-axis tickmar... |
Change x axes scale in matplotlib | 11,577,665 | 32 | 2012-07-20T10:38:25Z | 11,579,905 | 11 | 2012-07-20T13:00:14Z | [
"python",
"matplotlib"
] | I created this plot using Matlab

Using matplotlib, the x-axies draws large numbers such as 100000, 200000, 300000. I would like to have something like 1, 2, 3 and a 10^5 to indicate that it's actually 100000, 200000, 300000.
Is there a simple way to... | The [scalar formatter](http://matplotlib.sourceforge.net/api/ticker_api.html#matplotlib.ticker.ScalarFormatter) supports collecting the exponents. The docs are as follows:
> class matplotlib.ticker.ScalarFormatter(useOffset=True,
> useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter
>
> Tick location... |
How to setup django-hstore with an existing app managed by south? | 11,577,993 | 18 | 2012-07-20T11:01:10Z | 11,581,961 | 18 | 2012-07-20T15:05:31Z | [
"python",
"django",
"psycopg2",
"hstore"
] | I tried to use django-hstore using [this nice tutorial](http://www.craigkerstiens.com/2012/06/11/schemaless-django/). I added two classes to an existing app managed by South:
```
class Attribute(models.Model):
name = models.CharField(max_length=200, verbose_name=_("name"))
description = models.CharField(max_l... | I eventually found that the hstore extension wasn't installed for the specific database I was using:
```
$ psql -d mydb
psql (9.1.4)
Type "help" for help.
mydb=# SELECT t.oid, typarray FROM pg_type t JOIN pg_namespace ns ON typnamespace = ns.oid WHERE typname = 'hstore';
oid | typarray
-----+----------
(0 rows)
my... |
sqlalchemy: 'InstrumentedList' object has no attribute 'filter' | 11,578,070 | 9 | 2012-07-20T11:06:01Z | 11,579,347 | 22 | 2012-07-20T12:24:43Z | [
"python",
"sqlalchemy"
] | I have the following 3 classes:
```
class Resource:
id = Column(Integer, primary_key=True)
path = Column(Text)
data = Column(Binary)
type = Column(Text)
def set_resource(self, path, data, type):
self.path = path
self.data = data
self.type = type
class EnvironmentResource(B... | In order to work with the [relationship](http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#sqlalchemy.orm.relationship) as with `Query`, you need to configure it with `lazy='dynamic'`. See more on this in [Dynamic Relationship Loaders](http://docs.sqlalchemy.org/en/rel_0_7/orm/collections.html#dynamic-relati... |
How to change django datetime format output? | 11,578,311 | 8 | 2012-07-20T11:22:06Z | 11,578,330 | 21 | 2012-07-20T11:23:28Z | [
"python",
"django",
"django-templates"
] | I have a datetime object. This is my template file:
```
<ul>
<li>{{ sale.validity }}</li>
</ul>
```
and the output i'm getting is in the format:
> July 18, 2012, midnight
I would really like to change the output to be numerical in the format: day-month-year so for example the above would be changed to:
> 18-07-201... | Per [Django docs](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date), you can use a `date` filter to format date:
```
{{ sale.validity|date:"d-m-Y"}}
```
Additionally, you can also set [DATE\_FORMAT](https://docs.djangoproject.com/en/1.9/ref/settings/#date-format) (or DATETIME\_FORMAT) setting to set... |
threadsafe cannot be enabled with CGI handler | 11,578,358 | 4 | 2012-07-20T11:24:39Z | 11,578,672 | 29 | 2012-07-20T11:43:58Z | [
"python",
"google-app-engine"
] | I've been trying to follow [this turorial](https://developers.google.com/appengine/articles/openid?hl=pl#ex) in order to implement openID authentication on an app, but I am completely lost. No matter what I tried, I kept getting this error:
```
Fatal error when loading application configuration:
Invalid object:
thread... | This has nothing to do with OpenID.
If you use the new Concurrent Requests (**threadsafe=true**) mode with python 2.7 in Google App Engine you have to make sure that you specify a WSGI application (e.g. myapp.app) instead of a CGI handler (e.g. myapp.py) in app.yaml (see [here](https://developers.google.com/appengine/... |
How to bind multiple reusable Django apps together? | 11,579,232 | 16 | 2012-07-20T12:19:00Z | 14,327,559 | 10 | 2013-01-14T22:01:17Z | [
"python",
"django",
"django-1.4"
] | I try my best to write reusable Django apps. Now I'm puzzled how to put them all together to get the final project.
Here is an example of what I mean:
I have a picture app that stores, resizes and displays images. Also I have a weblog app that stores, edits and displays texts. Now I want to combine these two to show b... | Introduction talk in the bottom of the answer (more straight to the answer). I will assume that you have one app for text handling called Text and one app for picture handling called Pictures and a third app for blogging called Blog.
## Big picture
You will need to studdy [the manual about the template language for p... |
How do I get my computer's fully qualified domain name in Python? | 11,580,023 | 19 | 2012-07-20T13:07:08Z | 11,580,042 | 29 | 2012-07-20T13:08:36Z | [
"python",
"networking",
"dns",
"subdomain"
] | I know I can use platform.node() to get my computer's network name:
```
>>> import platform
>>> platform.node()
'MyComputerName'
```
But what I really want is something that will work similar to the following:
```
>>> get_full_network_domain_name()
'MyComputerName.it.na.mycompany.com'
```
Does something like this e... | The fully qualified domain name is returned by [`socket.getfqdn()`](http://docs.python.org/library/socket.html#socket.getfqdn). |
Are class based views widely used by the Django community? | 11,581,216 | 6 | 2012-07-20T14:17:56Z | 11,581,327 | 8 | 2012-07-20T14:25:23Z | [
"python",
"django",
"django-class-based-views"
] | I am new to Django and Python and after reading a lot I decided not to use global functions as views (maybe because I am not used to global functions but mostly because I want a better reuse level and prefer to have smaller code blocks). The problem is that most of the Django apps I have been checking do not use a clas... | One fact is that class based view was added in [Django 1.3](https://docs.djangoproject.com/en/dev/topics/class-based-views/), so if you're planning to support old Django version than you will have to stick with function view, for example if you want to create a generic app and launch it in GitHub or such for other peop... |
Force python subclass init to use subclass variables, not parent class | 11,581,546 | 4 | 2012-07-20T14:39:41Z | 11,581,604 | 9 | 2012-07-20T14:43:35Z | [
"python"
] | In the following code:
```
class A(object):
VALUE = 1
def __init__(self, value=VALUE):
self.value = value
class B(A):
VALUE = 2
```
i'd expect that B().value should be equal to 2, however:
```
B().value = 1
```
Is there an elegant way to define a class hierarchy where child classes can just declare class... | This is another [default arguments](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) question. The point is that when you write
```
def foo(value=VALUE):
```
the code inside the function is compiled and made into a function object. It is at *this* time -- not at ca... |
How do I change the format of a Python log message on a per-logger basis? | 11,581,794 | 14 | 2012-07-20T14:55:15Z | 11,582,124 | 15 | 2012-07-20T15:14:42Z | [
"python",
"logging",
"python-3.x"
] | After reading the [documentation on `logging`](http://docs.python.org/py3k/library/logging.html#module-logging), I know I can use code like this to perform simple logging:
```
import logging
def main():
logging.basicConfig(filename="messages.log",
level=logging.WARNING,
... | Try this
```
import logging
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging... |
Flask Python Model Validation | 11,582,233 | 7 | 2012-07-20T15:20:54Z | 18,579,864 | 10 | 2013-09-02T19:45:29Z | [
"python",
"validation",
"flask"
] | Coming from a php background, I am learning python through Flask. I have used WTForms for the client, and this handles validation nicely.
However, one of the things that I would like to use flask for is a public API, in which case I would like all validation to be run on my models. I thought that SQLAlchemy would incl... | ## Have you considered doing the validation in the Model layer...
This would allow you to have a perfectly DRY solution as validation would be automatically triggered whether the update source is data sent by the user, or whether it is a component of your application which is updating the model as part of an indirect ... |
defining class methods outside of the class Python | 11,582,454 | 4 | 2012-07-20T15:32:10Z | 11,582,495 | 9 | 2012-07-20T15:34:15Z | [
"python",
"class",
"methods"
] | I am trying to understand how the methods of the class are called when defined from outside of it. While I've found other threads addressing this issue, I haven't found a very clear answer to my question, so I want to post it in a simple form.
Is defining a function outside of a class and calling it from the inside th... | The two versions are completely equivalent (except that the first version also introduces `my_func` into the global namespace, of course, and the different name you used for the first parameter).
Note that there are no "class methods" in your code â both definitions result in regular (instance) methods.
A function ... |
Python, "commands out of sync; you can't run this command now" | 11,583,083 | 16 | 2012-07-20T16:07:57Z | 11,590,273 | 27 | 2012-07-21T07:21:40Z | [
"python",
"mysql"
] | I have a MySQL stored procedure that is executed from Python (wrapped in Django). I get the error "commands out of sync; you can't run this command now" when I try to execute the second statement. I cannot commit the transaction at this point. This is only an issue when I call a procedure. What to do?
```
cursor.callp... | Thanks to JoshuaBoshi for his answer, which solved the problem. After calling the procedure, I had to close the cursor and open it again before using it to execute another statement:
```
cursor.close()
cursor = connection.cursor()
```
The cursor can be closed immediately after `fetchall()`. The result set still rem... |
Install psycopg2 on Ubuntu | 11,583,714 | 24 | 2012-07-20T16:49:41Z | 11,583,788 | 32 | 2012-07-20T16:55:31Z | [
"python",
"postgresql",
"ubuntu"
] | I'm trying to get the python postgres client module installed on Ubuntu 12.04. The guidance is to do the following:
```
apt-get install python-psycopg2
```
However, `apt` says that the package can't be located.
I'm keen to install this through `apt`. Is this part of another package that I can install? | Using Ubuntu 12.04 it appears to work fine for me:
```
jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
python-psycopg2-doc
The following NEW packages will be installed
p... |
Install psycopg2 on Ubuntu | 11,583,714 | 24 | 2012-07-20T16:49:41Z | 25,855,548 | 33 | 2014-09-15T19:31:12Z | [
"python",
"postgresql",
"ubuntu"
] | I'm trying to get the python postgres client module installed on Ubuntu 12.04. The guidance is to do the following:
```
apt-get install python-psycopg2
```
However, `apt` says that the package can't be located.
I'm keen to install this through `apt`. Is this part of another package that I can install? | This works for me in Ubuntu 12.04 and 15.10
if pip not installed:
```
sudo apt-get install python-pip
```
and then:
```
sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2
``` |
Why is Python's 'all' function so slow? | 11,583,869 | 3 | 2012-07-20T17:01:07Z | 11,584,012 | 7 | 2012-07-20T17:11:25Z | [
"python",
"performance"
] | I have wrote some very simple tests (I know, they are not 'conclusive', but they make me curious). I ran with optimization and all that jazz.
```
from time import time
alist = [ 2, 4, 6, 8, 10, 12, 24, 48, 64, 128 ]
def all_even( alist ):
for val in alist:
if not (val & 1) == 0:
return False
... | `all()` definitely does exit early, I think the behavior difference is just the result of the overhead required to create the generator.
Here is some proof that `all()` does exit early:
```
In [8]: alist = [3] + [0] * 2**20 # alist bigger, with an early odd
In [10]: %timeit all_even(alist)
1000000 loops, best of ... |
Copy a file line by line in python | 11,584,300 | 2 | 2012-07-20T17:36:45Z | 11,584,338 | 9 | 2012-07-20T17:39:40Z | [
"python"
] | I am writing a python program to copy a file line by line into a new file. The code I have is below in which I am using a loop to copy the file line by line.
However since the number of lines in the file may change, is there a way to copy a file line by line in python without using a loop which relies on numbers, and ... | You can iterate over lines in a file object in Python by iterating over the file object itself:
```
for line in f:
copy.write(line)
```
From the [docs on file objects](http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects):
> An alternative approach to reading lines is to loop over the file ob... |
run cp command to make a copy of a file or change a file name in Python | 11,584,502 | 2 | 2012-07-20T17:53:30Z | 11,584,547 | 8 | 2012-07-20T17:57:09Z | [
"python",
"linux",
"bash",
"shell",
"cp"
] | In python 2.7.2, i need to make a copy of a file in Linux.
newfile = "namePart1" + dictionary[key] + "namePart2"
os.system("cp cfn5e10\_1.lp newfile")
But, the newfile cannot be replaced by its correct string.
the posts in the forum cannot help.
Any help is really appreciated. | Use [`shutil.copyfile`](http://docs.python.org/library/shutil.html#shutil.copyfile) to copy a file instead of `os.sytem`, it doesn't need to create a new process and it will automatically handle filenames with unusual characters in them, e.g. spaces -- `os.system` just passes the command to the shell, and the shell mig... |
sorting a graph by its edge weight. python | 11,584,773 | 4 | 2012-07-20T18:11:40Z | 11,584,812 | 8 | 2012-07-20T18:14:41Z | [
"python"
] | I have a list of tuples of format:
```
(node1, node2, weight)
```
What I want to do is sort this tuple so that the the nodes with higher weight are at the top
for example
```
(A,B,2)
(A,C,5)
(C,A,2)
```
should give me
```
(A,C,5)
(A,B,2)
(C,A,2)
```
The first node is sorted alphabetically.
Second node as per the... | This should work just fine:
```
lst.sort(key=lambda x:x[2], reverse=True)
```
Of course, we can avoid the lambda by:
```
import operator
lst.sort(key=operater.itemgetter(2), reverse=True)
```
If you want to sort on multiple conditions, you can create interesting functions to return tuples (tuples will sort by first... |
Python - How to nest file read loops? | 11,585,688 | 6 | 2012-07-20T19:20:43Z | 11,586,112 | 7 | 2012-07-20T19:52:25Z | [
"python",
"loops",
"readline"
] | 2 days ago I was first introduced to Python (and programming in general). Today I'm stuck. I've spent hours trying to find an answer to what I suspect is a problem so trivial, nobody else has yet been stuck here : )
The boss wants me to manually clean up HUGE .xml files into something more human readable. I'm trying t... | An example of using lxml which I highly recommend to process your data. (nb: written for Py2.x but easy to adapt for Py3.x)
```
from lxml import etree
xml = """<IssueTracking>
<Issue>
<SequenceNum>123</SequenceNum>
<Subject>Subject of Ticket 123</Subject>
<Description>Line 1 in Description field of Ticke... |
Python - how does passing values work? | 11,585,768 | 12 | 2012-07-20T19:27:29Z | 11,585,840 | 14 | 2012-07-20T19:31:56Z | [
"python",
"function",
"styles"
] | I have a question about function calls in Python. Say I want to write a function called superLongFunc(expr). The function is super long and really hard to debug. I want to split the function into smaller helper functions for better readability, to something like smallFunc1(expr),smallFunc2(expr), etc.
My question is, ... | Python uses a system sometimes called [call-by-object](http://effbot.org/zone/call-by-object.htm). Nothing is copied when you pass arguments to a function. The names of the function arguments are locally bound within the function body, to the same objects provided in the function call.
This is different from what most... |
Are numpy arrays passed by reference? | 11,585,793 | 21 | 2012-07-20T19:28:33Z | 11,585,878 | 29 | 2012-07-20T19:34:57Z | [
"python",
"arrays",
"numpy"
] | I came across the fact that `numpy` arrays are passed by reference at multiple places, but then when I execute the following code, why is there a difference between the behavior of `foo` and `bar`
```
import numpy as np
def foo(arr):
arr = arr - 3
def bar(arr):
arr -= 3
a = np.array([3, 4, 5])
foo(a)
print a ... | In Python, [all variable names are references to values](http://nedbatchelder.com/text/names.html).
When Python evaluates an assignment, [the right-hand side is evaluated before the left-hand side](https://docs.python.org/2/reference/expressions.html#evaluation-order). `arr - 3` creates a new array; it does not modify... |
Are numpy arrays passed by reference? | 11,585,793 | 21 | 2012-07-20T19:28:33Z | 11,585,888 | 7 | 2012-07-20T19:35:38Z | [
"python",
"arrays",
"numpy"
] | I came across the fact that `numpy` arrays are passed by reference at multiple places, but then when I execute the following code, why is there a difference between the behavior of `foo` and `bar`
```
import numpy as np
def foo(arr):
arr = arr - 3
def bar(arr):
arr -= 3
a = np.array([3, 4, 5])
foo(a)
print a ... | The first function calculates `(arr - 3)`, then assigns the local name `arr` to it, which doesn't affect the array data passed in. My guess is that in the second function, `np.array` overrides the `-=` operator, and operates in place on the array data. |
Does assigning another variable to a string make a copy or increase the reference count | 11,585,886 | 10 | 2012-07-20T19:35:19Z | 11,586,179 | 9 | 2012-07-20T19:57:54Z | [
"python"
] | On p.35 of "Python Essential Reference" by David Beazley, he first states:
> For immutable data such as strings, the interpreter aggressively
> shares objects between different parts of the program.
However, later on the same page, he states
> For immutable objects such as numbers and strings, this assignment
> effe... | An assignment in python never ever creates a copy (it is technically possible only if the assignment for a class member is redefined for example by using `__setattr__`, properties or descriptors).
So after
```
a = foo()
b = a
```
whatever was returned from `foo` has not been copied, and instead you have two variable... |
Can I use a variable string to refer to a list? | 11,585,921 | 4 | 2012-07-20T19:38:16Z | 11,585,989 | 11 | 2012-07-20T19:42:56Z | [
"python",
"arrays"
] | I have a list of stock prices in a dictionary and a list of their values. I want to go through the list to get the value of the stocks on each day but I'm having trouble resolving locations in a list when I'm using a variable to access the data.
Here's a example:
```
goog = [12,132,124,234,234]
msft = [432,23,234,54,... | Why not store your current lists as a dictionary instead?
Instead of:
```
goog = [12, 132, 124, 234, 234]
msft = [432, 23, 234, 54, 23]
```
Use:
```
stock_vals = { 'goog': [12, 132, 124, 234, 234], 'msft': [432, 23, 234, 54, 23] }
```
Now you can retrieve them using:
```
stock_vals[stock_name][day_index]
```
whe... |
PyGObject GTK+ 3 - Documentation? | 11,586,396 | 18 | 2012-07-20T20:16:58Z | 11,589,779 | 19 | 2012-07-21T05:37:27Z | [
"python",
"gtk",
"gtk3",
"pygobject",
"gobject"
] | PyGObject appears to have no real documentation. [This tutorial](http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html) is as close as it gets. I've been struggling all morning simply trying to find a description of the arguments accepted by the `Gtk.Window` constructor. It seems I can't do much reflection ... | I agree that this is a huge shortcoming of the PyGObject in it's current state. For those of us who have been using GTK+ for a while it's no problem, but, for new users it can be confusing.
Folks are working on a system to automatically generate the docs for languages other than C which is known as [GObject Introspect... |
PyGObject GTK+ 3 - Documentation? | 11,586,396 | 18 | 2012-07-20T20:16:58Z | 22,843,231 | 9 | 2014-04-03T16:11:07Z | [
"python",
"gtk",
"gtk3",
"pygobject",
"gobject"
] | PyGObject appears to have no real documentation. [This tutorial](http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html) is as close as it gets. I've been struggling all morning simply trying to find a description of the arguments accepted by the `Gtk.Window` constructor. It seems I can't do much reflection ... | The docs are located here:
<http://lazka.github.io/pgi-docs/api/Gtk_3.0/index.html>
The Gtk.Window arga (exactly what you have asked for) here:
<http://lazka.github.io/pgi-docs/api/Gtk_3.0/classes/Window.html>
Some interactive console solutions exist above, but I prefer the auto-complete one:
[How do I add tab compl... |
How can I create a tree for Huffman encoding and decoding? | 11,587,044 | 3 | 2012-07-20T21:17:10Z | 12,656,695 | 7 | 2012-09-29T21:37:26Z | [
"python",
"tree",
"encode",
"huffman-coding"
] | For my assignment, I am to do a encode and decode for huffman trees. I have a problem creating my tree, and I am stuck.
Don't mind the print statements - they are just for me to test and see what the output is when my function runs.
For the first for loop, I got all the values and index from the text file I used in m... | The Huffman algorithm in Wikipedia tells you exactly how to create the node tree, so your program can be based on that algorithm, or another like it. Here is a Python program with comments showing the corresponding wikipedia algorithm step. The test data is frequencies of the letters of the alphabet in English text.
O... |
Why doesn't var = [0].extend(range(1,10)) work in python? | 11,587,069 | 7 | 2012-07-20T21:19:56Z | 11,587,088 | 10 | 2012-07-20T21:21:37Z | [
"python",
"list"
] | I would think that if i did the following code in python
```
var = [0].extend(range(1,10))
```
then `var` would be a list with the values 0 - 9 in it.
What gives? | [**`list.extend`**](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) is an in-place method. It performs its action on the object itself and returns `None`.
This would work:
```
var = [0]
var.extend(range(1, 10))
```
Even better would be this:
```
var = list(range(10))
``` |
Issues with python-gevent and python-daemon | 11,587,164 | 3 | 2012-07-20T21:27:58Z | 11,687,342 | 7 | 2012-07-27T11:59:47Z | [
"python",
"daemon",
"gevent"
] | So I've been trying to make a process that runs a server in the background, and start it with a daemon process. So my code is:
```
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/foo.pid'
self.pid... | You hitting the problem of bad interaction between fork and epoll (or kqueue). Generally, it's hard to make epoll-based event loop to work reliably after fork and it's best to re-create a new event loop.
There a few ways to fix your problem:
* [Upgrade to gevent 1.0.](https://github.com/SiteSupport/gevent/downloads) ... |
How to handle AssertionError in Python and find out which line or statement it occurred on? | 11,587,223 | 18 | 2012-07-20T21:34:41Z | 11,587,247 | 28 | 2012-07-20T21:37:03Z | [
"python",
"assert"
] | I want to handle `AssertionError`s both to hide unnecessary parts of the stack trace from the user and to print a message as to why the error occurred and what the user should do about it.
**Is there any way to find out on which line or statement the `assert` failed within the `except` block?**
```
try:
assert Tr... | Use the [traceback](http://docs.python.org/library/traceback.html) module:
```
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = tracebac... |
Creating dummy variables in pandas for python | 11,587,782 | 13 | 2012-07-20T22:33:29Z | 11,589,000 | 10 | 2012-07-21T02:29:57Z | [
"python",
"pandas"
] | I'm trying to create a series of dummy variables from a categorical variable using pandas in python. I've come across the get\_dummies function, but whenever I try to call it I receive an error that the name is not defined.
Any thoughts or other ways to create the dummy variables would be appreciated.
**EDIT**: Since... | It's hard to infer what you're looking for from the question, but my best guess is as follows.
If we assume you have a DataFrame where some column is 'Category' and contains integers (or otherwise unique identifiers) for categories, then we can do the following.
Call the DataFrame `dfrm`, and assume that for each row... |
Creating dummy variables in pandas for python | 11,587,782 | 13 | 2012-07-20T22:33:29Z | 23,925,229 | 15 | 2014-05-29T03:26:56Z | [
"python",
"pandas"
] | I'm trying to create a series of dummy variables from a categorical variable using pandas in python. I've come across the get\_dummies function, but whenever I try to call it I receive an error that the name is not defined.
Any thoughts or other ways to create the dummy variables would be appreciated.
**EDIT**: Since... | When I think of dummy variables I think of using them in the context of OLS regression, and I would do something like this:
```
import numpy as np
import pandas as pd
import statsmodels.api as sm
my_data = np.array([[5, 'a', 1],
[3, 'b', 3],
[1, 'b', 2],
[3,... |
How to construct such a functional-programming tool in Python? | 11,588,263 | 7 | 2012-07-20T23:43:41Z | 11,588,287 | 15 | 2012-07-20T23:46:36Z | [
"python",
"function",
"recursion",
"functional-programming"
] | I want a function named `times()`, in order to make:
`times(func,2)` equivalent to `lambda x:func(func(x))`
and `times(func,5)` equivalent to `lambda x:func(func(func(func(func(x)))))`
Is there such a tool in Python? What would the code looks like if I want to write it by myself?
Thanks! | I'd suggest to call this `power()`, since this is actually the `n`th power of a function. There is no such thing in the standard library, but you can easily implement it yourself:
```
def power(f, n):
def wrapped(x):
for i in range(n):
x = f(x)
return x
return wrapped
``` |
python late binding - dynamically put locals in scope | 11,588,289 | 4 | 2012-07-20T23:47:18Z | 11,588,427 | 8 | 2012-07-21T00:12:02Z | [
"python",
"functional-programming",
"monads"
] | i have a function, m\_chain, which refers to two functions `bind` and `unit` which are not defined. i want to wrap this function in some context which provides definitions for these functions - you can think of them as interfaces for which i want to dynamically provide an implementation.
```
def m_chain(*fns):
"""... | In Python, you can write all the code you want that refers to stuff that doesn't exist; to be specific, you can write code that refers to names that do not have values bound to them. And you can compile that code. The only problem will happen at run time, if the names still don't have values bound to them.
Here is a c... |
How can I create a new model entity, and then read it immediately after? | 11,590,993 | 5 | 2012-07-21T09:21:47Z | 11,591,962 | 9 | 2012-07-21T11:56:08Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | My question is, what is the best way to create a new model entity, and then read it immediately after. For example,
```
class LeftModel(ndb.Model):
name = ndb.StringProperty(default = "John")
date = ndb.DateTimeProperty(auto_now_add=True)
class RightModel(ndb.Model):
left_model = ndb.KeyProperty(kind=Left... | Why are you trying to fetch the object via a query immediately after you have performed the `put()`.
You should use the `new_left` you just created and immediately assign it to the new\_right as in `new_right.left_model = current_left.key`
The reason you can not query immediately is because HRD uses an eventual consi... |
python - How select.select() works? | 11,591,054 | 22 | 2012-07-21T09:34:20Z | 11,591,492 | 15 | 2012-07-21T10:44:18Z | [
"python",
"select"
] | ## Background:
I'm familiar with `select()` C function. I've been using this function for many purpouses. Most of them, if not all, for reading and writting to pipes, files, etc... I must say that I've never used the error list, but this is not involved in the key question.
## Question:
Does python `select()` behave... | Python's `select()` gets passed through as a `select()` system call as you are expecting, but the problem you have with it blocking is a different issue, probably relating to buffering. Just to satify yourself that `select()` is doing the right thing, try reading/writing a file on the file system rather than using a sp... |
Why does Python's Queue return an approximate size in qsize()? | 11,591,957 | 6 | 2012-07-21T11:54:37Z | 11,591,980 | 21 | 2012-07-21T11:58:52Z | [
"python",
"multithreading"
] | In the [doc](http://docs.python.org/library/queue.html#queue-objects) of qsize() it says: Return the approximate size of the queue.
Why can't it just return an exact size of this Queue? I understand the Queue may be accessed by multiple threads, but at the moment I call the function I think it's still possible to retu... | It is precisely because there are other threads accessing it. By the time you try to use the size you get back from qsize(), the queue could have changed. It would be better if the documentation read something like this:
> Returns the size of the queue. Note that in a multi-threaded environment, the size can change at... |
Check if a string is hexadecimal | 11,592,261 | 16 | 2012-07-21T12:39:22Z | 11,592,279 | 34 | 2012-07-21T12:41:50Z | [
"python",
"hex"
] | I know the easiest way is using a [regular expression](http://en.wikipedia.org/wiki/Regular_expression), but I wonder if there are other ways to do this check.
Why do I need this? I am writing a Python script that reads text messages (SMS) from a [SIM](https://en.wikipedia.org/wiki/Subscriber_identity_module) card. In... | **(1)** Using [int()](http://docs.python.org/library/functions.html#int) works nicely for this, and Python does all the checking for you :)
```
int('00480065006C006C006F00200077006F0072006C00640021', 16)
6896377547970387516320582441726837832153446723333914657L
```
will work. In case of failure you will receive a `Val... |
Check if a string is hexadecimal | 11,592,261 | 16 | 2012-07-21T12:39:22Z | 11,592,292 | 13 | 2012-07-21T12:43:41Z | [
"python",
"hex"
] | I know the easiest way is using a [regular expression](http://en.wikipedia.org/wiki/Regular_expression), but I wonder if there are other ways to do this check.
Why do I need this? I am writing a Python script that reads text messages (SMS) from a [SIM](https://en.wikipedia.org/wiki/Subscriber_identity_module) card. In... | You can:
1. test whether the string contains only hexadecimal digits (0â¦9,Aâ¦F)
2. try to convert the string to integer and see whether it fails.
Here is the code:
```
import string
def is_hex(s):
hex_digits = set(string.hexdigits)
# if s is long, then it is faster to check against a set
return all... |
What is the pythonic way to implement a css parser/replacer | 11,592,347 | 3 | 2012-07-21T12:53:43Z | 11,685,846 | 9 | 2012-07-27T10:18:25Z | [
"python"
] | I want to implement a script that reads a CSS file and makes meaningful changes to it (adding/removing/replacing lines/words etc.). The basic logic is implement an RTL (right-to-left) transformation.
I could think of quite a few approaches to it:
* file reader - read a line, analyze it and make the needed changes to ... | If you want something "quick and dirty" there are many interesting ways to do this. (As you said: line-by-line, regular expressions, â¦)
But if you want to do it "right" (correct on all kinds of inputs) youâll need a real parser based on the official [CSS tokenization and grammar](http://www.w3.org/TR/CSS21/syndata... |
django createsuperuser not working | 11,593,556 | 7 | 2012-07-21T15:42:18Z | 11,593,861 | 13 | 2012-07-21T16:22:15Z | [
"python",
"django",
"eclipse"
] | # .bash\_profile
```
export PATH="/Applications/MAMP/bin:/usr/local/bin:/usr/local/sbin:usr/local/$
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$DYLD_LIBRARY_PATH"
export LANG="en_US.UTF-8"
```
# .profile
```
export PATH="/Applications/MAMP/bin:/usr/local/bin:/usr/local/sbin:usr/local/my$
export DYLD_LIBRARY_PAT... | You are seeing this because you don't have locale set on your system. You need to set it in order to create superuser, it's known and reported "bug" already.
see:
<https://code.djangoproject.com/ticket/17649>
Assuming that you're using linux you can fix that bug with
```
export LANG="en_US.UTF-8"
```
You use this i... |
django createsuperuser not working | 11,593,556 | 7 | 2012-07-21T15:42:18Z | 12,840,641 | 12 | 2012-10-11T13:26:57Z | [
"python",
"django",
"eclipse"
] | # .bash\_profile
```
export PATH="/Applications/MAMP/bin:/usr/local/bin:/usr/local/sbin:usr/local/$
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$DYLD_LIBRARY_PATH"
export LANG="en_US.UTF-8"
```
# .profile
```
export PATH="/Applications/MAMP/bin:/usr/local/bin:/usr/local/sbin:usr/local/my$
export DYLD_LIBRARY_PAT... | The accepted answer didn't work for me, so I keep searching around and found [this](http://stackoverflow.com/a/10894385/359248). It works for me. For sake of time saving I copy paste the two lines here. Enter this in terminal:
```
$ LC_CTYPE=en_US.UTF-8
$ LC_ALL=en_US.UTF-8
```
Note: I use Mac OS 10.7 if that's relev... |
Jquery ajax post request not working | 11,596,065 | 4 | 2012-07-21T21:42:49Z | 11,596,126 | 11 | 2012-07-21T21:54:32Z | [
"javascript",
"jquery",
"python",
"pyramid"
] | I have a simple form submission with ajax, but it keeps giving me an error. All the error says is "error". No code, no description. No nothing, when I alert it when it fails.
Javascript with jQuery:
```
$(document).ready(function(){
$(".post-input").submit(function(){
var postcontent = $(".post-f... | According to [jQuery](http://api.jquery.com/jQuery.post/) documentation, you must declare the data type:
```
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
```
Also, looking at your server-side code, you don't actually want to post JSON formatted data. This `{"post-for... |
How Does Python Memory Management Work? | 11,596,371 | 2 | 2012-07-21T22:34:26Z | 11,596,410 | 10 | 2012-07-21T22:40:57Z | [
"python"
] | Okay, I got this concept of a class that would allow other classes to import classes on as basis versus if you use it you must import it. How would I go about implementing it? Or, does the Python interpreter already do this in a way? Does it destroy classes not in use from memory, and how so?
I know C++/C are very mem... | Python -- like C#, Java, Perl, Ruby, Lua and many other languages -- uses garbage collection rather than manual memory management. You just freely create objects and the language's memory manager periodically (or when you specifically direct it to) looks for any objects that are no longer referenced by your program.
S... |
I don't understand encode and decode in Python (2.7.3) | 11,596,623 | 6 | 2012-07-21T23:30:09Z | 11,596,676 | 16 | 2012-07-21T23:42:16Z | [
"python",
"string",
"unicode",
"decode",
"encode"
] | I tried to understand by myself `encode` and `decode` in Python but nothing is really clear for me.
1. `str.encode([encoding,[errors]])`
2. `str.decode([encoding,[errors]])`
First, I don't understand the need of the "encoding" parameter in these two functions.
What is the output of each function, its encoding? What ... | It's a little more complex in Python 2 (compared to Python 3), since it conflates the concepts of 'string' and 'bytestring' quite a bit, but see [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets](http://www.joelonsoftware.com/articles/Unicode.html). Essenti... |
I don't understand encode and decode in Python (2.7.3) | 11,596,623 | 6 | 2012-07-21T23:30:09Z | 11,596,770 | 11 | 2012-07-22T00:04:50Z | [
"python",
"string",
"unicode",
"decode",
"encode"
] | I tried to understand by myself `encode` and `decode` in Python but nothing is really clear for me.
1. `str.encode([encoding,[errors]])`
2. `str.decode([encoding,[errors]])`
First, I don't understand the need of the "encoding" parameter in these two functions.
What is the output of each function, its encoding? What ... | My presentation from PyCon, [Pragmatic Unicode, or, How Do I Stop The Pain](http://bit.ly/unipain) covers all of these details.
Briefly, Unicode strings are sequences of integers called code points, and bytestrings are sequences of bytes. An encoding is a way to represent Unicode code points as a series of bytes. So `... |
Flask not serving pictures | 11,596,777 | 12 | 2012-07-22T00:06:03Z | 11,598,368 | 11 | 2012-07-22T07:06:05Z | [
"python",
"html",
"flask"
] | I created a small Flask app for the purpose of processing and presenting data for my local consumption on my local machine. My Flask app processes data in a subfolder and then opens a webpage to display the processed data. Everything looks great except that images are not being served. For example the resulting HTMl so... | The Flask application defaults the files where it attempts to serve static files as the "static" path in the root directory for the application. Thus, if you run your program in...
`C:\Users\username\Desktop\MyApp`
the static folder will be
`C:\Users\username\Desktop\MyApp\Static`
Thus, when attempting to serve
`/... |
Installing PyCrypto on Ubuntu - fatal error on build | 11,596,839 | 41 | 2012-07-22T00:17:37Z | 11,596,845 | 112 | 2012-07-22T00:18:55Z | [
"python",
"pycrypto"
] | Having looked at other similar threads, I still can't get pycrypto running.
I'm trying to get it working on my Ubuntu laptop - but I couldn't manage it on my Windows PC either.
I downloaded pycrypto-2.6, extracted it, and ran
```
python setup.py build
```
but then this happened
```
warning: GMP or MPIR library... | You need to install the Python development files. I believe this will do it:
```
sudo apt-get install python-dev
``` |
Installing PyCrypto on Ubuntu - fatal error on build | 11,596,839 | 41 | 2012-07-22T00:17:37Z | 21,566,418 | 14 | 2014-02-05T00:31:46Z | [
"python",
"pycrypto"
] | Having looked at other similar threads, I still can't get pycrypto running.
I'm trying to get it working on my Ubuntu laptop - but I couldn't manage it on my Windows PC either.
I downloaded pycrypto-2.6, extracted it, and ran
```
python setup.py build
```
but then this happened
```
warning: GMP or MPIR library... | On Ubuntu, I needed some other packages for it to succeed:
```
apt-get install autoconf g++ python2.7-dev
pip install pycrypto
``` |
Is it best to query by keys_only=True then get_multi or just full query? | 11,596,869 | 9 | 2012-07-22T00:24:30Z | 11,603,353 | 9 | 2012-07-22T19:31:11Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I am using NDB with python 2.7 with threadsafe mode turned on.
I understand that querying for entities with NDB does not use local cache or memcache but goes straight to the datastore unlike getting by key name. (The rest of the question might be redundant if this premise is not correct.)
Therefore would a good parad... | This has been extensively researched. See <http://code.google.com/p/appengine-ndb-experiment/issues/detail?id=118> |
How do I create a Python socket server that listens on a file descriptor? | 11,597,284 | 6 | 2012-07-22T02:05:57Z | 11,597,574 | 10 | 2012-07-22T03:28:41Z | [
"python",
"sockets",
"node.js",
"ipc"
] | I am trying to make a Javascript (Nodejs) app communicate with a Python app.
I got [something working](https://github.com/thlorenz/readarepo-zip/blob/master/highlight/pygments/server/pygments-service.py) using a socket bound to my localhost and a specific port.
To make things simpler (e.g., when deploying to environm... | I modified the [this nice example](http://www.velvetcache.org/2010/06/14/python-unix-sockets) a bit (e.g., python server has to listen on TCP instead UDP socket to be compatible with nodejs client.
I'm posting python server and nodejs client code here for reference:
### Python Server:
```
import socket
import os, os... |
setting spacing between grouped bar plots in matplotlib | 11,597,785 | 8 | 2012-07-22T04:30:12Z | 11,603,806 | 13 | 2012-07-22T20:37:29Z | [
"python",
"numpy",
"plot",
"matplotlib",
"scipy"
] | I'm trying to make a grouped bar plot in matplotlib, following the example in the gallery. I use the following:
```
import matplotlib.pyplot as plt
plt.figure(figsize=(7,7), dpi=300)
xticks = [0.1, 1.1]
groups = [[1.04, 0.96],
[1.69, 4.02]]
group_labels = ["G1", "G2"]
num_items = len(group_labels)
ind = aran... | The trick to both of your questions is understanding that bar graphs in Matplotlib expect each series (G1, G2) to have a total width of "1.0", counting margins on either side. Thus, it's probably easiest to set margins up and then calculate the width of each bar depending on how many of them there are per series. In yo... |
Why does Python allow a trailing comma in list? | 11,597,901 | 39 | 2012-07-22T05:11:30Z | 11,597,907 | 17 | 2012-07-22T05:14:29Z | [
"python",
"list",
"syntax",
"comma",
"trailing"
] | I am curious why in Python a trailing comma in a list is valid syntax, and it seems that Python simply ignores it:
```
>>> ['a','b',]
['a', 'b']
```
It makes sense when its a tuple since `('a')` and `('a',)` are two different things, but in lists? | It's a common syntactical convention to allow trailing commas in an array, languages like C and Java allow it, and Python seems to have adopted this convention for its list data structure. It's particularly useful when generating code for populating a list: just generate a sequence of elements and commas, no need to co... |
Why does Python allow a trailing comma in list? | 11,597,901 | 39 | 2012-07-22T05:11:30Z | 11,597,911 | 65 | 2012-07-22T05:15:53Z | [
"python",
"list",
"syntax",
"comma",
"trailing"
] | I am curious why in Python a trailing comma in a list is valid syntax, and it seems that Python simply ignores it:
```
>>> ['a','b',]
['a', 'b']
```
It makes sense when its a tuple since `('a')` and `('a',)` are two different things, but in lists? | The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.
Changing:
```
s = ['manny',
'mo',
'jack',
]
```
to:
```
s = ['manny',
'mo',
'jack',
'roger',
]
```
involves only a one-line change in the diff:
```
s = ['manny',
'mo',
... |
Why does Python allow a trailing comma in list? | 11,597,901 | 39 | 2012-07-22T05:11:30Z | 11,597,922 | 14 | 2012-07-22T05:18:53Z | [
"python",
"list",
"syntax",
"comma",
"trailing"
] | I am curious why in Python a trailing comma in a list is valid syntax, and it seems that Python simply ignores it:
```
>>> ['a','b',]
['a', 'b']
```
It makes sense when its a tuple since `('a')` and `('a',)` are two different things, but in lists? | It helps to eliminate a certain kind of bug. It's sometimes clearer to write lists on multiple lines.
But in, later maintenace you may want to rearrange the items.
```
l1 = [
1,
2,
3,
4,
5
]
# Now you want to rearrange
l1 = [
1,
2,
3,
5
... |
Python - manipulating lists to create another list | 11,599,256 | 4 | 2012-07-22T09:51:47Z | 11,599,261 | 10 | 2012-07-22T09:53:04Z | [
"python",
"list"
] | I have a number of lists that are of equal length, say 4, but this can change. What I want to do is combine these lists, so that the first item of each list, item[0], is combined to form a new list. Similarly with item[1], item[2] etc. This seems simple enough, but how do I make sure that the list names (i.e. slide1) a... | Very simple:
```
lst = zip(list1, list2, list3)
print(lst[0])
>>> ('slide1', 1, 'banana')
# in case you need a list, not a tuple
slide1 = list(lst[0])
``` |
Making it Pythonic: create a sqlite3 database if it doesn't exist? | 11,599,263 | 3 | 2012-07-22T09:53:26Z | 11,599,344 | 16 | 2012-07-22T10:05:05Z | [
"python",
"sqlite3"
] | I wrote a Python script which initializes an empty database if it doesn't exist.
```
import os
if not os.path.exists('Database'):
os.makedirs('Database')
os.system('sqlite3 Database/testDB.db ";"')
# rest of the script...
```
Can I do this in a more Pythonic fashion, with a try-except, or is this kind of co... | I think you can do it like that:
```
import sqlite3
conn = sqlite3.connect('Database/testDB.db')
```
This should connect to your database and create it in case that it doesn't exist. I'm not sure this is the most pythonic way, but it does use the `sqlite3` module instead of the `sqlite3` command. |
What are the limitations of Python on Android? | 11,600,364 | 23 | 2012-07-22T12:38:47Z | 11,602,162 | 17 | 2012-07-22T16:51:39Z | [
"java",
"android",
"python",
"sl4a"
] | I am getting ready to start a little Android development and need to choose a language. I know Python but would have to learn Java. I'd like to know from those of you who are using Python on Android what the limitations are. Also, are there any benefits over Java? | I investigated this recently for similar reasons. My conclusions were that I could not use Python to develop a native-looking application, which is what I wanted at the time. Specifically:
* Python can't receive callbacks from the Java UI classes, so you can't use any native Java UI elements such as ListView, etc. Onl... |
What are the limitations of Python on Android? | 11,600,364 | 23 | 2012-07-22T12:38:47Z | 11,820,485 | 21 | 2012-08-05T22:11:42Z | [
"java",
"android",
"python",
"sl4a"
] | I am getting ready to start a little Android development and need to choose a language. I know Python but would have to learn Java. I'd like to know from those of you who are using Python on Android what the limitations are. Also, are there any benefits over Java? | Most of the points mentioned by Andrew stand, I just wanted to mention that python can be and is used for full fledged Apps published on GooglePlay and even iOS. I can't speak for other frameworks but here are some examples of Apps published using Kivy.
1. Process Craft [Google Play](https://play.google.com/store/apps... |
Web application that uses scikit-learn | 11,600,471 | 10 | 2012-07-22T12:55:58Z | 11,600,891 | 7 | 2012-07-22T13:59:46Z | [
"python",
"web-applications",
"scikit-learn"
] | I have locally trained a [sklearn](http://scikits.appspot.com/scikit-learn) classifier and I have to create a simple web application that demonstrate its use. I'm a complete noob on web app development and I don't want to waste hours on creating a web app using a framework that doesn't support the modules I'm using.
1... | If this is just for a demo, train your classifier offline, pickle the model and then use a simple python web framework such as [flask](http://flask.pocoo.org/) or [bottle](http://bottlepy.org/docs/dev/) to unpickle the model at server startup time and call the predict function in an HTTP request handler.
django is a f... |
Algorithm (prob. solving) achieving fastest runtime | 11,600,628 | 17 | 2012-07-22T13:22:33Z | 11,647,600 | 10 | 2012-07-25T10:21:04Z | [
"python",
"algorithm"
] | For an algorithm competition training (not homework) we were given this question from a past year. Posted it to this site because the other site required a login.
This is the problem:
<http://pastehtml.com/view/c5nhqhdcw.html>
Image didn't work so posted it here: 
It has to run... | Suppose the list `houses` is composed of pairs `(x,pop)` with `0 <= x < 4*L` the location and `pop` the population.
The objective function, which we want to maximize, is
```
def revenue(i):
return sum(pop * min((i-j)%(4*L), 4*L - (i-j)%(4*L)) for j,pop in houses)
```
The naive algorithm O(*LN*) algorithm is simp... |
Algorithm (prob. solving) achieving fastest runtime | 11,600,628 | 17 | 2012-07-22T13:22:33Z | 11,654,257 | 9 | 2012-07-25T16:21:26Z | [
"python",
"algorithm"
] | For an algorithm competition training (not homework) we were given this question from a past year. Posted it to this site because the other site required a login.
This is the problem:
<http://pastehtml.com/view/c5nhqhdcw.html>
Image didn't work so posted it here: 
It has to run... | Here is a less mathematically inclined solution that works in `O(n)`.
Let us partition the houses (indexing starts at 0) into two disjoints sets:
* `F`, "front", where people walk CCW to the house
* `B`, "back", where people walk CW to the house
and a single house `p` that marks the current position where the plant ... |
Parse query part from url | 11,600,681 | 11 | 2012-07-22T13:30:00Z | 11,600,752 | 36 | 2012-07-22T13:41:04Z | [
"python",
"urlparse"
] | I want to parse query part from url, this is my code to do this:
```
>>> from urlparse import urlparse, parse_qs
>>> url = '/?param1¶m2=2'
>>> parse_qs(urlparse(url).query)
>>> {'param2': ['23']}
```
This code looks good, but "parse\_qs" method loses query parameters like "param1" or "param1=". Can I parse query ... | You want:
```
from urlparse import parse_qs, urlparse
parse_qs(urlparse(url).query, keep_blank_values=True)
# {'param2': ['2'], 'param1': ['']}
``` |
why does updating a dict that was appended to a list change the list? | 11,600,824 | 4 | 2012-07-22T13:51:08Z | 11,600,892 | 11 | 2012-07-22T14:00:16Z | [
"python",
"arrays",
"dictionary"
] | My code will be more clear I think-
```
someList = list()
foo = {'a':'b'}
someList.append(foo)
print someList
>>> [{'a':'b'}]
defaultbazz = {'a':2, 'b':'t', 'c':'gg'}
for k, v in defaultbazz.iteritems():
foo[k] = v
print someList
>>> [{'a': 2, 'c': 'gg', 'b': 't'}]
```
Shouldn't the last print be `[{'a':'b'}]`?... | It looks like you are expecting your dict to be copied when you add it to a list or assign it to a new variable, but that is not how Python operates. If you assign a dict -- actually, if you assign any object -- you are not creating a new object, but instead you are simply giving your object a new name. (An object can ... |
Python function for capping a string to a maximum length | 11,602,386 | 10 | 2012-07-22T17:22:24Z | 11,602,405 | 20 | 2012-07-22T17:24:39Z | [
"python",
"string"
] | Is there a function in Python, built-in or in the standard library, for capping a string to a certain length, and if the length was exceeded, append three dots (...) after it?
For example:
```
>>> hypothetical_cap_function("Hello, world! I'm a string", 10)
"Hello, ..."
>>> hypothetical_cap_function("Hello, world! I'm... | ```
def cap(s, l):
return s if len(s)<=l else s[0:l-3]+'...'
``` |
Installing mod_wsgi on WAMP server running on Windows 7 | 11,602,653 | 10 | 2012-07-22T17:57:20Z | 11,602,894 | 21 | 2012-07-22T18:28:57Z | [
"python",
"apache",
"windows-7",
"wamp",
"mod-wsgi"
] | I downloaded mod\_wsgi from the [following location](http://www.lfd.uci.edu/~gohlke/pythonlibs/) for apache 2.2 and python 2.7 (64bit). (I'm trying to get django to run on my computer).
Whenever I add the following line:
```
LoadModule wsgi_module modules/mod_wsgi.so
```
Apache fails to start up. Can anyone tell me ... | These are the following things you need to do to setup Apache for Django. I assume you are using Python 2.7 (**32-bit**) on Windows (**32-bit**) with WAMP server (**32-bits**) installed.
1. [Download](http://code.google.com/p/modwsgi/downloads/list) mod\_wsgi-win32-ap22py27-3.3.so. Or download your respective .so comp... |
How to detect if a cell is empty when reading Excel files using the xlrd library? | 11,603,009 | 6 | 2012-07-22T18:43:18Z | 11,603,764 | 13 | 2012-07-22T20:30:04Z | [
"python",
"excel",
"xlrd"
] | I handle Excel files using the functions **row\_values** and **col\_values**:
```
import xlrd
workbook = xlrd.open_workbook( filename )
sheet_names = workbook.sheet_names()
for sheet_name in sheet_names:
sheet = workbook.sheet_by_name( sheet_name )
# ...
row_values = sheet.row_values( rownum )
# ...
col... | You could be explicit and check that `sheet.cell_type(rowno, colno) in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK)` but the docs state the value will be `u''` where those are the case anyway.
Instead of using `row_values`, you could also use `row(n)` which returns a list of `Cell` objects which have `.value` and `.cell_t... |
Allowing resizing window pyGame | 11,603,222 | 10 | 2012-07-22T19:11:42Z | 11,604,661 | 7 | 2012-07-22T22:59:58Z | [
"python",
"pygame"
] | I am trying to allow resizing for this app, I put the RESIZABLE flag, but when I try to resize, it messes up! Try my code.
It is a grid program, when the window resizes I want the grid to also resize/shrink.
```
import pygame,math
from pygame.locals import *
# Define some colors
black = ( 0, 0, 0)
white =... | You are not updating your width, height, or size when the window changes.
From the docs: <http://www.pygame.org/docs/ref/display.html>
> If the display is set with the pygame.RESIZABLE flag,
> pygame.VIDEORESIZE events will be sent when the user adjusts the
> window dimensions.
You can get the new `size, w, h` from ... |
Collapse run-on whitespace | 11,603,241 | 4 | 2012-07-22T19:13:44Z | 11,603,248 | 13 | 2012-07-22T19:14:53Z | [
"python",
"regex",
"whitespace"
] | How would I collapse run-on whitespace in python?
```
"a b c d e" --> "a b c d e"
``` | Assuming
```
s = 'a b c d e'
```
then
```
' '.join(s.split())
'a b c d e'
```
will give you the specified output.
This works by using [split()](http://docs.python.org/library/stdtypes.html?highlight=split#str.split) to break the string into into a list of individual characters `['a', 'b', 'c', 'd', 'e']` ... |
Running python script in Blender | 11,604,548 | 15 | 2012-07-22T22:38:12Z | 11,604,587 | 16 | 2012-07-22T22:44:58Z | [
"python",
"blender"
] | I installed Blender 2.6 and I'm trying to run a script called drawcar.py (Which uses PyOpenGL)
I looked around the documentation for importing a script and could only access Blender's python console.
How do I run drawcar.py from the Linux terminal with Blender? | 1. Open a Text Editor view in Blender.
2. Press Alt + O, or go to Text>Open Text Block and open the .py file
3. Then simply press Run script :D |
Running python script in Blender | 11,604,548 | 15 | 2012-07-22T22:38:12Z | 12,683,160 | 16 | 2012-10-02T00:54:34Z | [
"python",
"blender"
] | I installed Blender 2.6 and I'm trying to run a script called drawcar.py (Which uses PyOpenGL)
I looked around the documentation for importing a script and could only access Blender's python console.
How do I run drawcar.py from the Linux terminal with Blender? | You can also execute the following code in the python console to execute an external script without opening it up in the text editor:
```
filename = "/full/path/to/myscript.py"
exec(compile(open(filename).read(), filename, 'exec'))
```
The above code comes from the following link:
[Blender - Tips and Tricks](http://... |
Add command line arguments with flags in Python3 | 11,604,653 | 4 | 2012-07-22T22:57:32Z | 11,604,777 | 18 | 2012-07-22T23:18:41Z | [
"python",
"command-line",
"python-3.x",
"arguments"
] | I have to input the parameters from the command line i.e username, password and database name. I know how to do that without using flags, by using 'sys.argv' (like below).
```
##Test.py
hostname = str(sys.argv[1])
username = str(sys.argv[2])
password = str(sys.argv[3])
def ConnecttoDB():
try:
con=sql.conn... | The python 3 library includes 3 modules for parsing the command line thus nothing extra to add to your setup.
The one you should use is [argparse](http://docs.python.org/py3k/library/argparse.html)
```
import argparse
parser = argparse.ArgumentParser()
#-db DATABSE -u USERNAME -p PASSWORD -size 20
parser.add_argumen... |
Is there a way to do more work after a return statement? | 11,604,699 | 6 | 2012-07-22T23:05:08Z | 11,604,754 | 9 | 2012-07-22T23:15:27Z | [
"python"
] | I was a bit curious if I could do more work in a function after returning a result. Basically I'm making a site using the pyramid framework(which is simply coding in python) after I process the inputs I return variables to render the page but sometimes I want to do more work after I render the page.
For example, you c... | Why don't you use a [contextmanager](http://docs.python.org/library/contextlib.html#contextlib.contextmanager)? It basically does exactly what you want.
Here's the canonical example from the Python docs.
```
from contextlib import contextmanager
@contextmanager
def tag(name):
print "<%s>" % name
yield
pr... |
Using "and" in return | 11,604,808 | 5 | 2012-07-22T23:25:17Z | 11,604,833 | 11 | 2012-07-22T23:29:46Z | [
"python",
"methods",
"python-2.7",
"return"
] | I'm taking Web Application Engineering course on Udacity. I noticed that the instructor use `and` operator in `return` statement in his validation method. And I didn't understand how it is possible to return 2 arguments. I think, it may be something like `if` statement. Could anyone explain what it actually is?
Here i... | The `and` operator evaluates whether both of its arguments are tru-ish, but in a slightly surprising way: First it examines its left argument. If it is truish, then it returns its right argument. If the left argument is falsish, then it returns the left argument.
So the last line in your code:
```
return username and... |
Python Remove SOME duplicates from a list while maintaining order? | 11,606,112 | 3 | 2012-07-23T03:26:38Z | 11,606,243 | 8 | 2012-07-23T03:47:43Z | [
"python",
"list",
"set",
"duplicates"
] | I want to remove certain duplicates in my python list.
I know there are ways to remove all duplicates, but I wanted to remove only consecutive duplicates, while maintaining the list order.
For example, I have a list such as the following:
```
list1 = [a,a,b,b,c,c,f,f,d,d,e,e,f,f,g,g,c,c]
```
However, I want to remov... | Not completely sure if `c` and `f` are special cases, or if you want to compress consecutive duplicates only. If it is the latter, you can use `itertools.groupby()`:
```
>>> import itertools
>>> list1
['a', 'a', 'b', 'b', 'c', 'c', 'f', 'f', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'c', 'c']
>>> [k for k, g in itertool... |
Which is a better way to check request conditions? | 11,608,041 | 2 | 2012-07-23T07:24:29Z | 11,608,245 | 8 | 2012-07-23T07:40:47Z | [
"python",
"django",
"request"
] | Many times in open source codes of django python , I have seen the scenario like this
```
if request.META and 'HTTP_REFERER' in request.META:
```
Similarly I have seen these two if conditions also
```
if request.POST and 'next' in request.POST:
if request.GET and 'next' in request.GET:
```
I believe that only one c... | It can be acheived only by checking
`request.META.get('HTTP_REFERER')`
and
`request.REQUEST.get('next')`
instead of checking it for *`request.POST`* or *`request.GET`* |
Is it possible to add a where clause with list comprehension? | 11,608,238 | 13 | 2012-07-23T07:40:21Z | 11,608,419 | 9 | 2012-07-23T07:54:33Z | [
"python",
"list-comprehension"
] | Consider the following list comprehension
```
[ (x,f(x)) for x in iterable if f(x) ]
```
This filters the iterable based a condition `f` and returns the pairs of `x,f(x)`. The problem with this approach is `f(x)` is calculated twice.
It would be great if we could write like
```
[ (x,fx) for x in iterable if fx where... | You seek to have `let`-statement semantics in python list comprehensions, whose scope is available to both the `___ for..in`(map) and the `if ___`(filter) part of the comprehension, and whose scope depends on the `..for ___ in...`.
---
**Your solution, modified:**
Your (as you admit unreadable) solution of `[ (x,fx) ... |
Is it possible to add a where clause with list comprehension? | 11,608,238 | 13 | 2012-07-23T07:40:21Z | 11,609,666 | 9 | 2012-07-23T09:22:01Z | [
"python",
"list-comprehension"
] | Consider the following list comprehension
```
[ (x,f(x)) for x in iterable if f(x) ]
```
This filters the iterable based a condition `f` and returns the pairs of `x,f(x)`. The problem with this approach is `f(x)` is calculated twice.
It would be great if we could write like
```
[ (x,fx) for x in iterable if fx where... | There is no `where` statement but you can "emulate" it using `for`:
```
a=[0]
def f(x):
a[0] += 1
return 2*x
print [ (x, y) for x in range(5) for y in [f(x)] if y != 2 ]
print "The function was executed %s times" % a[0]
```
Execution:
```
$ python 2.py
[(0, 0), (2, 4), (3, 6), (4, 8)]
The function was exec... |
How to decide when to introduce a new type instead of using list or tuple? | 11,609,027 | 5 | 2012-07-23T08:38:16Z | 11,609,287 | 8 | 2012-07-23T08:56:10Z | [
"python"
] | I like to do some silly stuff with python like solving programming puzzles, writing small scripts etc. Each time at a certain point I'm facing a dilemma whether I should create a new class to represent my data or just use quick and dirty and go with all values packed in a list or tuple. Due to extreme laziness and pers... | Are you aware of [`collections.namedtuple`](http://docs.python.org/dev/library/collections.html?highlight=namedtuple#collections.namedtuple)? ([since 2.6](http://docs.python.org/library/collections.html?highlight=namedtuple#collections.namedtuple))
```
def getLocation(stuff):
return collections.namedtuple('Point',... |
Flatten Sequence With Boolean Expression Generator | 11,609,393 | 3 | 2012-07-23T09:03:25Z | 11,609,426 | 7 | 2012-07-23T09:05:36Z | [
"python",
"list-comprehension"
] | I am looking for a generator that will flatten a sequence of tuples based on a Boolean expression. My data looks like this:
```
my_data = ((3, 4), (None, 4), (5, 8), (None, 1), (None, 9)...)
```
What I'd like to do is to flatten this into a one dimensional generator of numbers where I take the first item in each tupl... | ```
(x[0] or x[1] for x in my_data)
```
or alternatively,
```
(x or y for x,y in my_data)
``` |
Slow performance of POS tagging. Can I do some kind of pre-warming? | 11,610,076 | 10 | 2012-07-23T09:45:35Z | 11,622,678 | 18 | 2012-07-24T00:55:06Z | [
"python",
"nltk"
] | I am using NLTK to POS-tag hundereds of tweets in a web request. As you know, Django instantiates a request handler for each request.
I noticed this: for a request (~200 tweets), the first tweet needs ~18 seconds to tag, while all subsequent tweets need ~120 milliseconds to tag. What can I do to speed up the process?
... | Those first 18 seconds are the POS tagger being unpickled from disk into RAM. If you want to get around this, load the tagger yourself outside of a request function.
```
import nltk.data, nltk.tag
tagger = nltk.data.load(nltk.tag._POS_TAGGER)
```
And then replace `nltk.pos_tag` with `tagger.tag`.
The tradeoff is that... |
Slow performance of POS tagging. Can I do some kind of pre-warming? | 11,610,076 | 10 | 2012-07-23T09:45:35Z | 33,692,061 | 14 | 2015-11-13T11:47:20Z | [
"python",
"nltk"
] | I am using NLTK to POS-tag hundereds of tweets in a web request. As you know, Django instantiates a request handler for each request.
I noticed this: for a request (~200 tweets), the first tweet needs ~18 seconds to tag, while all subsequent tweets need ~120 milliseconds to tag. What can I do to speed up the process?
... | As stated previously, NLTK unpickles every time is you use the standard pos\_tag method. For NLTK 3.1, assuming you're happy with the NLTK's default tagger (PerceptronTagger) then the following method works for me:
First load the tagger:
```
from nltk.tag.perceptron import PerceptronTagger
tagger = PerceptronTagger()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.