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
How to use Sphinx's autodoc to document a class's __init__(self) method?
5,599,254
58
2011-04-08T18:23:39Z
5,599,712
57
2011-04-08T19:08:27Z
[ "python", "python-sphinx", "autodoc" ]
Sphinx doesn't generate docs for \_\_init\_\_(self) by default. I have tried the following: ``` .. automodule:: mymodule :members: ``` and ``` ..autoclass:: MyClass :members: ``` In conf.py, setting the following only appends the \_\_init\_\_(self) docstring to the class docstring ([the Sphinx autodoc docum...
Here are three alternatives: 1. To ensure that `__init__()` is always documented, you can use [`autodoc-skip-member`](http://sphinx.pocoo.org/ext/autodoc.html#skipping-members) in conf.py. Like this: ``` def skip(app, what, name, obj, skip, options): if name == "__init__": return False ...
How to use Sphinx's autodoc to document a class's __init__(self) method?
5,599,254
58
2011-04-08T18:23:39Z
9,772,922
35
2012-03-19T15:25:06Z
[ "python", "python-sphinx", "autodoc" ]
Sphinx doesn't generate docs for \_\_init\_\_(self) by default. I have tried the following: ``` .. automodule:: mymodule :members: ``` and ``` ..autoclass:: MyClass :members: ``` In conf.py, setting the following only appends the \_\_init\_\_(self) docstring to the class docstring ([the Sphinx autodoc docum...
You were close. Place the following line in your Sphinx project's `conf.py` file: ``` autoclass_content = 'both' ```
How can I assign the value of a variable using eval in python?
5,599,283
34
2011-04-08T18:26:13Z
5,599,309
9
2011-04-08T18:29:24Z
[ "python" ]
Okay. So my question is simple: How can I assign the value of a variable using eval in Python? I tried `eval('x = 1')` but that won't work. It returns a SyntaxError. Why won't this work?
You can't, since variable assignment is a statement, not an expression, and `eval` can only `eval` expressions. Use `exec` instead. Better yet, don't use either and tell us what you're *really* trying to do so that we can come up with a safe and sane solution.
How can I assign the value of a variable using eval in python?
5,599,283
34
2011-04-08T18:26:13Z
5,599,313
62
2011-04-08T18:29:33Z
[ "python" ]
Okay. So my question is simple: How can I assign the value of a variable using eval in Python? I tried `eval('x = 1')` but that won't work. It returns a SyntaxError. Why won't this work?
Because `x=1` is a statement, not an expression. Use [`exec`](http://docs.python.org/py3k/library/functions.html#exec) to run statements. ``` >>> exec('x=1') >>> x 1 ``` --- By the way, there are many ways to avoid using `exec`/`eval` if all you need is a dynamic name to assign, e.g. you could use a dictionary, the ...
Python (Windows) - ImportError: No module named site
5,599,872
57
2011-04-08T19:25:31Z
5,687,052
102
2011-04-16T14:12:00Z
[ "python", "windows", "module", "installation", "environment-variables" ]
I am trying to install Python for the first time. I downloaded the following installer from the Python website: [Python 2.7.1 Windows Installer (Windows binary -- does not include source)](http://www.python.org/ftp/python/2.7.1/python-2.7.1.msi). I then ran the installer, selected 'All Users' and all was fine. I instal...
Hey, I've been looking into this problem for myself for almost a day and finally had a breakthrough. Try this: 1. Setting the PYTHONPATH / PYTHONHOME variables Right click the Computer icon in the start menu, go to properties. On the left tab, go to Advanced system settings. In the window that comes up, go to t...
Python (Windows) - ImportError: No module named site
5,599,872
57
2011-04-08T19:25:31Z
8,895,513
22
2012-01-17T13:34:32Z
[ "python", "windows", "module", "installation", "environment-variables" ]
I am trying to install Python for the first time. I downloaded the following installer from the Python website: [Python 2.7.1 Windows Installer (Windows binary -- does not include source)](http://www.python.org/ftp/python/2.7.1/python-2.7.1.msi). I then ran the installer, selected 'All Users' and all was fine. I instal...
Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH For example if you installed to c:\Python27 ``` set PYTHONHOME=c:\Python27 set PYTHONPATH=c:\Python27\Lib set PATH=%PYTHONHOME%;%PATH% ``` Make sure you don't have a trailing '\' on the PYTHON\* vars, this seems to break it aswel.
Python (Windows) - ImportError: No module named site
5,599,872
57
2011-04-08T19:25:31Z
19,377,110
8
2013-10-15T08:59:01Z
[ "python", "windows", "module", "installation", "environment-variables" ]
I am trying to install Python for the first time. I downloaded the following installer from the Python website: [Python 2.7.1 Windows Installer (Windows binary -- does not include source)](http://www.python.org/ftp/python/2.7.1/python-2.7.1.msi). I then ran the installer, selected 'All Users' and all was fine. I instal...
I was having this issue after installing both Windows Python and Cygwin Python, and trying to run Cygwin Python from Cygwin. I solved it by `export`ing PYTHONHOME=/usr/ and PYTHONPATH=/usr/lib/python2.7
Can JavaScript talk to Selenium 2?
5,600,048
9
2011-04-08T19:43:49Z
5,654,387
8
2011-04-13T19:18:05Z
[ "javascript", "python", "asynchronous", "selenium", "selenium-webdriver" ]
I know I can get Selenium 2's webdriver to run JavaScript and get return values but so much asynchronous stuff is happening I would like JavaScript to talk to Selenium instead of the other way around. I have done some searching and haven't found anything like this. Do people just generally use `implicitly_wait`? That s...
You should look into the execute\_async\_script() method (JavascriptExecutor.executeAsyncScript in Java, IJavaScriptExecutor.ExecuteAsyncScript() in .NET), which allows you to wait for a callback function. The callback function is automatically appended to the `arguments` array in your JavaScript function. So, assuming...
python matplotlib add and remove text to figure using button events
5,600,370
2
2011-04-08T20:20:53Z
5,600,964
8
2011-04-08T21:28:40Z
[ "python", "matplotlib" ]
I'm trying to add text to a graph at the location of the mouse pointer when button\_press\_event is called and remove it when button\_release\_event is called. I have successfully added the text but I can not get it to erase. Here is part of the code I used: ``` def onclick(event): print 'you pressed', event.butto...
Assuming you should use it in a class and refer to the following `txt` as `self.txt` I use global here for sake of ease: ``` txt = None def onclick(event): global txt txt = plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8) fig.canvas.draw() def offclick(event): txt.remove() fig.canvas.dr...
Check if a record exists in App Engine Datastore
5,601,869
7
2011-04-08T23:47:52Z
5,602,418
7
2011-04-09T02:01:14Z
[ "python", "google-app-engine", "gae-datastore" ]
From what I've read, this is how I should check for any records... ``` v = PC_Applications.all().filter('column =', value) if not v: return False ``` But this returns an error! > IndexError: The query returned fewer than 1 results Any ideas to doing this? I've read that .count() is a bad option. I'm new to ...
``` if not v.get(): ``` From [App Engine, Query Class get()](http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_get) > Executes the query, then returns the > first result, or None if the query > returned no results.
numpy boolean array with 1 bit entries
5,602,155
16
2011-04-09T00:54:12Z
5,602,175
12
2011-04-09T00:57:49Z
[ "python", "numpy", "boolean" ]
Is there a way in numpy to create an array of booleans that uses just 1 bit for each entry? The standard `np.bool` type is 1 byte, but this way I use 8 times the required memory. On Google I found that C++ has [`std::vector<bool>`](http://en.cppreference.com/w/cpp/container/vector_bool).
You want a [bitarray](http://pypi.python.org/pypi/bitarray): > *efficient arrays of booleans -- C extension* > > This module provides an object type which efficiently represents an array of booleans. Bitarrays are sequence types and behave very much like usual lists. Eight bits are represented by one byte in a contigu...
numpy boolean array with 1 bit entries
5,602,155
16
2011-04-09T00:54:12Z
5,604,266
9
2011-04-09T09:52:09Z
[ "python", "numpy", "boolean" ]
Is there a way in numpy to create an array of booleans that uses just 1 bit for each entry? The standard `np.bool` type is 1 byte, but this way I use 8 times the required memory. On Google I found that C++ has [`std::vector<bool>`](http://en.cppreference.com/w/cpp/container/vector_bool).
You might like to take a look at [bitstring](http://python-bitstring.googlecode.com) (documentation [here](http://packages.python.org/bitstring/)). If you create a `ConstBitArray` or `ConstBitStream` from a file then it will use `mmap` and not load it into memory. In this case it won't be mutable so if you want to mak...
(PostgreSQL) Select NULL Values In SQLAlchemy
5,602,918
13
2011-04-09T04:40:41Z
5,632,224
33
2011-04-12T08:13:04Z
[ "python", "sql", "database", "postgresql", "sqlalchemy" ]
Here's my (PostgreSQL) table -- ``` test=> create table people (name varchar primary key, marriage_status varchar) ; test=> insert into people values ('Ken', 'married'); test=> insert into people values ('May', 'single'); test=> insert into people values ('Joe', NULL); ``` I want to sele...
(as indicated by [@augurar](http://stackoverflow.com/users/2572431/augurar)): Because *sqlalchemy* uses *magic methods (operator overloading)* to create `SQL` constructs, it can only handle operator such as `!=` or `==`, but is not able to work with `is` (which is a very valid Python construct). Therefore, to make it ...
How to code argparse combinational options in python
5,603,364
13
2011-04-09T06:45:09Z
5,603,420
16
2011-04-09T06:59:23Z
[ "python", "argparse" ]
I have been troubled with this small piece of activity to be completed. I did do some experiment, but was not able to achieve the result. **Requirement:** ``` test2.py [-c/-v] -f ``` **Usage or Rules:** 1. -c (compare) takes 2 parameter. -v (verify) takes 1 parameter. *Either* of these two must be presen...
Set the filename to be a positional argument, and let `argparse` set its own usage message: ``` $ python so.py --help usage: so.py [-h] [-c Package1 Package2 | -v Package] outFileName ``` The filename should be positional, and you should let `argparse` write its own usage message. ### Code ``` #!/usr/bin/python im...
Creating my own "integer" object in Python
5,604,713
6
2011-04-09T11:23:32Z
5,604,760
8
2011-04-09T11:33:06Z
[ "python", "object" ]
Essentially I want to be able to do something like: ``` a = Integer(1) a += 1 print a ``` And of course printing the number two as result. What methods do I need to create to get this behaviour in my Integer class? Disclaimer: I'm not planning to use this for "real", just curious.
This is a simple and incomplete example. Look at methods `__sub__`, `__div__` and so on. ``` class Integer(object) : def __init__(self, val=0) : self._val = int(val) def __add__(self, val) : if type(val) == Integer : return Integer(self._val + val._val) return self._val + va...
What do these python `import` statements mean?
5,605,299
10
2011-04-09T13:27:11Z
5,605,357
12
2011-04-09T13:38:49Z
[ "python" ]
At the beginning of a python script, there are some `import` statements. Could someone explain what they imply? ``` import getopt import os import re import string import sys import getpass import urllib import subprocess ```
The `import` statements are similar (but different) to the `#include` statements in C: they allow you to use functions defined elsewhere (either in a standard module, or your own). For example, module `sys` allows you to do this: ``` import sys # ... somewhere down in the file sys.exit(0) ``` Which would terminate y...
PyLab: Plotting axes to log scale, but labelling specific points on the axes
5,605,503
4
2011-04-09T14:04:00Z
5,605,692
8
2011-04-09T14:45:37Z
[ "python", "graph", "matplotlib" ]
Basically, I'm doing scalability analysis, so I'm working with numbers like 2,4,8,16,32... etc and the only way graphs look rational is using a log scale. But instead of the usual 10^1, 10^2, etc labelling, I want to have these datapoints (2,4,8...) indicated on the axes Any ideas?
There's more than one way to do it, depending on how flexible/fancy you want to be. The simplest way is just to do something like this: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl x = np.exp2(np.arange(10)) plt.semilogy(x) plt.yticks(x, x) # Turn y-axis minor ticks off plt.gca(...
How to set and retrieve cookie in HTTP header in Python?
5,606,083
8
2011-04-09T16:00:12Z
5,606,179
9
2011-04-09T16:17:19Z
[ "python", "cookies", "http-headers" ]
I need to get the cookies from a HTTP response sent by a server and put it in the next request's header. How can I do it? Thanks in advance.
Look at urllib module: (with Python 3.1, in Python 2, use urllib2.urlopen instead) For retrieving cookies: ``` >>> import urllib.request >>> d = urllib.request.urlopen("http://www.google.co.uk") >>> d.getheader('Set-Cookie') 'PREF=ID=a45c444aa509cd98:FF=0:TM=14.....' ``` And for sending, simply send a Cookie header ...
How to set and retrieve cookie in HTTP header in Python?
5,606,083
8
2011-04-09T16:00:12Z
5,607,087
22
2011-04-09T18:50:40Z
[ "python", "cookies", "http-headers" ]
I need to get the cookies from a HTTP response sent by a server and put it in the next request's header. How can I do it? Thanks in advance.
You should use the [cookielib module](http://docs.python.org/library/cookielib.html). It will store cookies between requests, and you can load/save them on disk. Here is an example: ``` import cookielib import urllib2 cookies = cookielib.LWPCookieJar() handlers = [ urllib2.HTTPHandler(), urllib2.HTTPSHandler(...
Python: Test if value can be converted to an int in a list comprehension
5,606,585
9
2011-04-09T17:24:47Z
5,606,627
16
2011-04-09T17:30:22Z
[ "types", "casting", "int", "python" ]
Basically I want to do this; ``` return [ row for row in listOfLists if row[x] is int ] ``` But row[x] is a text value that may or may not be convertible to an int I'm aware that this could be done by: ``` try: int(row[x]) except: meh ``` But it'd be nice to do it is a one-liner. Any ideas?
If you only deal with integers, you can use [`str.isdigit()`](http://docs.python.org/library/stdtypes.html#str.isdigit): > Return true if all characters in the string are digits and there is at least one character, false otherwise. ``` [row for row in listOfLists if row[x].isdigit()] ``` Or if negative integers are ...
how do I use py2app?
5,607,121
5
2011-04-09T18:57:05Z
5,607,163
8
2011-04-09T19:03:55Z
[ "python", "osx", "py2app" ]
Ok - here goes. I am trying to learn how to use py2app, so I created a simple python file; just hello\_world.py ``` #! /usr/bin/env python def main(): print "Hello" if __name__=="__main__": main() ``` I followed a tutorial and did the following: ``` py2applet --make-setup hello.py python setup.py py2app -A ``` ...
You have successfully used py2app - it just opens, prints "hello" and then closes really quickly! If you want to see something, then make it pause for a bit: ``` print "Hello" import time time.sleep(5) ``` *time.sleep* pauses a program for the number of seconds given.
How can I manually generate a .pyc file from a .py file
5,607,283
44
2011-04-09T19:28:20Z
5,607,315
34
2011-04-09T19:31:46Z
[ "python" ]
For some reason, I can not depend on Python's "import" statement to generate .pyc file automatically Is there a way to implement a function as following? ``` def py_to_pyc(py_filepath, pyc_filepath): ... ```
It's been a while since I last used Python, but I believe you can use [`py_compile`](https://docs.python.org/3/library/py_compile.html#py_compile.compile): ``` import py_compile py_compile.compile("file.py") ```
How can I manually generate a .pyc file from a .py file
5,607,283
44
2011-04-09T19:28:20Z
5,615,653
17
2011-04-11T00:20:41Z
[ "python" ]
For some reason, I can not depend on Python's "import" statement to generate .pyc file automatically Is there a way to implement a function as following? ``` def py_to_pyc(py_filepath, pyc_filepath): ... ```
I would use [compileall](http://docs.python.org/library/compileall.html). It works nicely both from scripts and from the command line. It's a bit higher level module/tool than the already mentioned [py\_compile](http://docs.python.org/library/py_compile.html) that it also uses internally.
How can I manually generate a .pyc file from a .py file
5,607,283
44
2011-04-09T19:28:20Z
22,779,209
81
2014-04-01T07:16:31Z
[ "python" ]
For some reason, I can not depend on Python's "import" statement to generate .pyc file automatically Is there a way to implement a function as following? ``` def py_to_pyc(py_filepath, pyc_filepath): ... ```
You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The [compileall](https://docs.python.org/2/library/compileall.html) module is part of the python standard library, so you don't need to install anything extra to u...
How can I manually generate a .pyc file from a .py file
5,607,283
44
2011-04-09T19:28:20Z
32,686,745
14
2015-09-21T03:08:08Z
[ "python" ]
For some reason, I can not depend on Python's "import" statement to generate .pyc file automatically Is there a way to implement a function as following? ``` def py_to_pyc(py_filepath, pyc_filepath): ... ```
You can compile individual files(s) from the command line with: ``` python -m compileall <file_1>.py <file_n>.py ```
How to add with tuples
5,607,284
4
2011-04-09T19:28:26Z
5,607,358
7
2011-04-09T19:37:43Z
[ "python", "algorithm", "tuples" ]
I have pseudo-code like this: ``` if( b < a) return (1,0)+foo(a-b,b) ``` I want to write it in python. But can python add tuples? What is the best way to code something like that?
Do you want to do element-wise addition, or to append the tuples? By default python does ``` (1,2)+(3,4) = (1,2,3,4) ``` You could define your own as: ``` def myadd(x,y): z = [] for i in range(len(x)): z.append(x[i]+y[i]) return tuple(z) ``` Also, as @delnan's comment makes it clear, this is...
How to add with tuples
5,607,284
4
2011-04-09T19:28:26Z
14,375,890
7
2013-01-17T09:30:57Z
[ "python", "algorithm", "tuples" ]
I have pseudo-code like this: ``` if( b < a) return (1,0)+foo(a-b,b) ``` I want to write it in python. But can python add tuples? What is the best way to code something like that?
I'd go for ``` >>> map(sum, zip((1, 2), (3, 4))) [4, 6] ``` or, more naturally: ``` >>> numpy.array((1, 2)) + numpy.array((3, 4)) array([4, 6]) ```
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
5,607,708
215
2011-04-09T20:30:21Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
You need to pass your parameters into [`urlencode()`](http://docs.python.org/2/library/urllib.html#urllib.urlencode) as either a mapping (dict), or a sequence of 2-tuples, like: ``` >>> import urllib >>> f = { 'eventName' : 'myEvent', 'eventDescription' : "cool event"} >>> urllib.urlencode(f) 'eventName=myEvent&eventD...
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
9,345,102
590
2012-02-18T23:23:03Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
# Python 2 What you're looking for is [`urllib.quote_plus`](https://docs.python.org/2/library/urllib.html#urllib.quote_plus): ``` >>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$') 'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24' ``` # Python 3 In Python 3, you the `urllib` package ...
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
9,472,647
22
2012-02-27T21:35:06Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
Python 3: [urllib.parse.quote\_plus(string, safe='', encoding=None, errors=None)](http://docs.python.org/py3k/library/urllib.parse.html?highlight=urllib#urllib.parse.quote_plus)
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
10,390,093
22
2012-04-30T20:23:23Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
Note that the urllib.urlencode does not always do the trick. The problem is that some services care about the order of arguments, which gets lost when you create the dictionary. For such cases, urllib.quote\_plus is better, as Ricky suggested.
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
18,558,040
17
2013-09-01T11:36:38Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
Try [requests](http://docs.python-requests.org/en/latest/) instead of urllib and you don't need to bother with urlencode! ``` import requests requests.get('http://youraddress.com', params=evt.fields) ``` **EDIT:** If you need **ordered name-value pairs** or multiple values for a name then set params like so: ``` pa...
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
18,648,642
28
2013-09-06T01:50:35Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
### Context * Python (version 2.7.2 ) ### Problem * You want to generate a urlencoded query string. * You have a dictionary or object containing the name-value pairs. * You want to be able to control the output ordering of the name-value pairs. ### Solution * urllib.urlencode * urllib.quote\_plus ### Pitfalls * ...
Python urlencode querystring
5,607,551
234
2011-04-09T20:07:12Z
24,730,081
8
2014-07-14T05:36:01Z
[ "python", "url-encoding" ]
I am trying to urlencode this string before I submit. ``` queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; ```
Try this: ``` urllib.pathname2url(stringToURLEncode) ``` I wasn't able to get `urlencode` to work, it might need a full actual URL. `quote_plus` didn't produce the correct output.
How to specify py2app icon?
5,608,080
7
2011-04-09T21:34:46Z
5,609,857
17
2011-04-10T04:54:05Z
[ "python", "osx", "py2app" ]
How do I specify the icon file when using py2app? Just now I create the setup file: ``` py2applet --make-setup MyApplication.py ``` and then build the application bundle: ``` python setup.py py2app -A ``` where is it that I specify the icon file.. getting a little confused. Thanks for any help. according to this...
In your setup.py, add iconfile ``` """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['main.py'] DATA_FILES = [] OPTIONS = { 'iconfile':'icon.icns', 'plist': {'CFBundleShortVersionString':'0.1.0',} } setup( app=APP, name='M...
How can I convert a string to either int or float with priority on int?
5,608,702
8
2011-04-09T23:45:31Z
5,609,191
15
2011-04-10T01:36:51Z
[ "python" ]
I couldn't find another answer when I wanted this, so I thought I would post my own solution for anyone else and also get corrections if I've done something wrong. I had to make an automatic config file parser and I preferred to make numbers int if possible and float if not. The usual try/except conversion doesn't wor...
``` def int_or_float(s): try: return int(s) except ValueError: return float(s) ``` If you want something like `"10.0000"` converted to int, try this: ``` def int_dammit_else_float(s): f = float(s) i = int(f) return i if i == f else f ``` What result do you want for input like `"1e...
How to save figures to pdf as raster images in matplotlib
5,609,969
10
2011-04-10T05:27:28Z
5,638,626
13
2011-04-12T16:32:40Z
[ "python", "pdf", "matplotlib", "raster" ]
I have some complex graphs made using matplotlib. Saving them to a pdf using the savefig command uses a vector format, and the pdf takes ages to open. Is there any way to save the figure to pdf as a raster image to get around this problem?
You can force individual figure elements to be rasterized like this: ``` text(1,1,'foobar',rasterized=True) ```
How can I redirect after POST in Pyramid?
5,610,087
18
2011-04-10T06:06:38Z
5,610,146
7
2011-04-10T06:24:01Z
[ "python", "post", "redirect", "pylons", "pyramid" ]
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route. For example: * User loads the page website.com/post * Form POSTs the data to website.com/post-save * User gets redirected back to website.com/post Pyramid is giving me some troubles doing this. Here's...
The Pyramid documentation has a particularly on-point [section](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/views.html#using-a-view-callable-to-do-an-http-redirect) with the following example: ``` from pyramid.httpexceptions import HTTPFound def myview(request): return HTTPFound(location='http:/...
How can I redirect after POST in Pyramid?
5,610,087
18
2011-04-10T06:06:38Z
5,641,144
25
2011-04-12T20:19:27Z
[ "python", "post", "redirect", "pylons", "pyramid" ]
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route. For example: * User loads the page website.com/post * Form POSTs the data to website.com/post-save * User gets redirected back to website.com/post Pyramid is giving me some troubles doing this. Here's...
Your problem is most easily solved by simply POSTing to the same URL that your form is shown at, and simply redirecting the user away from the page when the POST is successful. That way until the form is successfully submitted you do not change URLs. If you're just dying to POST to a different URL, then you need to sa...
related_name argument not working as expected in Django model?
5,611,410
13
2011-04-10T11:22:50Z
5,612,282
42
2011-04-10T14:07:41Z
[ "python", "django" ]
I recently got a ForeignKey clash in my Django model. I have the need to have two foreign keys (owner, assigned\_to) ultimately pointing to the same model (a user). From what I understand I need a `related_name` argument to solve that problem. So I did that: ``` assigned_to = models.ForeignKey(TaskUser, blank=True, n...
If you have `ForeignKey` relationships in an abstract base class every class inheriting from it will have this relationship. As a result of this you must not 'hardcode' its `related_name`, because all sub classes will try to create the same accessor on the realted class (`TaskUser` in this case). You should better do ...
Basic pySQLite example?
5,612,745
6
2011-04-10T15:26:13Z
5,612,774
10
2011-04-10T15:33:04Z
[ "python", "sqlite", "pysqlite" ]
Gang, I am beginning to play around with pySQLite and I'm trying to find an example that illustrates how to query the db for existing records before inserting a new record if it doesn't already exist in the db. I feel I am overlooking a very basic function. Thanks!
Use the `UNIQUE` keyword when creating the table, and use `INSERT OR INGORE` to insert only if the record is "new" (unique): ``` connection=sqlite3.connect(':memory:') cursor=connection.cursor() cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)') ``` Here we insert the row once: ``` cursor.execute('...
root mean square in numpy and complications of matrix and arrays of numpy
5,613,244
7
2011-04-10T16:53:02Z
7,433,184
40
2011-09-15T15:12:00Z
[ "python", "numpy" ]
Can anyone direct me to the section of numpy manual where i can get functions to accomplish root mean square calculations ... (i know this can be accomplished using np.mean and np.abs .. isn't there a built in ..if no why?? .. just curious ..no offense) can anyone explain the complications of matrix and arrays (just i...
For the RMS, I think this is the clearest: ``` from numpy import mean, sqrt, square, arange a = arange(10) # For example rms = sqrt(mean(square(a))) ``` The code reads like you say it: "root-mean-square".
Parsing repeated characters
5,614,163
2
2011-04-10T19:30:21Z
5,614,324
7
2011-04-10T19:58:10Z
[ "python", "parsing", "lepl" ]
I'm new to parsing (obviously). I am using [LEPL](http://www.acooke.org/lepl/) library to parse some markup language. I have a problem with this code (I've omitted details for the sake of clarity). ``` from lepl import * a = Literal('a')[0:,...] # 0 or more, join the result b = Literal('b') c = (a | b)[0:] print c...
I am pretty sure that, in your first example, you want ``` a = Literal('a')[1:] ``` With two `[0:]` repeats in your grammar, the parser will indeed run into effectively infinite backtracking.
Need help understanding Comet in Python (with Django)
5,614,274
30
2011-04-10T19:49:22Z
5,615,700
8
2011-04-11T00:30:21Z
[ "python", "django", "twisted", "comet", "gevent" ]
After spending two entire days on this I'm still finding it impossible to understand all the choices and configurations for Comet in Python. I've read all the answers here as well as every blog post I could find. It feels like I'm about to hemorrhage at this point, so my utmost apologies for anything wrong with this qu...
You could use Socket.IO. There are gevent and tornado handlers for it. See my blog post on gevent-socketio with Django here: <http://codysoyland.com/2011/feb/6/evented-django-part-one-socketio-and-gevent/>
JSON->String in python
5,614,572
12
2011-04-10T20:41:34Z
5,615,192
19
2011-04-10T22:38:34Z
[ "python", "json" ]
Say I get this line of JSON ``` [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}] ``` How can I convert those separate values to strings? So I can say ``` Print Status ``` And it returns ``` active ```
That is NOT a "line of JSON" as received from an external source. It looks like the result of `json.loads(external_JSON_string)`. Also `Print Status` won't work; you mean `print status`. ``` >>> result = [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}] >>> print result[0]['status'] ac...
Call a python function within a html file
5,615,228
6
2011-04-10T22:47:30Z
5,615,268
11
2011-04-10T22:55:37Z
[ "python", "html" ]
Is there a way to call a python function when a certain link is clicked within a html page? Thanks
You'll need to use a web framework to route the requests to Python, as you can't do that with just HTML. [Flask](http://flask.pocoo.org/) is one simple framework: **server.py**: ``` from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('template.html') ...
Does python's setuptools support the `__name__ == "__main__"` style of execution?
5,615,292
6
2011-04-10T22:59:41Z
5,616,734
9
2011-04-11T04:27:44Z
[ "python", "setuptools" ]
I'm just getting into packaging with setuptools, and it seems that the recommended way to install a python script along with one's module is to specify a script name that calls the name of a function, like this: ``` setup( # ... entry_points = { "console_scripts": [ "script_name": "project....
It is: `"script_name = project.main:do_stuff` with setuptools Setuptools creates scripts named `script_name` that imports and runs the function `project.main:do_stuff`, not run the script directly. You should re-read [this part](http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation) ([alternate ...
Python call function within class
5,615,648
71
2011-04-11T00:20:07Z
5,615,671
15
2011-04-11T00:24:36Z
[ "python", "class", "function", "call" ]
I have this code which calculates the distance between two coordinates. The two functions are both within the same class. However how do I call the function `distToPoint` in the function `isNear`? ``` def distToPoint(self, p): """ Use pythagoras to find distance (a^2 = b^2 + c^2) """ ... def isNe...
That doesn't work because `distToPoint` is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: `classname.distToPoint(self, p)`. You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the firs...
Python call function within class
5,615,648
71
2011-04-11T00:20:07Z
5,615,674
133
2011-04-11T00:24:42Z
[ "python", "class", "function", "call" ]
I have this code which calculates the distance between two coordinates. The two functions are both within the same class. However how do I call the function `distToPoint` in the function `isNear`? ``` def distToPoint(self, p): """ Use pythagoras to find distance (a^2 = b^2 + c^2) """ ... def isNe...
Since these are member functions, call it as a member function on the instance, `self`. ``` def isNear(self, p): self.distToPoint(p) ... ```
Pygame screen freezes when I close it
5,615,860
3
2011-04-11T01:03:51Z
5,616,666
8
2011-04-11T04:09:28Z
[ "python", "pygame" ]
The code loads up a pygame screen window, but when I click the X to close it, it becomes unresponsive. I'm running on a 64-bit system, using a 32-bit python and 32-bit pygame. ``` from livewires import games, color games.init(screen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop() ```
Mach1723's [answer](http://stackoverflow.com/questions/5615860/pygame-screen-freezes-when-i-close-it/5616374#5616374) is correct, but I would like to suggest another variant of a main loop: ``` while 1: for event in pygame.event.get(): if event.type == QUIT: ## defined in pygame.locals pygame.q...
Making Python batch files
5,616,032
2
2011-04-11T01:45:27Z
5,617,266
9
2011-04-11T05:51:15Z
[ "python", "batch-file", "pygame" ]
How can I create a bat file to run a python file, specifically containing pygame.
Simple. Just put the following as the very first line of the batch file: `python -x %0 %* &goto :eof` The rest of the batch file is the Python program. Here is a complete example: ``` python -x %0 %* &goto :eof import sys print "this is a batch file" sys.exit() ``` First of all the & is a delimiter and allows...
Is there a statistical profiler for python? If not, how could I go about writing one?
5,616,446
13
2011-04-11T03:15:37Z
10,333,592
11
2012-04-26T12:38:48Z
[ "python", "profile", "stochastic" ]
I would need to run a python script for some random amount of time, pause it, get a stack traceback, and unpause it. I've googled around for a way to do this, but I see no obvious solution.
There's the [`statprof` module](http://pypi.python.org/pypi/statprof/) `pip install statprof` (or `easy_install statprof`), then to use: ``` import statprof statprof.start() try: my_questionable_function() finally: statprof.stop() statprof.display() ``` There's a bit of background on the module from [th...
Python regex find all overlapping matches?
5,616,822
34
2011-04-11T04:41:50Z
5,616,910
70
2011-04-11T04:58:06Z
[ "python", "regex", "overlapping" ]
I'm trying to find every 10 digit series of numbers within a larger series of numbers using re in Python 2.6. I'm easily able to grab no overlapping matches, but I want every match in the number series. Eg. in "123456789123456789" I should get the following list: ``` [1234567891,2345678912,3456789123,4567891234,567...
``` import re s = "123456789123456789" matches = re.finditer(r'(?=(\d{10}))',s) results = [int(match.group(1)) for match in matches] # results: # [1234567891, # 2345678912, # 3456789123, # 4567891234, # 5678912345, # 6789123456, # 7891234567, # 8912345678, # 9123456789] ```
Python regex find all overlapping matches?
5,616,822
34
2011-04-11T04:41:50Z
6,845,215
16
2011-07-27T13:34:12Z
[ "python", "regex", "overlapping" ]
I'm trying to find every 10 digit series of numbers within a larger series of numbers using re in Python 2.6. I'm easily able to grab no overlapping matches, but I want every match in the number series. Eg. in "123456789123456789" I should get the following list: ``` [1234567891,2345678912,3456789123,4567891234,567...
I'm fond of regexes, but they are not needed here. Simply ``` s = "123456789123456789" n = 10 li = [ s[i:i+n] for i in xrange(len(s)-n+1) ] print '\n'.join(li) ``` result ``` 1234567891 2345678912 3456789123 4567891234 5678912345 6789123456 7891234567 8912345678 9123456789 ```
Python regex find all overlapping matches?
5,616,822
34
2011-04-11T04:41:50Z
18,966,891
30
2013-09-23T19:06:51Z
[ "python", "regex", "overlapping" ]
I'm trying to find every 10 digit series of numbers within a larger series of numbers using re in Python 2.6. I'm easily able to grab no overlapping matches, but I want every match in the number series. Eg. in "123456789123456789" I should get the following list: ``` [1234567891,2345678912,3456789123,4567891234,567...
You can also try using the [new Python regex module](https://pypi.python.org/pypi/regex), which supports overlapping matches. ``` >>> import regex as re >>> s = "123456789123456789" >>> matches = re.findall(r'\d{10}', s, overlapped=True) >>> for match in matches: print match ... 1234567891 2345678912 3456789123 456789...
Why is this program faster in Python than Objective-C?
5,616,847
18
2011-04-11T04:46:05Z
5,617,198
9
2011-04-11T05:42:28Z
[ "python", "objective-c", "nsstring" ]
I got interested in [this small example](http://stackoverflow.com/questions/5523058/how-to-optimize-this-python-code-from-thinkpython-exercise-10-10/5523071#comment-6276679) of an algorithm in Python for looping through a large word list. I am writing a few "tools" that will allow my to slice a Objective-C string or ar...
Keep in mind that the Python version has been written to move a lot of the heavy lifting down into highly optimised C code when executed on CPython (especially the file input buffering, string slicing and the hash table lookups to check whether `even` and `odd` are in `words`). That said, you seem to be decoding the f...
How do I use prepared statements for inserting MULTIPLE records in SQlite using Python / Django?
5,616,895
12
2011-04-11T04:56:13Z
5,616,969
19
2011-04-11T05:07:28Z
[ "python", "django", "sqlite" ]
How do I use prepared statement for inserting MULTIPLE records in SQlite using Python / Django?
``` http://docs.python.org/library/sqlite3.html#cursor-objects ``` Python's SQLite libraries don't have prepared statement objects, but they do allow you to use parameterized queries, and to provide more than one set of parameters. Edit: An example of `executemany` as requested: ``` values_to_insert = [(1,"foo"), (2...
Mid-line comment in Python?
5,617,159
25
2011-04-11T05:37:14Z
5,617,169
18
2011-04-11T05:38:40Z
[ "python", "syntax", "comments" ]
I'm wondering if there is any way to comment out part of a line, like you can do in c++ with `/*this*/`. The only comments I know about are `# this` which always goes to the end of the line and the `"""these"""` ones, which do not work mid-line. Example use-case: using subprocess and need to temporarily comment out an...
You are correct, the answer is a big fat ***NO***.
Mid-line comment in Python?
5,617,159
25
2011-04-11T05:37:14Z
5,617,226
32
2011-04-11T05:46:22Z
[ "python", "syntax", "comments" ]
I'm wondering if there is any way to comment out part of a line, like you can do in c++ with `/*this*/`. The only comments I know about are `# this` which always goes to the end of the line and the `"""these"""` ones, which do not work mid-line. Example use-case: using subprocess and need to temporarily comment out an...
Actually if you break your statement into multiple lines you can. Something like: ``` ['../some/guy', '-m', '10', # '-p', '0', '-n', '100', '-f', '/dev/stdout'] ``` should work.
Django NameError during ManyToMany field referencing
5,618,720
2
2011-04-11T08:36:24Z
5,619,069
13
2011-04-11T09:09:51Z
[ "python", "django", "django-models", "many-to-many" ]
I am having a table named PlayCat. which basically stores al the category names of playful activities. such as disco,pool n stuff. So i want these categories to b referenced(ManyToMany) when a user creates a Play arena where he/she can select al the categories it belongs to. Play : ``` class Play(models.Model): sho...
I guess it's because you have a model PlayCat defined after a model Play. So it can't resolve it. You can either put model PlayCat before Play or use a string for reference ``` category = models.ManyToManyField('PlayCat') ```
Python regular expression parsing binary file
5,618,988
18
2011-04-11T09:00:37Z
5,619,886
23
2011-04-11T10:19:46Z
[ "python", "regex", "parsing", "binary" ]
I have a file which mixes binary data and text data. I want to parse it through a regular expression, but I get this error: `TypeError: can't use a string pattern on a bytes-like object` I'm guessing that message means that Python doesn't want to parse binary files. I'm opening the file with the `"rb"` flags. How ca...
In your `re.compile` you need to use a `bytes` object, signified by an initial `b`: ``` r = re.compile(b"(This)") ``` This is Python 3 being picky about the difference between strings and bytes.
Python regular expression parsing binary file
5,618,988
18
2011-04-11T09:00:37Z
5,620,074
12
2011-04-11T10:35:37Z
[ "python", "regex", "parsing", "binary" ]
I have a file which mixes binary data and text data. I want to parse it through a regular expression, but I get this error: `TypeError: can't use a string pattern on a bytes-like object` I'm guessing that message means that Python doesn't want to parse binary files. I'm opening the file with the `"rb"` flags. How ca...
I think you use Python 3 . > 1.Opening a file in **binary mode** is simple but subtle. The only difference > from opening it in text mode is that > the mode parameter contains a **'b'** > character. > > ........ > > 4.Here’s one difference, though: a **binary stream** object has no encoding > attribute. That makes s...
What's a good Python library to manipulate frames of a video file?
5,619,053
6
2011-04-11T09:08:43Z
5,619,792
7
2011-04-11T10:11:36Z
[ "python", "video", "video-processing" ]
I'm looking for a Python video processing library, similar to [PIL](http://www.pythonware.com/products/pil/), where I can iterate through all the frames of a source video, access the pixel data for each frame, draw onto each frame and save the result as a new video file. I've found a couple of similar questions, but t...
I've often needed the same thing and as far as I know, there is no good solution with bindings in Python. Also it is not as simple as it may seem to manipulate frames of a video file. A modern file format for video does not store the frames one frame after the other but instead uses "delta frames", in which only the c...
Troubleshooting "descriptor 'date' requires a 'datetime.datetime' object but received a 'int'"
5,619,489
11
2011-04-11T09:45:48Z
5,619,570
21
2011-04-11T09:52:19Z
[ "python", "datetime" ]
In my code I ask the user for a date in the format `dd/mm/yyyy`. ``` currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ") day,month,year = currentdate.split('/') today = datetime.date(int(year),int(month),int(day)) ``` This returns the error > TypeError: descriptor 'date' requires a 'dateti...
It seems that you have imported `datetime.datetime` module instead of `datetime`. This should work though: ``` import datetime currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ") day,month,year = currentdate.split('/') today = datetime.date(int(year),int(month),int(day)) ``` ..or this: ```...
Troubleshooting "descriptor 'date' requires a 'datetime.datetime' object but received a 'int'"
5,619,489
11
2011-04-11T09:45:48Z
5,619,571
12
2011-04-11T09:52:20Z
[ "python", "datetime" ]
In my code I ask the user for a date in the format `dd/mm/yyyy`. ``` currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ") day,month,year = currentdate.split('/') today = datetime.date(int(year),int(month),int(day)) ``` This returns the error > TypeError: descriptor 'date' requires a 'dateti...
Do you import like this? ``` from datetime import datetime ``` Then you must change it to look like this: ``` import datetime ``` Explanation: In the first case you are effectively calling `datetime.datetime.date()`, a method on the object `datetime` in the module `datetime`. In the later case you create a new `dat...
Conversion from IP string to integer, and backward in Python
5,619,685
23
2011-04-11T10:02:11Z
5,619,864
11
2011-04-11T10:17:19Z
[ "python", "networking", "ip-address" ]
i have a little problem with my script, where i need to convert ip in form 'xxx.xxx.xxx.xxx' to integer representation and go back from this form. ``` def iptoint(ip): return int(socket.inet_aton(ip).encode('hex'),16) def inttoip(ip): return socket.inet_ntoa(hex(ip)[2:].decode('hex')) In [65]: inttoip(iptoi...
You lose the left-zero-padding which breaks decoding of your string. Here's a working function: ``` def inttoip(ip): return socket.inet_ntoa(hex(ip)[2:].zfill(8).decode('hex')) ```
Conversion from IP string to integer, and backward in Python
5,619,685
23
2011-04-11T10:02:11Z
13,294,427
51
2012-11-08T17:28:38Z
[ "python", "networking", "ip-address" ]
i have a little problem with my script, where i need to convert ip in form 'xxx.xxx.xxx.xxx' to integer representation and go back from this form. ``` def iptoint(ip): return int(socket.inet_aton(ip).encode('hex'),16) def inttoip(ip): return socket.inet_ntoa(hex(ip)[2:].decode('hex')) In [65]: inttoip(iptoi...
``` def ip2int(addr): return struct.unpack("!I", socket.inet_aton(addr))[0] def int2ip(addr): return socket.inet_ntoa(struct.pack("!I", addr)) ```
Conversion from IP string to integer, and backward in Python
5,619,685
23
2011-04-11T10:02:11Z
16,446,104
9
2013-05-08T16:52:28Z
[ "python", "networking", "ip-address" ]
i have a little problem with my script, where i need to convert ip in form 'xxx.xxx.xxx.xxx' to integer representation and go back from this form. ``` def iptoint(ip): return int(socket.inet_aton(ip).encode('hex'),16) def inttoip(ip): return socket.inet_ntoa(hex(ip)[2:].decode('hex')) In [65]: inttoip(iptoi...
In pure python without use additional module ``` def IP2Int(ip): o = map(int, ip.split('.')) res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3] return res def Int2IP(ipnum): o1 = int(ipnum / 16777216) % 256 o2 = int(ipnum / 65536) % 256 o3 = int(ipnum / 256) % 256 o4 = int(ipn...
Sendmail Errno[61] Connection Refused
5,619,914
18
2011-04-11T10:22:12Z
5,619,974
11
2011-04-11T10:27:34Z
[ "python", "smtp", "smtplib" ]
I've been trying to get my application to mail some outputted text to an email. For simplification I have isolated the script : ``` import smtplib import sys import os SERVER = "localhost" FROM = os.getlogin() TO = [raw_input("To : ")] SUBJECT = "Message From " + os.getlogin() print "Message : (End with ^D)" TEXT ...
My guess is that you do not have any SMTP server installed on your local machine. If your emails are not sensitive, open a Gmail account and [send your emails using it with Python](http://stackoverflow.com/questions/778202/smtplib-and-gmail-python-script-problems).
Sendmail Errno[61] Connection Refused
5,619,914
18
2011-04-11T10:22:12Z
7,198,982
7
2011-08-26T00:58:37Z
[ "python", "smtp", "smtplib" ]
I've been trying to get my application to mail some outputted text to an email. For simplification I have isolated the script : ``` import smtplib import sys import os SERVER = "localhost" FROM = os.getlogin() TO = [raw_input("To : ")] SUBJECT = "Message From " + os.getlogin() print "Message : (End with ^D)" TEXT ...
Start a simple SMTP server with Python like so: ``` python -m smtpd -n -c DebuggingServer localhost:1025 ```
Sendmail Errno[61] Connection Refused
5,619,914
18
2011-04-11T10:22:12Z
7,422,843
39
2011-09-14T20:53:37Z
[ "python", "smtp", "smtplib" ]
I've been trying to get my application to mail some outputted text to an email. For simplification I have isolated the script : ``` import smtplib import sys import os SERVER = "localhost" FROM = os.getlogin() TO = [raw_input("To : ")] SUBJECT = "Message From " + os.getlogin() print "Message : (End with ^D)" TEXT ...
If you start a local server as follows: > python -m smtpd -n -c DebuggingServer localhost:1025 Make sure to modify the mail-sending code to use the non-standard port number: ``` server = smtplib.SMTP(SERVER, 1025) server.sendmail(FROM, TO, message) server.quit() ```
Project Euler Problem 17 Python
5,620,571
3
2011-04-11T11:24:22Z
5,620,851
11
2011-04-11T11:53:10Z
[ "python" ]
Please let me know how to bug fix this code . I tried and correct a lot of things , but I am 10 extra to the solution ! If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive w...
The word "eighteen" only has eight letters, not nine. Since it appears ten times in the range 1-1000, that would explain the discrepancy. By the way, if you're checking if n is less than 10, why not simply use `n<10` instead of `n/10 == 0`?
SEARCH BEFORE/AFTER with Pythons imaplib
5,621,341
9
2011-04-11T12:35:37Z
9,309,921
10
2012-02-16T10:48:09Z
[ "python", "search", "date", "imap" ]
I have a smaller IMAP-script written i Python(3.2). I my search-line looks like this: ``` typ, data = M.search(None, 'FROM', '"MyName"') ``` I get the expected results. However, if I change it to something like: ``` typ, data = M.search(None, 'AFTER', '"01-Jan-2010"') ``` (with or without quoted date, I get this e...
You can use search like these: But seems it does not support detailed time, but only date. and the date is the internal date (disregarding time and timezone) of the email ``` M.search(None, '(SINCE "01-Jan-2012")') M.search(None, '(BEFORE "01-Jan-2012")') M.search(None, '(SINCE "01-Jan-2012" BEFORE "02-Jan-2012")') ...
Attaching file to an email in python leads to a blank file name?
5,622,660
10
2011-04-11T14:20:14Z
5,622,888
11
2011-04-11T14:35:57Z
[ "python", "email", "filenames", "attachment" ]
The following snipit of code works fine, except for the fact that the resulting attachment file name is blank in the email (the file opens as 'noname' in gmail). What am I doing wrong? ``` file_name = RecordingUrl.split("/")[-1] file_name=file_name+ ".wav" urlretrieve(RecordingUrl, file_name) ...
You need to add a [Content-Disposition header](http://en.wikipedia.org/wiki/MIME#Content-Disposition) to the `audio` part of the message using the [`add_header` method](http://docs.python.org/library/email.message.html#email.message.Message.add_header): ``` file = open(file_name, 'rb') audio = MIMEAudio(file.read()) f...
Write file with specific permissions in Python
5,624,359
31
2011-04-11T16:21:15Z
5,624,686
12
2011-04-11T16:49:21Z
[ "python", "file-io", "permissions" ]
I'm trying to create a file that is only user-readable and -writable (`0600`). Is the only way to do so by using `os.open()` as follows? ``` import os fd = os.open('/path/to/file', os.O_WRONLY, int("0600", 8)) myFileObject = os.fdopen(fd) myFileObject.write(...) myFileObject.close() ``` Ideally, I'd like to be able ...
**update** Folks, while I thank you for the upvotes here, I myself have to argue against my originally proposed solution bellow. The reason is doing things this way, there will be an amount of time, however small, where the file does exist, and does not have the proper permissions in place - this leave open wide ways o...
Write file with specific permissions in Python
5,624,359
31
2011-04-11T16:21:15Z
5,624,691
27
2011-04-11T16:49:27Z
[ "python", "file-io", "permissions" ]
I'm trying to create a file that is only user-readable and -writable (`0600`). Is the only way to do so by using `os.open()` as follows? ``` import os fd = os.open('/path/to/file', os.O_WRONLY, int("0600", 8)) myFileObject = os.fdopen(fd) myFileObject.write(...) myFileObject.close() ``` Ideally, I'd like to be able ...
What's the problem? `file.close()` will close the file even though it was open with `os.open()`. ``` with os.fdopen(os.open('/path/to/file', os.O_WRONLY | os.O_CREAT, 0o600), 'w') as handle: handle.write(...) ```
Write file with specific permissions in Python
5,624,359
31
2011-04-11T16:21:15Z
15,015,748
16
2013-02-22T02:14:25Z
[ "python", "file-io", "permissions" ]
I'm trying to create a file that is only user-readable and -writable (`0600`). Is the only way to do so by using `os.open()` as follows? ``` import os fd = os.open('/path/to/file', os.O_WRONLY, int("0600", 8)) myFileObject = os.fdopen(fd) myFileObject.write(...) myFileObject.close() ``` Ideally, I'd like to be able ...
This answer does not use the `with` statement, but it addresses multiple concerns with the [answer](http://stackoverflow.com/a/5624691/832230) by [vartec](http://stackoverflow.com/users/60711/vartec), especially the `umask` concern. Firstly, if the desired mode is `0600`, it can more clearly be specified as the octal ...
In python, how would I sort a list of strings where the location of the string comparison changes?
5,624,757
3
2011-04-11T16:56:52Z
5,624,791
7
2011-04-11T16:59:25Z
[ "python", "sorting" ]
I have a list of strings that have 2 dashes separating text like: ``` Wednesday-Morning-Go bowling Sunday-Really late at night-Sleep July-Noon-BBQ ``` I'd like to sort the list in alphabetical order in python by the last part of the string--the 2nd dash and on. Is there a way to do this in python? E.g. this is what I...
You can use the `key` attribute to `list.sort()`: ``` a = ["Wednesday-Morning-Go bowling", "Sunday-Really late at night-Sleep", "July-Noon-BBQ"] a.sort(key=lambda x: x.split("-", 2)[-1]) print a ``` prints ``` ['July-Noon-BBQ', 'Wednesday-Morning-Go bowling', 'Sunday-Really late at night-Sleep'] ``` Note that ...
kwargs parsing best practice
5,624,912
14
2011-04-11T17:10:37Z
5,624,942
27
2011-04-11T17:12:50Z
[ "python", "kwargs" ]
Is there a more compact/efficient way of doing this? ``` for key in kwargs: if key == 'log': self.log = kwargs[key] elif key == 'bin': self.bin = kwargs[key] elif key == 'pid': self.pid = kwargs[key] elif key == 'conf': self.conf = kwa...
``` for key in ('log', 'bin', 'pid', 'conf'): if key in kwargs: setattr(self, key, kwargs[key]) ``` or ``` self.__dict__.update((key, kwargs[key]) for key in ('log', 'bin', 'pid', 'conf') if key in kwargs) ```
kwargs parsing best practice
5,624,912
14
2011-04-11T17:10:37Z
5,624,955
20
2011-04-11T17:13:46Z
[ "python", "kwargs" ]
Is there a more compact/efficient way of doing this? ``` for key in kwargs: if key == 'log': self.log = kwargs[key] elif key == 'bin': self.bin = kwargs[key] elif key == 'pid': self.pid = kwargs[key] elif key == 'conf': self.conf = kwa...
``` self.log = kwargs.get('log', default_log) self.bin = kwargs.get('bin', default_bin) self.pid = kwargs.get('pid', default_pid) self.conf = kwargs.get('conf', default_conf) ``` This has the additional advantage that `self.log` is assigned in any case (`AttributeError` means your code is broken as hell, nothing more....
python csv module error
5,625,412
11
2011-04-11T17:58:24Z
5,625,502
29
2011-04-11T18:06:53Z
[ "python", "csv" ]
When I use Pythons [`csv`](https://docs.python.org/2/library/csv.html) module, it shows me ``` "delimiter" must be an 1-character string" ``` My code is like this ``` sep = "," srcdata = cStringIO.StringIO(wdata[1]) data = csv.reader(srcdata, delimiter=sep) ``` `wdata[1]` is a string source. How do I fix this p...
You most likely have `from __future__ import unicode_literals` at the top of your module or you are using python 3.x+ You need to do something like this: ``` sep=b"," # notice the b before the " srcdata=cStringIO.StringIO(wdata[1]) data = csv.reader(srcdata,delimiter=sep) ``` This tells Python that you want to repre...
How to Close a program using python?
5,625,524
4
2011-04-11T18:09:13Z
10,457,565
7
2012-05-04T23:57:55Z
[ "python" ]
Is there a way that python can close a windows application? I know how to start an app, but now I need to know how to close one.
``` # I have used os comands for a while # this program will try to close a firefox window every ten secounds import os import time # creating a forever loop while 1 : os.system("TASKKILL /F /IM firefox.exe") time.sleep(10) ```
List lookup faster than tuple?
5,626,164
18
2011-04-11T19:03:34Z
5,626,219
10
2011-04-11T19:08:19Z
[ "python", "performance", "list", "tuples", "python-internals" ]
In the past, when I've needed array-like indexical  lookups in a tight loop, I usually use tuples, since they seem to be generally extremely performant (close to using just n-number of variables). However, I decided to question that assumption today and came up with some surprising results: ``` In [102]: l = range(10...
Contrary to this, I have completely different advice. If the data is -- by the nature of the problem -- fixed in length, use a tuple. Examples: * ( r, g, b ) - three elements, fixed by the definition of the problem. * ( latitude, longitude ) - two elements, fixed by the problem definition If the data is -- by the n...
List lookup faster than tuple?
5,626,164
18
2011-04-11T19:03:34Z
5,626,776
20
2011-04-11T19:56:34Z
[ "python", "performance", "list", "tuples", "python-internals" ]
In the past, when I've needed array-like indexical  lookups in a tight loop, I usually use tuples, since they seem to be generally extremely performant (close to using just n-number of variables). However, I decided to question that assumption today and came up with some surprising results: ``` In [102]: l = range(10...
Tuples are primarily faster for *constructing* lists, not for accessing them. Tuples should be slightly faster to access: they require one less indirection. However, I believe the main benefit is that they don't require a second allocation when constructing the list. The reason lists are slightly faster for lookups i...
What is a monkey patch?
5,626,193
208
2011-04-11T19:05:41Z
5,626,225
10
2011-04-11T19:08:52Z
[ "python", "terminology", "monkeypatching" ]
I am trying to understand, what is a monkey patch? Is that something like methods/operators overloading or delegating? Does it have anything common with these things?
According to [Wikipedia](http://en.wikipedia.org/wiki/Monkey_patch): > In Python, the term monkey patch only > refers to dynamic modifications of a > class or module at runtime, motivated > by the intent to patch existing > third-party code as a workaround to a > bug or feature which does not act as > you desire.
What is a monkey patch?
5,626,193
208
2011-04-11T19:05:41Z
5,626,250
220
2011-04-11T19:10:57Z
[ "python", "terminology", "monkeypatching" ]
I am trying to understand, what is a monkey patch? Is that something like methods/operators overloading or delegating? Does it have anything common with these things?
No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime. For instance, consider a class that has a method `get_data`. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don...
What is a monkey patch?
5,626,193
208
2011-04-11T19:05:41Z
5,626,255
9
2011-04-11T19:11:13Z
[ "python", "terminology", "monkeypatching" ]
I am trying to understand, what is a monkey patch? Is that something like methods/operators overloading or delegating? Does it have anything common with these things?
First: monkey patching is an evil hack (in my opinion). It is often used to replace a method on the module or class level with a custom implementation. The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code thro...
What is a monkey patch?
5,626,193
208
2011-04-11T19:05:41Z
6,647,776
206
2011-07-11T08:52:36Z
[ "python", "terminology", "monkeypatching" ]
I am trying to understand, what is a monkey patch? Is that something like methods/operators overloading or delegating? Does it have anything common with these things?
> A MonkeyPatch is a piece of Python code which extends or modifies > other code at runtime (typically at startup). A simple example looks like this: ``` from SomeOtherProduct.SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass.speak = speak ``` **Source:** [MonkeyPatch](https:...
What is a monkey patch?
5,626,193
208
2011-04-11T19:05:41Z
27,466,499
51
2014-12-14T04:57:48Z
[ "python", "terminology", "monkeypatching" ]
I am trying to understand, what is a monkey patch? Is that something like methods/operators overloading or delegating? Does it have anything common with these things?
> # What is a monkey patch? Simply put, monkey patching is making changes to a module or class while the program is running. # Example in usage There's an example of Monkey-Patching in the Pandas documentation: ``` import pandas as pd def just_foo_cols(self): """Get a list of column names containing the string ...
python print statement with utf-8 and nohup
5,626,960
10
2011-04-11T20:11:32Z
5,627,087
14
2011-04-11T20:22:12Z
[ "python", "utf-8", "nohup" ]
I have a some python code that prints log messages. When run at the command line, it does fine with utf-8. Log messages that contain special characters print out fine. However, when run in the background under nohup, it barfs on utf-8 characters. ``` nohup python2.7 myProgram.py & ``` The error I see is the usual "tr...
Use [PYTHONIOENCODING](http://docs.python.org/using/cmdline.html#envvar-PYTHONIOENCODING): ``` export PYTHONIOENCODING=utf-8 nohup python2.7 myProgram.py & ``` --- For example, if **myProgram.py**: ``` unicode_obj=u'\N{INFINITY}' print(unicode_obj) ``` then running ``` nohup python2.7 myProgram.py > /tmp/test & ...
Write PDF file from URL using urllib2
5,627,083
11
2011-04-11T20:21:47Z
5,627,165
16
2011-04-11T20:29:07Z
[ "python", "urllib2" ]
I'm trying to save a dynamic pdf file generated from a web server using python's module urllib2. I use following code to get data from server and to write that data to a file in order to store the pdf in a local disk.: ``` import urllib2 import cookielib theurl = 'https://myweb.com/?pdf&var1=1' cj = cookielib.CookieJ...
Try changing, ``` FILE = open('report.pdf', "w") ``` to ``` FILE = open('report.pdf', "wb") ``` The extra 'b' indicates to write in binary mode. Currently you are writing a binary file in ASCII/text mode.
Using python string formatting in a django template
5,627,525
11
2011-04-11T21:01:57Z
5,627,788
12
2011-04-11T21:28:42Z
[ "python", "django", "django-templates" ]
Is there an easy way to use python string formatting from within a django template? That is, I'd like to be able to do something like this in a template ``` {{ variable|%.3f }} ``` I know in this case, one can just use ``` {{ variable|floatformat:3 }} ``` But I'd really like to be able to generically use any python...
``` {{ variable|stringformat:".3f" }} ``` *Source: <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat>*
String formatting with "{0:d}".format gives Unknown format code 'd' for object of type 'float'
5,627,605
5
2011-04-11T21:10:37Z
5,627,624
7
2011-04-11T21:12:44Z
[ "python", "string-formatting" ]
If I understood the docs correctly, in python 2.6.5 string formatting "{0:d}" would do the same as "%d" with the String.format() way of formatting strings ``` " I have {0:d} dollars on me ".format(100.113) ``` Should print "I have 100 dollars on me " However I get the error : > ValueError: Unknown format code 'd' >...
That error is signifying that you are passing a float to the format code expecting an integer. Use `{0:f}` instead. Thus: ``` "I have {0:f} dollars on me".format(100.113) ``` will give: ``` 'I have 100.113000 dollars on me' ```
How to get generated captcha image using mechanize
5,627,923
9
2011-04-11T21:43:09Z
5,992,549
11
2011-05-13T13:24:13Z
[ "python", "captcha", "mechanize" ]
I'm trying to use python and mechanize to send sms from my mobile provider website. The problem is that form has a captcha image. Using mechanize I can get the link to the image, but it's different all the time I access that link. Is there any way to get exact picture from mechanize?
This is a rough example of how to get the image, note that mechanize uses cookies so any cookies received will be sent to the server with the request for the image (this is probably what you *want*). ``` br = mechanize.Browser() response = br.open('http://example.com') soup = BeautifulSoup(response.get_data()) img = s...
Execute statement every N iterations in Python
5,628,055
7
2011-04-11T22:01:14Z
5,628,106
10
2011-04-11T22:07:03Z
[ "python", "loops" ]
I have a very long loop, and I would like to check the status every N iterations, in my specific case I have a loop of 10 million elements and I want to print a short report every millionth iteration. So, currently I am doing just (n is the iteration counter): ``` if (n % 1000000==0): print('Progress report...') ...
Is it really slowing down? You have to try and see for yourself. It won't be much of a slowdown, but if we're talking about nanoseconds it may be considerable. Alternatively you can convert one 10 million loop to two smaller loops: ``` m = 1000000 for i in range(10): for i in range(m): // do sth print(...
Execute statement every N iterations in Python
5,628,055
7
2011-04-11T22:01:14Z
5,628,116
9
2011-04-11T22:08:19Z
[ "python", "loops" ]
I have a very long loop, and I would like to check the status every N iterations, in my specific case I have a loop of 10 million elements and I want to print a short report every millionth iteration. So, currently I am doing just (n is the iteration counter): ``` if (n % 1000000==0): print('Progress report...') ...
How about keeping a counter and resetting it to zero when you reach the wanted number? Adding and checking equality is faster than modulo. ``` printcounter = 0 # Whatever a while loop is in Python while (...): ... if (printcounter == 1000000): print('Progress report...') printcounter = 0 ...
Test if a class is inherited from another
5,628,084
38
2011-04-11T22:05:23Z
5,628,127
64
2011-04-11T22:09:17Z
[ "python", "django", "unit-testing" ]
This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set. ``` def quiz_form_factory(question): properties = { 'question' : forms.IntegerField(widget=forms.HiddenInput, initial=question.id),...
Use [issubclass(myclass, parentclass)](http://docs.python.org/library/functions.html#issubclass). In your case: ``` self.assertTrue( issubclass(QuizForm, forms.Form) ) ```
Key Order in Python Dictionaries
5,629,023
24
2011-04-12T00:21:38Z
5,629,043
9
2011-04-12T00:24:55Z
[ "python", "dictionary" ]
Code: ``` d = {'a': 0, 'b': 1, 'c': 2} l = d.keys() print l ``` This prints ['a', 'c', 'b']. I'm unsure of how the method **keys** determines the order of the keywords within **l**. However, I'd like to be able to retrive the keywords in the "proper" order. The proper order of course would create the list ['a', 'b',...
Just sort the list when you want to use it. ``` l = sorted(d.keys()) ```
Key Order in Python Dictionaries
5,629,023
24
2011-04-12T00:21:38Z
5,629,045
7
2011-04-12T00:25:08Z
[ "python", "dictionary" ]
Code: ``` d = {'a': 0, 'b': 1, 'c': 2} l = d.keys() print l ``` This prints ['a', 'c', 'b']. I'm unsure of how the method **keys** determines the order of the keywords within **l**. However, I'd like to be able to retrive the keywords in the "proper" order. The proper order of course would create the list ['a', 'b',...
From <http://docs.python.org/tutorial/datastructures.html>: "The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."
Key Order in Python Dictionaries
5,629,023
24
2011-04-12T00:21:38Z
5,629,046
26
2011-04-12T00:25:09Z
[ "python", "dictionary" ]
Code: ``` d = {'a': 0, 'b': 1, 'c': 2} l = d.keys() print l ``` This prints ['a', 'c', 'b']. I'm unsure of how the method **keys** determines the order of the keywords within **l**. However, I'd like to be able to retrive the keywords in the "proper" order. The proper order of course would create the list ['a', 'b',...
``` >>> print sorted(d.keys()) ['a', 'b', 'c'] ``` Use the [sorted function](http://docs.python.org/library/functions.html#sorted), which sorts the iterable passed in. The `.keys()` method returns the keys in an arbitrary order.