title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python modules appearing out of no where
3,122,638
2
2010-06-26T03:55:00Z
3,122,650
8
2010-06-26T04:01:43Z
[ "python", "google-app-engine" ]
Today one peculiar thing happened to me .I was trying to get a hang of appengine and djago on www.shell.appspot.com when i entered `dir(django)` the o/p i got was ``` ['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'conf', 'core', 'template', 'utils'] ``` but still i tried ``` from django ...
The statement `from package import module` loads (if it had not been previously loaded) `package/module.py` (after first loading `package/__init__.py` if it hadn't previously loaded it already) and adds `'module'` as an entry in the package (as well as a variable in the current scope). So `dir(package)` will show a `'m...
Splitting a 16 bit int into two 8 bit ints in python
3,123,371
4
2010-06-26T09:26:40Z
3,123,398
9
2010-06-26T09:37:22Z
[ "python", "math" ]
I have to convert a given 16 bit integer into two 8 bit integers, which are then taken and used as output, where they are headed takes the two 8 bit integers and recombines them as 16 bit input (unfortunately out of my control). My solution works, but feels unclean. For the coarse number I am bit shifting the original ...
I would do ``` c = (x >> 8) & 0xff f = x & 0xff ``` It is "safer", see e.g. ``` >>> (10303 >> 8) &0xff 40 >>> (1030333333 >> 8) &0xff 163 >>> (1030333333 >> 8) 4024739 ``` Since in python you can't "controll" if the number is or not a 16bit, you have to "force" it into a at-most 16bit value; not needed if you're s...
Splitting a 16 bit int into two 8 bit ints in python
3,123,371
4
2010-06-26T09:26:40Z
3,124,374
7
2010-06-26T15:23:14Z
[ "python", "math" ]
I have to convert a given 16 bit integer into two 8 bit integers, which are then taken and used as output, where they are headed takes the two 8 bit integers and recombines them as 16 bit input (unfortunately out of my control). My solution works, but feels unclean. For the coarse number I am bit shifting the original ...
In python, bit-fiddling doesn't have any particular advantage, so I would go with: ``` c, f= divmod(your_number, 256) ``` EDIT: To make your intention even more obvious to the powers-of-two-challenged source viewer (if such a beast exists), you can replace the plain `256` with much more colourful alternatives, like `...
How to make an auto-filled and auto-incrementing field in django admin
3,123,796
11
2010-06-26T12:04:05Z
3,124,223
15
2010-06-26T14:38:05Z
[ "python", "django", "django-models", "django-admin", "default-value" ]
[**Update:** Changed question title to be more specific] Sorry if I didn't make the question very well, I can't figure how to do this: ``` class WhatEver(): number = model.IntegerField('Just a Field', default=callablefunction) ... ``` Where `callablefunction` does this query: ``` from myproject.app.models impor...
**Got it!** I hope this will help everyone that has any problems making a auto-filled and auto-incrementing field in django. The solution is this, I'll put my code: ``` class Cliente(models.Model): """This is the client data model, it holds all client information. This docstring has to be improved.""" d...
In Python, how do you use decimal module in a script rather than the interpreter?
3,124,905
6
2010-06-26T17:48:56Z
3,124,989
17
2010-06-26T18:12:48Z
[ "python", "decimal" ]
I'm using Python 2.5.4 and trying to use the decimal module. When I use it in the interpreter, I don't have a problem. For example, this works: ``` >>> from decimal import * >>> Decimal('1.2')+ Decimal('2.3') Decimal("3.5") ``` But, when I put the following code: ``` from decimal import * print Decimal('1.2')+Decima...
You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised. To solve this problem simply rename the script, as long as you are jus...
Forcing to make floating point calculations
3,125,192
4
2010-06-26T19:12:20Z
3,125,206
11
2010-06-26T19:16:06Z
[ "python", "ironpython", "expression" ]
In IronPython is there any way to force the expression containing integer values to be calculated as floating point. For instance, I'd like the expression ``` 1/3 ``` to be evaluated as ``` 1./3. ``` with the result 0.333... I need this to make a simple run-time expression calculator within a C# project by means o...
``` from __future__ import division print 1 / 3 print 1 // 3 ```
Forcing to make floating point calculations
3,125,192
4
2010-06-26T19:12:20Z
3,125,209
8
2010-06-26T19:16:21Z
[ "python", "ironpython", "expression" ]
In IronPython is there any way to force the expression containing integer values to be calculated as floating point. For instance, I'd like the expression ``` 1/3 ``` to be evaluated as ``` 1./3. ``` with the result 0.333... I need this to make a simple run-time expression calculator within a C# project by means o...
You may force a floating point division like any of these, no matter if anything is imported from `__future__`: ``` print val1 / (val2 + 0.0) print (val1 + 0.0) / val2 print float(val1) / val2 print val1 / float(val2) ```
Disable all `pylint` 'Convention' messages
3,125,333
11
2010-06-26T20:02:59Z
3,125,349
10
2010-06-26T20:10:39Z
[ "python", "pylint" ]
### Background I find `pylint` useful, but I also find it is horrifically undocumented, has painfully verbose output, and lacks an intuitive interface. I'd like to use pylint, but it keeps pumping out an absurd number of pointless 'convention' messages, e.g. `C: 2: Line too long (137/80)` etc. ### Question If I cou...
If I'm not mistaken, you should be able to use `--disable-msg-cat=C` (can't remember whether it's uppercase or lowercase or both) to accomplish this. UPDATE: In later versions of pylint, you should use `--disable=C`
python subprocess hide stdout and wait it to complete
3,125,525
5
2010-06-26T21:14:12Z
3,125,581
18
2010-06-26T21:40:34Z
[ "python", "synchronization", "subprocess", "stdout" ]
I have this code: ``` def method_a(self): command_line = 'somtoolbox GrowingSOM ' + som_prop_path subprocess.Popen(shlex.split(command_line)) ...... def method_b(self): ..... .... ``` and like you all see, method\_a has a subprocess that is calling the somtoolbox program. But this program have a long std...
The best way to do that is to redirect the output into /dev/null. You can do that like this: ``` devnull = open('/dev/null', 'w') subprocess.Popen(shlex.split(command_line), stdout=devnull) ``` Then to wait until it's done, you can use .wait() on the Popen object, getting you to this: ``` devnull = open('/dev/null',...
Does NLTK have a tool for dependency parsing?
3,125,926
14
2010-06-27T00:11:58Z
3,126,853
12
2010-06-27T08:38:47Z
[ "python", "nlp", "nltk" ]
I'm building a NLP application and have been using the Stanford Parser for most of my parsing work, but I would like to start using Python. So far, NLTK seems like the best bet, but I cannot figure out how to parse grammatical dependencies. I.e. this is an example from the Stanford Parser. I want to be able to produce...
NLTK includes support for using the **[MaltParser](http://maltparser.org/)**, see **[nltk.parse.malt.MaltParser](http://nltk.googlecode.com/svn/trunk/doc/api/nltk.parse.malt.MaltParser-class.html)**. The pretrained English model for the MaltParser that's available **[here](http://maltparser.org/mco/english_parser/engm...
Google App Engine: upload_data fails because "target machine actively refused it" on devserver
3,126,036
4
2010-06-27T01:18:52Z
3,129,455
10
2010-06-28T00:26:06Z
[ "python", "google-app-engine", "urlopen" ]
I'm trying to upload data from a CSV to my app using the devserver: ``` appcfg.py upload_data --config_file="DataLoader.py" --filename="data.csv" --kind=Foo --url=http://localhost:8083/remote_api "path/to/app" ``` The result: ``` Application: appname; version: 1. Uploading data records. [INFO ] Logging to bulkloa...
Decrease the number of threads to 4 by adding the command line option `--num_threads=4` If it still doesn't work decrease further the number of threads.
How to represent matrices in python
3,127,404
18
2010-06-27T13:05:03Z
3,127,415
10
2010-06-27T13:08:46Z
[ "python", "matrix" ]
How can I represent matrices in python?
Python doesn't have matrices. You can use a list of lists or [NumPy](http://numpy.scipy.org/)
How to represent matrices in python
3,127,404
18
2010-06-27T13:05:03Z
3,127,423
33
2010-06-27T13:10:22Z
[ "python", "matrix" ]
How can I represent matrices in python?
Take a look at [this answer](http://stackoverflow.com/questions/211160/python-inverse-of-a-matrix/211174#211174): ``` from numpy import matrix from numpy import linalg A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix. x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector)...
concat multiple block in jinja2?
3,127,502
5
2010-06-27T13:36:57Z
3,146,588
13
2010-06-30T05:01:11Z
[ "python", "templates", "jinja2" ]
I use jinja2 for my template engine in python. i would like to join content of multiple block and would like to render it at the end of the template, just before tag. { they are various JavaScript snippets throughout the code in multiple template which i would like to move to the end of the file, how do i do it ? } e...
I assume that by multiple children, you mean that there are templates inheriting from templates inheriting from templates ... inheriting from the base template. If that's the case, you need to define the same `javascript` block in each template and call [`super()`](http://jinja.pocoo.org/2/documentation/templates#super...
Is there any linux distribution that comes with python 3?
3,127,715
6
2010-06-27T14:49:38Z
3,127,755
11
2010-06-27T15:05:22Z
[ "python", "linux", "python-3.x" ]
I would like to know if there is any Linux distribution where you can easily install and use Python 3. This means a distribution that will provide not only Python 3 binaries and updates but also python modules. I know that probably we are not going to see any python 3 as the default python interpretor so soon but at l...
Ubuntu 10.04 comes by default w/ Python 2.6.5, but the following python 3 packages are in the standard repositories as well: ``` python3 python3.1-minimal python3-dev python3.0 python3.1-profiler python3-doc python3.1 python3.1-tk python3-examples pytho...
Items ordering in Python dictionary
3,127,945
5
2010-06-27T16:17:01Z
3,127,956
21
2010-06-27T16:22:53Z
[ "python", "dictionary" ]
I am in simple doubt... I created the following dictionary: ``` >>> alpha={'a': 10, 'b': 5, 'c': 11} ``` But, when I want to see the dictionary keys and values I got: ``` >>> alpha {'a': 10, 'c': 11, 'b': 5} ``` See that the "b" and "c" has swapped their position. How can I make the position be the same of the mome...
Dictionaries are unordered containers - if you want to preserve order, you can use `collections.OrderedDict` (Python 2.7 or later), or use another container type which is naturally order-preserving. Generally if you have an access pattern that cares about ordered retrieval then a dictionary is solving a problem you do...
Git library for Ruby or Python?
3,128,104
7
2010-06-27T17:04:41Z
3,128,559
9
2010-06-27T19:16:37Z
[ "python", "ruby", "git" ]
I'm looking for a Ruby or Python implementation of the Git client that can be used to update and commit changes in a local repository. I prefer if the library does not use shell commands at all but keeps everything in "pure code". Are there any? Thank you in advance.
There's also [Dulwich](http://pypi.python.org/pypi/dulwich), a Python implementation of the Git file formats and protocols.
Python script header
3,128,669
43
2010-06-27T19:50:26Z
3,129,622
46
2010-06-28T01:33:34Z
[ "python", "scripting" ]
The typical header should be ``` #!/usr/bin/env python ``` But I found below also works when executing the script like `$python ./my_script.py` ``` #!/usr/bin/python #!python ``` What's difference between these 2 headers? What could be the problem for 2nd one? Please also discussing the case for python interpreter ...
First, any time you run a script using the interpreter explicitly, as in ``` $ python ./my_script.py $ ksh ~/bin/redouble.sh $ lua5.1 /usr/local/bin/osbf3 ``` the `#!` line is always ignored. The `#!` line is a Unix feature of *executable* scripts only, and you can see it documented in full on the [man page for `exec...
What is paster and how do I install it?
3,128,727
7
2010-06-27T20:07:14Z
3,128,782
7
2010-06-27T20:27:51Z
[ "python", "paster" ]
I am installing an application and have installed `python` and `easy_install`. I now have two steps to complete: ``` 5. Make a config file as follows:: paster make-config openbiblio development.ini 6. Tweak the config file as appropriate and then setup the application:: paster setup-app config.ini ``` I ha...
I think you're looking for [pythonpaste](http://pythonpaste.org/script/)'s "Paste Script", which you can download from [here](http://pypi.python.org/pypi/PasteScript) and then unpack and install.
What is the Python equivalent of Perl's DBI?
3,128,961
7
2010-06-27T21:28:49Z
3,129,009
8
2010-06-27T21:48:14Z
[ "python" ]
What is Python's equivalent of Perl's DBI and how do I use it? More specifically, what is the Python equivalent of the following Perl code? ``` use DBI; # connect to a MySQL database my $dbh = DBI->connect("dbi:mysql:database=$database; host=localhost; port=3306", $user, $pass); # select and read a few rows my $sth ...
``` import MySQLdb.cursors db = MySQLdb.connect(db=database, host=localhost, port=3306, user=user, passwd=pass, cursorclass=MySQLdb.cursors.DictCursor) cur = db.cursor() #this is not string interpolation, everything is quoted for you automatically cur.execute("select id, name...
What is the Python equivalent of Perl's DBI?
3,128,961
7
2010-06-27T21:28:49Z
3,129,919
14
2010-06-28T03:36:47Z
[ "python" ]
What is Python's equivalent of Perl's DBI and how do I use it? More specifically, what is the Python equivalent of the following Perl code? ``` use DBI; # connect to a MySQL database my $dbh = DBI->connect("dbi:mysql:database=$database; host=localhost; port=3306", $user, $pass); # select and read a few rows my $sth ...
Shylent's post meets the OP's request for equivalent code. However it does not adequately address the issue of what is Python's equivalent to the Perl DBI. For those not familiar with [Perl's DBI](http://search.cpan.org/perldoc?DBI), it provides a common interface for all database systems. To add support for new stora...
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
3,129,330
30
2010-06-27T23:41:32Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
On Windows: ``` from win32api import GetSystemMetrics print "Width =", GetSystemMetrics(0) print "Height =", GetSystemMetrics(1) ``` Based on this <http://bytes.com/topic/python/answers/618587-screen-size-resolution-win32-python>
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
3,129,494
31
2010-06-28T00:42:33Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
If you're using wxWindows, you can simply do: ``` import wx wx.App(False) # the wx.App object must be created first. print(wx.GetDisplaySize()) # returns a tuple ```
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
3,129,524
60
2010-06-28T00:54:26Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
In Windows, you can also use ctypes: ``` import ctypes user32 = ctypes.windll.user32 screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) ``` so that you don't need to install the pywin32 package; it doesn't need anything that doesn't come with Python itself.
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
3,129,567
11
2010-06-28T01:09:39Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
And for completeness, Mac OS X ``` import AppKit [(screen.frame().size.width, screen.frame().size.height) for screen in AppKit.NSScreen.screens()] ``` will give you a list of tuples containing all screen sizes (if multiple monitors present)
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
16,529,695
14
2013-05-13T19:29:23Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
Taken directly from an answer to this post: [How to get the screen size in Tkinter?](http://stackoverflow.com/questions/3949844/how-to-get-the-screen-size-in-tkinter/3949983#3949983) ``` import tkinter as tk root = tk.Tk() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() ```
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
17,475,065
8
2013-07-04T16:42:51Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
If you are using the `Qt` toolkit specifically `PySide`, you can do the following: ``` from PySide import QtGui import sys app = QtGui.QApplication(sys.argv) screen_rect = app.desktop().screenGeometry() width, height = screen_rect.width(), screen_rect.height() ```
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
23,608,025
9
2014-05-12T11:39:44Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
Here is a quick little Python program that will display the information about your multi-monitor setup: ``` import gtk window = gtk.Window() # the screen contains all monitors screen = window.get_screen() print "screen size: %d x %d" % (gtk.gdk.screen_width(),gtk.gdk.screen_height()) # collect data about each monit...
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
26,539,115
7
2014-10-23T23:20:59Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
On Windows 8.1 I am not getting the correct resolution from either ctypes or tk. Other people are having this same problem for ctypes: [getsystemmetrics returns wrong screen size](http://stackoverflow.com/questions/2630392/getsystemmetrics-returns-wrong-value-for-sm-cxscreen) To get the correct full resolution of a hig...
How do I get monitor resolution in Python?
3,129,322
46
2010-06-27T23:39:21Z
31,171,430
10
2015-07-01T20:50:47Z
[ "python", "screen", "resolution" ]
What is the simplest way to get monitor resolution (preferably in a tuple)?
FYI I created a PyPI module for this reason: ``` pip install screeninfo ``` The code: ``` from screeninfo import get_monitors for m in get_monitors(): print(str(m)) ``` Result: ``` monitor(1920x1080+1920+0) monitor(1920x1080+0+0) ``` **It supports multi monitor environments**. Its goal is to be cross platform...
Python 2 vs. Python 3 - urllib formats
3,129,355
19
2010-06-27T23:50:22Z
3,129,407
14
2010-06-28T00:06:03Z
[ "python", "json", "python-3.x", "compatibility", "urllib" ]
I'm getting really tired of trying to figure out why this code works in Python 2 and not in Python 3. I'm just trying to grab a page of json and then parse it. Here's the code in Python 2: ``` import urllib, json response = urllib.urlopen("http://reddit.com/.json") content = response.read() data = json.loads(content) ...
The code you post is presumably due to wrong cut-and-paste operations because it's clearly wrong in both versions (`f.read()` fails because there's no `f` barename defined). In Py3, `ur = response.decode('utf8')` works perfectly well for me, as does the following `json.loads(ur)`. Maybe the wrong copys-and-pastes affe...
Python can't locate distutils_path on Mac OSX
3,129,852
21
2010-06-28T03:07:40Z
3,129,956
7
2010-06-28T03:49:07Z
[ "python", "osx", "virtualenv", "distutils" ]
I've been using virtualenv + pip for python development. I'm not sure what happened, but suddenly whenever I try to run a command-line tool or import libraries, I get this error message: ``` Traceback (most recent call last): File "/Users/kyle/.virtualenvs/fj/bin/pip", line 4, in <module> import pkg_resources ...
Turns out the problem was that Migration Assistant, for whatever reason, didn't copy over tools like `gcc` -- I reinstalled Xcode and things work properly again.
Python can't locate distutils_path on Mac OSX
3,129,852
21
2010-06-28T03:07:40Z
8,393,396
33
2011-12-05T23:29:34Z
[ "python", "osx", "virtualenv", "distutils" ]
I've been using virtualenv + pip for python development. I'm not sure what happened, but suddenly whenever I try to run a command-line tool or import libraries, I get this error message: ``` Traceback (most recent call last): File "/Users/kyle/.virtualenvs/fj/bin/pip", line 4, in <module> import pkg_resources ...
I encountered this `distutils/__init__.py` problem when transitioning to OS X 10.7 Lion (from OS X 10.5 Leopard) and using Migration Assistant. I've already installed Xcode 3.2.6 -- thus resolving the missing install\_name\_tool problem. Migration Assistant brought over my previous virtualenvs, but since they were bas...
Python can't locate distutils_path on Mac OSX
3,129,852
21
2010-06-28T03:07:40Z
10,167,039
22
2012-04-15T23:19:18Z
[ "python", "osx", "virtualenv", "distutils" ]
I've been using virtualenv + pip for python development. I'm not sure what happened, but suddenly whenever I try to run a command-line tool or import libraries, I get this error message: ``` Traceback (most recent call last): File "/Users/kyle/.virtualenvs/fj/bin/pip", line 4, in <module> import pkg_resources ...
``` > cd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/ > sudo touch __init__.py ``` Out-of-the-box python on Lion comes without the python source - just the compiled pyc/pyo files. However virtualenv goes looking for the distutils source file just to confirm where it is. Turns out a...
Matplotlib savefig image trim
3,130,072
18
2010-06-28T04:35:02Z
3,130,349
30
2010-06-28T05:57:45Z
[ "python", "matplotlib" ]
The following sample code will produce a basic line plot with no axes and save it as an SVG file: ``` import matplotlib.pyplot as plt plt.axis('off') plt.plot([1,3,1,2,3]) plt.plot([3,1,1,2,1]) plt.savefig("out.svg", transparent = True) ``` How do I set the resolution / dimensions of the image? There is padding on al...
I am continually amazed at how many ways there are to do the same thing in matplotlib. As such, I am sure that someone can make this code much more terse. At any rate, this should clearly demonstrate how to go about solving your problem. ``` >>> import pylab >>> fig = pylab.figure() >>> pylab.axis('off') (0.0, 1....
Stopping a Reduce() operation mid way. Functional way of doing partial running sum
3,130,352
13
2010-06-28T05:59:05Z
3,130,443
9
2010-06-28T06:24:59Z
[ "python", "f#", "functional-programming" ]
I have been doing some functional programming and had a question. Perhaps I might be missing something but is there any way to stop a "reduce()" function midway? Lets say when I reach a certain condition? The idea somehow seems anti functional. I haven't seen any such option in python or F#, As an example, lets say I ...
Reduce is often used in combination with map. Google for example has developed a map-reduce framework for querying their databases and this map-reduce pattern is now used in several other projects (e.g. CouchDB, Hadoop, etc). First, you need to map the `input` variables `[2, 1, 3, 4, 5]` to something like: ``` [(1, 2...
Stopping a Reduce() operation mid way. Functional way of doing partial running sum
3,130,352
13
2010-06-28T05:59:05Z
3,131,599
8
2010-06-28T10:27:44Z
[ "python", "f#", "functional-programming" ]
I have been doing some functional programming and had a question. Perhaps I might be missing something but is there any way to stop a "reduce()" function midway? Lets say when I reach a certain condition? The idea somehow seems anti functional. I haven't seen any such option in python or F#, As an example, lets say I ...
I agree with JaredPar that writing your own recursive function that behaves similarly to `fold`, but allows you to stop the computation earlier is the best approach. The way I would write it is a bit more general (so that you can use the function for any situation where you need *folding* that can *stop earlier*): ```...
How do I detect the currently focused application?
3,130,912
6
2010-06-28T08:16:04Z
3,131,644
8
2010-06-28T10:35:24Z
[ "python", "x11", "xlib" ]
I'd like to be able to track which application is currently focused on my X11 display from Python. The intent is to tie it into a timetracking tool so that I can keep track of how much time I spend being unproductive. I already found this code at <http://thpinfo.com/2007/09/x11-idle-time-and-focused-window-in.html>: ...
Whoo! I figured it out myself: ``` import Xlib.display display = Xlib.display.Display() window = display.get_input_focus().focus wmname = window.get_wm_name() wmclass = window.get_wm_class() if wmclass is None and wmname is None: window = window.query_tree().parent wmname = window.get_wm_name() print "WM Name:...
Error handling when importing modules
3,131,217
14
2010-06-28T09:15:09Z
3,131,251
17
2010-06-28T09:22:57Z
[ "python", "error-handling", "module", "cross-platform" ]
This probably has an obvious answer, but I'm a beginner. I've got a "module" (really just a file with a bunch of functions I often use) at the beginning of which I import a number of other modules. Because I work on many systems, however, not all modules may be able to load on any particular machine. To make things sli...
I don't think `try except` block is un-pythonic; instead it's a common way to handle import on Python. Quoting [Dive into Python](http://diveintopython.net/file_handling/index.html): > There are a lot of other uses for > exceptions besides handling actual > error conditions. **A common use in the > standard Python li...
Python: always use __new__ instead of __init__?
3,131,488
24
2010-06-28T10:05:47Z
3,133,504
19
2010-06-28T14:59:06Z
[ "python", "new-style-class" ]
I understand how both `__init__` and `__new__` work. I'm wondering if there is anything `__init__` can do that `__new__` cannot? i.e. can use of `__init__` be replaced by the following pattern: ``` class MySubclass(object): def __new__(cls, *args, **kwargs): self = super(MySubclass, cls).__new__(cls, *arg...
So, the class of a class is typically `type`, and when you call `Class()` the `__call__()` method on `Class`'s class handles that. I believe `type.__call__()` is implemented more or less like this: ``` def __call__(cls, *args, **kwargs): # should do the same thing as type.__call__ obj = cls.__new__(cls, *args,...
How do I access the command history from IDLE?
3,132,265
71
2010-06-28T12:20:13Z
3,132,305
33
2010-06-28T12:25:01Z
[ "python", "python-idle" ]
On bash or Window's Command Prompt, we can press the up arrow on keyboard to get the last command, and edit it, and press ENTER again to see the result. But in Python's IDLE 2.6.5 or 3.1.2, it seems if our statement prints out 25 lines, we need to press the up arrow 25 times to that last command, and press ENTER for i...
just use `Alt+P` to go up. Similarly, `Alt+N` could be used to go down.
How do I access the command history from IDLE?
3,132,265
71
2010-06-28T12:20:13Z
3,132,309
102
2010-06-28T12:25:52Z
[ "python", "python-idle" ]
On bash or Window's Command Prompt, we can press the up arrow on keyboard to get the last command, and edit it, and press ENTER again to see the result. But in Python's IDLE 2.6.5 or 3.1.2, it seems if our statement prints out 25 lines, we need to press the up arrow 25 times to that last command, and press ENTER for i...
I think you are looking for the `history-previous` action, which is bound to `alt`+`p` by default. You can remap it in Options->Configure IDLE->Keys Incidentally, why don't you try a better (less ugly, for starters) shell like [bpython](http://bpython-interpreter.org/) or [ipython](http://ipython.scipy.org/moin/)?
How do I access the command history from IDLE?
3,132,265
71
2010-06-28T12:20:13Z
26,785,641
7
2014-11-06T17:27:18Z
[ "python", "python-idle" ]
On bash or Window's Command Prompt, we can press the up arrow on keyboard to get the last command, and edit it, and press ENTER again to see the result. But in Python's IDLE 2.6.5 or 3.1.2, it seems if our statement prints out 25 lines, we need to press the up arrow 25 times to that last command, and press ENTER for i...
If you're on mac, it's `ctrl`+`p`.
How to write data to an excel file?
3,133,142
4
2010-06-28T14:18:22Z
3,133,170
11
2010-06-28T14:22:01Z
[ "python", "excel" ]
I have some data that I'd like to save in an excel file. How does one do this in python?
There's a great python module called [XLWT](http://pypi.python.org/pypi/xlwt). I'd recommend using that... it writes native Excel files instead of CSVs. Supports formulas, etc too. [Documentation](http://www.python-excel.org/) (borrowed from Mark)
Convert Unix Timestamp to human format in Django with Python
3,133,486
5
2010-06-28T14:57:33Z
3,133,631
11
2010-06-28T15:13:13Z
[ "python", "django", "string", "datetime", "formatting" ]
I'd like to a convert unix timestamp I have in a string (ex. 1277722499.82) into a more humanized format (hh:mm:ss or similar). Is there an easy way to do this in python for a django app? This is outside of a template, in the model that I would like to do this. Thanks. **edit** I'm using the python function time.time(...
``` >>> import datetime >>> datestring = "1277722499.82" >>> dt = datetime.datetime.fromtimestamp(float(datestring)) >>> print dt 2010-06-28 11:54:59.820000 ```
Are Interfaces just "Syntactic Sugar"?
3,134,531
8
2010-06-28T17:12:34Z
3,134,617
11
2010-06-28T17:22:54Z
[ "php", "python", "oop", "interface" ]
I've been playing mostly with PHP and Python. I've been reading about Interfaces in OO programming and can't see an advantage in using it. Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well? Why do I need to create an Interface "with no implementation" - mainly a...
The usefulness of an interface is directly connected to the usefulness of static typing. If you're working in a dynamically-typed language like PHP or Python, interfaces truly don't add significantly to the *expressiveness* of the language. That is, any program that can be described as using interfaces can be expressed...
Are Interfaces just "Syntactic Sugar"?
3,134,531
8
2010-06-28T17:12:34Z
3,134,623
13
2010-06-28T17:23:38Z
[ "php", "python", "oop", "interface" ]
I've been playing mostly with PHP and Python. I've been reading about Interfaces in OO programming and can't see an advantage in using it. Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well? Why do I need to create an Interface "with no implementation" - mainly a...
First, and foremost, try not to compare and contrast between Python and Java. They are *different* languages, with *different* semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires. It's a lot like compar...
Python String Formats with SQL Wildcards and LIKE
3,134,691
16
2010-06-28T17:33:00Z
3,134,756
16
2010-06-28T17:42:04Z
[ "python", "sql", "format", "like" ]
I'm having a hard time getting some sql in python to correctly go through MySQLdb. It's pythons string formatting that is killing me. My sql statement is using the LIKE keyword with wildcards. I've tried a number of different things in Python. The problem is once I get one of them working, there's a line of code in My...
Those queries all appear to be vulnerable to SQL injection attacks. Try something like this instead: ``` curs.execute("""SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE %s""", ('%' + query + '%',...
Python String Formats with SQL Wildcards and LIKE
3,134,691
16
2010-06-28T17:33:00Z
3,134,842
9
2010-06-28T17:53:48Z
[ "python", "sql", "format", "like" ]
I'm having a hard time getting some sql in python to correctly go through MySQLdb. It's pythons string formatting that is killing me. My sql statement is using the LIKE keyword with wildcards. I've tried a number of different things in Python. The problem is once I get one of them working, there's a line of code in My...
It's not about string formatting but the problem is how queries should be executed according to db operations requirements in Python ([PEP 249](http://www.python.org/dev/peps/pep-0249/)) try something like this: ``` sql = "SELECT column FROM table WHERE col1=%s AND col2=%s" params = (col1_value, col2_value) cursor.e...
Pascal's triangle in python
3,134,813
4
2010-06-28T17:49:42Z
3,134,943
10
2010-06-28T18:07:07Z
[ "python" ]
So I'm making a Pascal's triangle and I can't figure out why this code isn't working. It prints out something like this ``` [] [1] [1, 2] [1, 3, 3] [1, 4, 6, 4] [1, 5, 10, 10, 5] [1, 6, 15, 20, 15, 6] [1, 7, 21, 35, 35, 21, 7] [1, 8, 28, 56, 70, 56, 28, 8] [1, 9, 36, 84, 126, 126, 84, 36, 9] ``` Which is almost corre...
I would change `PrintingList = list()` to `PrintingList = [newValue]`. `triangle(10)` then gives you the following: ``` [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] `...
Can I have two init functions in a python class?
3,134,829
4
2010-06-28T17:52:11Z
3,135,079
14
2010-06-28T18:26:57Z
[ "python", "init" ]
I'm porting some geolocation java code from <http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#Java> (shown below) to python. It can be initialized using two functions (fromDegrees or fromRadians). I thought I could do something like ``` class geoLocation: _radLat = 0 _radLong = 0 _degLat = 0 ...
Chose one default ( radians or degrees ) and stick with it. You can write a classmethod to automatically convert to the other: ``` class geoLocation: def __init__(self, lat, long): """init class from lat,long as radians""" @classmethod def fromDegrees(cls, dlat, dlong): """creat `cls` from...
How to Close an Image?
3,135,328
8
2010-06-28T19:03:04Z
3,135,368
14
2010-06-28T19:08:20Z
[ "python", "python-imaging-library" ]
I'm trying to take an image file, do some stuff to it and save the changes back to the original file. The problem I'm having is in overwriting the original image; there doesn't seem to be a reliable way to release the handle on `filename`. I need this content to be saved back to the same file because external processe...
You can provide a file-like object instead of a filename to the [`Image.open`](http://www.pythonware.com/library/pil/handbook/image.htm) function. So try this: ``` def do_post_processing(filename): with open(str(filename), 'rb') as f: image = Image.open(f) ... del new_image, image os.re...
Pythonic way to functions/methods with a lot of arguments
3,135,982
4
2010-06-28T20:45:12Z
3,136,007
17
2010-06-28T20:47:45Z
[ "python", "idioms", "idiomatic" ]
Imagine this: ``` def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa): pass ``` The line overpass the 79 characters, so, what's the pythonic way to multiline it?
You can include line breaks within parentheses (or brackets), e.g. ``` def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa): pass ``` (the amount of whitespace to include is, of course, up to you) But in this case, you could also consider ``` def method(self, *arg...
Pythonic way to functions/methods with a lot of arguments
3,135,982
4
2010-06-28T20:45:12Z
3,136,252
7
2010-06-28T21:25:00Z
[ "python", "idioms", "idiomatic" ]
Imagine this: ``` def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa): pass ``` The line overpass the 79 characters, so, what's the pythonic way to multiline it?
I think the 'Pythonic' way of answering this is to look deeper than syntax. Passing in that many arguments to a method indicates a likely problem with your object model. 1. First of all, do you really need to pass that many arguments to this method? Perhaps this is an indication that the work could be better done else...
Getting one value from a python tuple
3,136,059
33
2010-06-28T20:55:35Z
3,136,069
63
2010-06-28T20:56:50Z
[ "python", "tuples" ]
Is there a way to get one value from a tuple in python using expressions? ``` def Tup(): return (3,"hello") i = 5 + Tup(); ## I want to add just the three ``` I know I can do this: ``` (j,_) = Tup() i = 5 + j ``` But that would add a few dozen lines to my function, doubling its length.
You can write ``` i = 5 + Tup()[0] ``` Tuples can be indexed just like lists. The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work p...
Find and replace string values in Python list
3,136,689
55
2010-06-28T22:45:12Z
3,136,699
16
2010-06-28T22:47:05Z
[ "python", "list" ]
I got this list: ``` words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really'] ``` What I would like is to replace `[br]` with some fantastic value similar to `&lt;br /&gt;` and thus getting a new list: ``` words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really'] ```
You can use, for example: ``` words = [word.replace('[br]','<br />') for word in words] ```
Find and replace string values in Python list
3,136,689
55
2010-06-28T22:45:12Z
3,136,703
87
2010-06-28T22:47:36Z
[ "python", "list" ]
I got this list: ``` words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really'] ``` What I would like is to replace `[br]` with some fantastic value similar to `&lt;br /&gt;` and thus getting a new list: ``` words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really'] ```
`words = [w.replace('[br]', '<br />') for w in words]` called [List Comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)
Find and replace string values in Python list
3,136,689
55
2010-06-28T22:45:12Z
3,137,706
17
2010-06-29T03:42:41Z
[ "python", "list" ]
I got this list: ``` words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really'] ``` What I would like is to replace `[br]` with some fantastic value similar to `&lt;br /&gt;` and thus getting a new list: ``` words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really'] ```
Beside list comprehension, you can try **map** ``` >>> map(lambda x: str.replace(x, "[br]", "<br/>"), words) ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really'] ```
Matplotlib: one line, plotted against two related x axes in different units?
3,136,800
12
2010-06-28T23:10:49Z
3,137,008
8
2010-06-29T00:03:50Z
[ "python", "matplotlib" ]
I have one y variable, which I am trying to plot against two related x axes, on the top and bottom of the figure (e.g. y="number of things in cube", x1="side length of cube", x2="volume of cube"). I have y, x1, x2 in numpy arrays. The relationship between my x1 and x2 is one-to-one and monotonic, but not simple, and th...
For different x-scales use `twiny()` (think of this as "shared y-axes"). An example slightly adapted from the [matplotlib documentation](http://matplotlib.sourceforge.net/examples/api/two_scales.html): ``` import numpy as np import matplotlib.pyplot as plt # plot f(x)=x for two different x ranges x1 = np.linspace(0, ...
Find MacOSX version from Python
3,136,818
4
2010-06-28T23:14:49Z
3,136,853
8
2010-06-28T23:27:27Z
[ "python", "osx" ]
Currently I am using this: ``` def _get_mac_ver(): import subprocess p = subprocess.Popen(['sw_vers', '-productVersion'], stdout=subprocess.PIPE) stdout, stderr = p.communicate() return stdout.strip() ``` Is there a better version (eg: by using built-in Python API)? ``` >>> print _get_mac_ver() 10.6....
True to the philosophy that **python comes with batteries included**, there is a module in the standard library to do this: `platform`. See in particular the [`mac\_ver()' function](http://docs.python.org/library/platform.html#mac-os-platform): ``` >>> import platform >>> platform.mac_ver() ('10.6.3', ('', '', ''), '...
Passing all arguments of a function to another function
3,136,915
26
2010-06-28T23:41:29Z
3,137,022
20
2010-06-29T00:07:55Z
[ "python", "function", "arguments" ]
I want to pass all the arguments passed to a function(`func1`) as arguments to another function(`func2`) inside `func1` This can be done with `*args, *kwargs` in the called `func1` and passing them down to `func2`, but is there another way? Originally ``` def func1(*args, **kwargs): func2(*args, **kwargs) ``` bu...
*Explicit is better than implicit* but if you really don't want to type a few characters: ``` def func1(a=1, b=2, c=3): func2(**locals()) ``` `locals()` are all local variables, so you can't set any extra vars before calling `func2` or they will get passed too.
Python: Can a class forbid clients setting new attributes?
3,137,558
12
2010-06-29T02:58:31Z
3,137,596
15
2010-06-29T03:08:53Z
[ "python", "oop", "typing" ]
I just spent too long on a bug like the following: ``` >>> class Odp(): def __init__(self): self.foo = "bar" >>> o = Odp() >>> o.raw_foo = 3 # oops - meant o.foo ``` I have a class with an attribute. I was trying to set it, and wondering why it had no effect. Then, I went back to the original class defi...
You can implement a `__setattr__` method for the purpose -- that's much more robust than the `__slots__` which is often misused for the purpose (for example, `__slots__` is automatically "lost" when the class is inherited from, while `__setattr__` survives unless explicitly overridden). ``` def __setattr__(self, name,...
Using Python's @property decorator on dicts
3,137,685
4
2010-06-29T03:37:33Z
3,137,768
7
2010-06-29T04:02:49Z
[ "python", "properties", "setter", "dictionary", "getter" ]
I'm trying to use Python's `@property` decorator on a dict in a class. The idea is that I want a certain value (call it 'message') to be cleared after it is accessed. But I also want another value (call it 'last\_message') to contain the last set message, and keep it until another message is set. In my mind, this code ...
``` class MyDict(dict): def __setitem__(self,key,value): if key=='message': dict.__setitem__(self,'message','') dict.__setitem__(self,'last_message',value) else: dict.__setitem__(self,key,value) class A(object): def __init__(self): self._b = MyDi...
Is this correct way to import python scripts residing in arbitrary folders?
3,137,731
8
2010-06-29T03:50:05Z
3,137,914
9
2010-06-29T04:44:07Z
[ "python" ]
This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain. I have a few functions written in scripts in different directories, and I would like to be able to import them into new projects without having to...
The "official" and fully safe approach is the [imp](http://docs.python.org/library/imp.html?highlight=imp#module-imp) module of the standard Python library. Use [imp.find\_module](http://docs.python.org/library/imp.html?highlight=imp#imp.find_module) to find the module on your precisely-specified list of acceptable di...
Unescaping HTML in Django
3,138,588
3
2010-06-29T07:13:18Z
3,138,985
13
2010-06-29T08:25:52Z
[ "python", "html", "django", "encoding", "django-filter" ]
I have html encoded text which reads like this: ``` RT <a href="http://twitter.com/freuter">@freuter</a>... ``` I want this displayed as html but I am not sure if there is a filter which i can apply to this text to convert the html-encoded text back to html ... can someone help?
As Daniel says, use the `{{ tweet|safe }}` filter in the html, or mark it safe from the views. Use `django.template.mark_safe()`
In Eclipse PyDev is there a way to exclude arbitrary file-types from the Pydev Package explorer?
3,138,677
4
2010-06-29T07:26:20Z
3,141,573
7
2010-06-29T14:23:34Z
[ "python", "eclipse", "pydev" ]
If you click on the icon resembling a downard-pointing triangle in the PyDev Package Explorer and then select "Customize View", The "Available Customizations" pop-down allows the user to select which of a standard set of files are visible in the package explorer. That's great if you wish to exlude or include certain s...
To the left of the down arrow is the "Setup custom filters" button. You can enter custom filters delimited by commas. If that file name indeed has a comma in it, then you will have to enter the filter as `*cover` since `*,cover` is treated as two separate filters.
Qt programming: More productive in Python or C++?
3,139,414
30
2010-06-29T09:32:12Z
3,139,451
20
2010-06-29T09:38:36Z
[ "c++", "python", "qt", "pyqt" ]
Trying to dive into Qt big time but haven't done a large project with it yet. Currently using Python, but I've been thinking -- which is really the better language to use in terms of programmer productivity? In most comparisons between the languages, Python is the obvious answer, because you don't have to mess with me...
If one or the other, I'd actually suggest Python in spite of being a C++ enthusiast. With Python code you don't have to bother with the MOC, portability, build times, etc. Just compare the work involved in implementing a QT slot in C++ vs. PyQT or PySide, e.g. I find it to be much less of a pain to deal with widgets th...
Qt programming: More productive in Python or C++?
3,139,414
30
2010-06-29T09:32:12Z
3,139,545
16
2010-06-29T09:51:30Z
[ "c++", "python", "qt", "pyqt" ]
Trying to dive into Qt big time but haven't done a large project with it yet. Currently using Python, but I've been thinking -- which is really the better language to use in terms of programmer productivity? In most comparisons between the languages, Python is the obvious answer, because you don't have to mess with me...
**My Opinion** (having tried out C++ and Python in general and specifically in Qt case): Python always wins in terms of 'programmer productivity' and 'peace of mind'. PyQt represent Qt very well and hence question doesn't remain of "Qt with Python" or "Qt with C++", in general python is more productive unless off-cours...
Qt programming: More productive in Python or C++?
3,139,414
30
2010-06-29T09:32:12Z
7,457,626
7
2011-09-17T20:39:08Z
[ "c++", "python", "qt", "pyqt" ]
Trying to dive into Qt big time but haven't done a large project with it yet. Currently using Python, but I've been thinking -- which is really the better language to use in terms of programmer productivity? In most comparisons between the languages, Python is the obvious answer, because you don't have to mess with me...
definitely Python. Yes, people will say that Python is more productive without a reason. Some of the answers mention that you do not have to recompile. I will give you some more details 1. Python is one layer of abstraction over C++, so you can think and express your designs with less code. Your program might not run...
heapq.nlargest index of returned result in original sequence
3,139,869
4
2010-06-29T10:40:40Z
3,139,935
13
2010-06-29T10:51:11Z
[ "python", "sorting", "heap" ]
How do I return the index in the original list of the nth largest items of an iterable ``` heapq.nlargest(2, [100, 2, 400, 500, 400]) output = [(3,500), (2, 400)] ``` This already cost me a couple hours. I can't figure it out.
``` >>> seq = [100, 2, 400, 500, 400] >>> heapq.nlargest(2, enumerate(seq), key=lambda x: x[1]) [(3, 500), (2, 400)] ```
Project Euler - Problem 160
3,140,533
7
2010-06-29T12:21:46Z
3,140,676
7
2010-06-29T12:42:53Z
[ "python", "math", "optimization" ]
> For any N, let f(N) be the last five > digits before the trailing zeroes in > N!. For example, > > ``` > 9! = 362880 so f(9)=36288 > 10! = 3628800 so f(10)=36288 > 20! = 2432902008176640000 so f(20)=17664 > ``` > > Find f(1,000,000,000,000) I've successfully tackled this question for the given examples, my functi...
`mul` can get very big. Is that necessary? If I asked you to compute the last 5 non-zero digits of 1278348572934847283948561278387487189900038 \* 38758 *by hand*, exactly how many digits of the first number do you actually need to know?
how to delete files from amazon s3 bucket?
3,140,779
30
2010-06-29T12:54:07Z
3,264,960
60
2010-07-16T12:49:11Z
[ "python", "amazon-s3", "bucket" ]
i need to write a code in python that will delete the required file from the amazon s3 bucket, i am able to make connections to the amazon s3 bucket and also able to save files, i just want to know how to delete a file? please help if anyone knows.
found one more way to do it using the boto: ``` from boto.s3.connection import S3Connection, Bucket, Key conn = S3Connection(AWS_ACCESS_KEY, AWS_SECERET_KEY) b = Bucket(conn, S3_BUCKET_NAME) k = Key(b) k.key = 'images/my-images/'+filename b.delete_key(k) ```
Keyword argument in unpacking argument list/dict cases in Python
3,141,152
4
2010-06-29T13:35:46Z
3,141,216
8
2010-06-29T13:41:05Z
[ "python", "argument-passing" ]
For python, I could use unpacking arguments as follows. ``` def hello(x, *y, **z): print 'x', x print 'y', y print 'z', z hello(1, *[1,2,3], a=1,b=2,c=3) hello(1, *(1,2,3), **{'a':1,'b':2,'c':3}) ``` ``` x = 1 y = (1, 2, 3) z = {'a': 1, 'c': 3, 'b': 2} ``` But, I got an error if I use keyword argumen...
Regardless of the order in which they are specified, positional arguments get assigned prior to keyword arguments. In your case, the positional arguments are `(1, 2, 3)` and the keyword arguments are `x=1, a=1, b=2, c=3`. Because positional arguments get assigned first, the parameter `x` receives 1 and is not eligible ...
Good Example of Twisted IRC Server?
3,141,451
5
2010-06-29T14:08:36Z
3,142,408
8
2010-06-29T15:53:35Z
[ "python", "twisted", "irc" ]
I'm in the process of experimenting a bit with the twisted libraries for IRC servers/clients. I've found a few good examples of how to implement an IRC client but seem to find anything good on the server side of things. Could anybody provide some insight into how to create a basic IRC server in twisted? Edit: What abo...
Perhaps something like this? ``` exarkun@boson:/tmp/irc-server$ cat > passwd alice:secret bob:19820522 exarkun@boson:/tmp/irc-server$ twistd -n words --irc-port 6667 --auth file:passwd 2010-06-29 11:51:26-0400 [-] Log opened. 2010-06-29 11:51:26-0400 [-] twistd 10.0.0+r29436 (/usr/bin/python 2.6.4) starting up. 2010-0...
Python, add items from txt file into a list
3,142,054
7
2010-06-29T15:11:53Z
3,142,063
25
2010-06-29T15:13:29Z
[ "python", "file-io" ]
Say I have an empty list `myNames = []` How can I open a file with names on each line and read in each name into the list? like: ``` > names.txt > dave > jeff > ted > myNames = [dave,jeff,ted] ```
Read the [documentation](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files): ``` with open('names.txt', 'r') as f: myNames = f.readlines() ``` The others already provided answers how to get rid of the newline character. **Update**: [Fred Larson](http://stackoverflow.com/users/10077/fred...
"/1/2/3/".split("/")
3,142,428
4
2010-06-29T15:55:49Z
3,142,445
18
2010-06-29T15:57:36Z
[ "python", "string" ]
It's too hot & I'm probably being retarded. ``` >>> "/1/2/3/".split("/") ['', '1', '2', '3',''] ``` Whats with the empty elements at the start and end? Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from <http://docs.python.org/library/stdtypes.html> ...
Compare with: ``` "1/2/3".split("/") ``` Empty elements are still elements. You could use `strip('/')` to trim the delimiter from the beginning/end of your string.
Architecting from scratch in Python: what to use?
3,143,115
18
2010-06-29T17:18:45Z
3,144,382
29
2010-06-29T20:14:25Z
[ "python", "orm", "rest", "frameworks" ]
I'm lucky enough to have full control over the architecture of my company's app, and I've decided to scrap our prototype written in Ruby/Rails and start afresh in Python. This is for a few reasons: I want to learn Python, I prefer the syntax and I've basically said "F\*\*k it, let's do it." So, baring in mind this is ...
**Frameworks** OK, so I'm a little biased here as I currently make extensive use of Django and organise the Django User Group in London so bear that in mind when reading the following. Start with Django because it's a great gateway drug. Lots of documentation and literature, a very active community of people to talk ...
Architecting from scratch in Python: what to use?
3,143,115
18
2010-06-29T17:18:45Z
3,340,005
14
2010-07-27T00:49:21Z
[ "python", "orm", "rest", "frameworks" ]
I'm lucky enough to have full control over the architecture of my company's app, and I've decided to scrap our prototype written in Ruby/Rails and start afresh in Python. This is for a few reasons: I want to learn Python, I prefer the syntax and I've basically said "F\*\*k it, let's do it." So, baring in mind this is ...
Ok, you might be making a mistake, the same one I made when I started with python. Before you decide on a thing like django, which is an excellent, yet *atypical* python web framework, spend an night cuddled up with: [This](http://bitworking.org/news/Why_so_many_Python_web_frameworks), is a good start. Make sure you ...
Expand Python Search Path to Other Source
3,144,089
38
2010-06-29T19:37:43Z
3,144,107
64
2010-06-29T19:39:34Z
[ "python", "search", "import", "path" ]
I have just joined a project with a rather large existing code base. We develop in linux and do not use and IDE. We run through the command line. I'm trying to figure out how to get python to search for the right path when I run project modules. For instance, when I run something like: ``` python someprojectfile.py ``...
There are a few possible ways to do this: * Set the environment variable `PYTHONPATH` to a colon-separated list of directories to search for imported modules. * In your program, use `sys.path.append('/path/to/search')` to add the names of directories you want Python to search for imported modules. [`sys.path`](http://...
Expand Python Search Path to Other Source
3,144,089
38
2010-06-29T19:37:43Z
3,177,320
7
2010-07-05T05:08:21Z
[ "python", "search", "import", "path" ]
I have just joined a project with a rather large existing code base. We develop in linux and do not use and IDE. We run through the command line. I'm trying to figure out how to get python to search for the right path when I run project modules. For instance, when I run something like: ``` python someprojectfile.py ``...
You should also read about python packages, <http://docs.python.org/tutorial/modules.html> . From your example, I would guess that you really have a package at ~/codez/project. The file `__init__.py` in a python directory maps a directory into a namespace. If your subdirectories all have an `__init__.py` file then you ...
Ruby version of to String method
3,144,265
5
2010-06-29T19:59:59Z
3,144,308
9
2010-06-29T20:05:29Z
[ "python", "ruby" ]
This question is about formatting ruby's strings. In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example: ``` >>>$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GC...
``` [1,23,4].inspect #=> "[1, 23, 4]" p [1,23,4] # Same as puts [1,23,4].inspect ```
Ruby version of to String method
3,144,265
5
2010-06-29T19:59:59Z
3,144,508
9
2010-06-29T20:33:15Z
[ "python", "ruby" ]
This question is about formatting ruby's strings. In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example: ``` >>>$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GC...
In Ruby, there are four methods that are typically available for getting a string representation of an object. 1. `#to_str`: this is part of Ruby's standard type conversion protocols (similar to `to_int`, `to_ary`, `to_float`, …). It is used if and *only* if the object really actually *is* a string but for whatever re...
Python question about time spent
3,144,898
2
2010-06-29T21:29:09Z
3,144,906
10
2010-06-29T21:29:59Z
[ "python", "timedelta" ]
I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it? Thank you
The best way would be to run some [benchmark tests](http://tarekziade.wordpress.com/2007/10/18/unobtrusive-benchmark-and-debug-of-python-applications/) (to test individual functions) or [**Profiling**](http://docs.python.org/library/profile.html) (to test an entire application/program). Python comes with built-in Profi...
Multiple text nodes in Python's ElementTree? HTML generation
3,145,015
7
2010-06-29T21:47:39Z
3,193,707
9
2010-07-07T10:00:10Z
[ "python", "elementtree", "html-generation" ]
I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the `text` and `tail` properties of `Element`. This is a problem if I want to generate something that would require multiple text nodes, for example: ``` <a>text1 <b>text2</b> text3 <b>text4...
To generate the above string with `ElementTree` you can use the following code. The trick to this is that the `text` is the very first lot of text before the next element and the `tail` is all the text after the element up to the next element. ``` import xml.etree.ElementTree as ET root = ET.Element("a") root.text = '...
get contents of <a> tags using python
3,145,178
3
2010-06-29T22:14:31Z
3,145,257
8
2010-06-29T22:31:10Z
[ "python", "html-parsing", "sgml" ]
Assuming I have html read into my program like this: ``` <p><a href="http://vancouver.en.craigslist.ca/nvn/ret/1817849271.html">F/T &amp; P/T Sales Associate - Caliente Fashions</a> - <font size="-1"> (North Vancouver)</font></p> <p><a href="http://vancouver.en.craigslist.ca/van/ret/1817804151.html">IMMEDIATE EMPLOYME...
Simplest is probably [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) (be sure to use 3.0.8 or higher `3.0.*` release, **not** `3.1.*`, unless you're on Python 3 -- see [here](http://www.crummy.com/software/BeautifulSoup/3.1-problems.html)!). ``` import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(th...
Python code simplification? One line, add all in list
3,145,379
5
2010-06-29T22:58:10Z
3,145,390
15
2010-06-29T23:01:05Z
[ "python" ]
I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion. Question: What is the sum of the digits of the number 21000? My answer:...
``` sum(int(n) for n in str(2**1000)) ```
Which openid / oauth library to connect a django project to Google Apps Accounts?
3,145,453
30
2010-06-29T23:14:36Z
3,323,033
17
2010-07-23T23:14:25Z
[ "python", "django", "openid", "google-openid" ]
I'm working on an intranet django project (not using GAE) for a company that uses Google Apps for login. So I'd like my users to be able to log in to my django project using their google accounts login. OpenID seems appropriate, although maybe Oauth might work too? I see a lot of similarly named libraries out there to...
I finally got this working, so I'll answer my own question since the previous answers here were helpful but don't tell the whole story. [django-openid-auth](https://launchpad.net/django-openid-auth) is actually quite easy to set up and use. The README file is very clear. If you just want to use standard google account...
How to accumulate state across tests in py.test
3,145,720
3
2010-06-30T00:25:30Z
3,145,756
7
2010-06-30T00:35:24Z
[ "python", "testing", "py.test" ]
I currently have a project and tests similar to these. ``` class mylib: @classmethod def get_a(cls): return 'a' @classmethod def convert_a_to_b(cls, a): return 'b' @classmethod def works_with(cls, a, b): return True class TestMyStuff(object): def test_first(self):...
Good unit test practice is to avoid state accumulated across tests. Most unit test frameworks go to great lengths to prevent you from accumulating state. The reason is that you want each test to stand on its own. This lets you run arbitrary subsets of your tests, and ensures that your system is in a clean state for eac...
Running pyflakes remotely with flymake and tramp in emacs?
3,145,746
16
2010-06-30T00:33:20Z
7,217,709
8
2011-08-27T22:10:49Z
[ "python", "emacs", "tramp", "flymake", "pyflakes" ]
I'm trying to use flymake to run pyflakes, as suggested [here](http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc9) This works fine for local files, and almost works with remote files with a bit of tweaking, but I'm left with a problem where flymake/pyflakes 'modifies' the buffer when it runs (although nothing actua...
You need to tell flymake to [create](http://www.emacswiki.org/emacs/FlyMake#toc14) it's copy of the buffer [somewhere](http://hustoknow.blogspot.com/2010/09/emacs-and-pyflakes-using-tmp-directory.html) locally, I prefer using the `$TMP` directory since this *also* allows me to use tramp on files in directories I don't ...
read and write on same csv file
3,146,571
12
2010-06-30T04:56:06Z
3,146,590
9
2010-06-30T05:01:47Z
[ "python", "csv" ]
I am trying to read and write on the same CSV file: ``` file1 = open(file.csv, 'rb') file2 = open(file.csv, 'wb') reader = csv.reader(file1) writer = csv.writer(file2) for row in reader: if row[2] == 'Test': writer.writerow( row[0], row[1], 'Somevalue') ``` My csv files are: * `val1,2323,Notest` * `val2, 23...
You should use different output file name. Even if you want the name to be the same, you should use some temporary name and finally rename file. When you open file in 'w' (or 'wb') mode this file is "cleared" -- whole file content disappears. Python documentation for `open()` says: *... 'w' for only writing (an exist...
How to convert comma-separated key value pairs into a dictionary using lambda functions
3,147,554
2
2010-06-30T08:24:32Z
3,147,584
13
2010-06-30T08:30:54Z
[ "python", "lambda" ]
I'm having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions? ``` fname:John,lname:doe,mname:dunno,city:Florida ``` Thanks
There is not really a need for a lambda here. ``` s = "fname:John,lname:doe,mname:dunno,city:Florida" sd = dict(u.split(":") for u in s.split(",")) ```
Inserting records into Sqlite using Python parameter substitution where some fields are blank
3,148,315
2
2010-06-30T10:26:45Z
3,148,436
7
2010-06-30T10:43:48Z
[ "python", "sqlite" ]
I am running this sort of query: ``` insert into mytable (id, col1, col2) values (:ID, :COL1, :COL2) ``` In Python, a dictionary of this form can be used in conjuction with the query above for parameter substitution: ``` d = { 'ID' : 0, 'COL1' : 'hi', 'COL2' : 'there' } cursor.execute(sql_insert, d) ``` But in the ...
I haven't checked that this works, but I think it should: ``` from collections import defaultdict d = { 'ID' : 0, 'COL1' : 'hi' } cursor.execute(sql_insert, defaultdict(str, d)) ``` `defaultdict` is a specialised dictionary where any missing keys generate a new value instead of throwing a `KeyError`. Of course this ...
Python splitting list based on missing numbers in a sequence
3,149,440
16
2010-06-30T12:59:24Z
3,149,493
31
2010-06-30T13:06:46Z
[ "python", "list", "sequence" ]
I am looking for the most pythonic way of splitting a list of numbers into smaller lists based on a number missing in the sequence. For example, if the initial list was: ``` seq1 = [1, 2, 3, 4, 6, 7, 8, 9, 10] ``` the function would yield: ``` [[1, 2, 3, 4], [6, 7, 8, 9, 10]] ``` or ``` seq2 = [1, 2, 4, 5, 6, 8, 9...
From the [python documentation](http://docs.python.org/library/itertools.html#itertools-example): ``` >>> # Find runs of consecutive numbers using groupby. The key to the solution >>> # is differencing with a range so that consecutive numbers all appear in >>> # same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22...
How do I get the index of the largest list inside a list of lists using Python?
3,149,502
7
2010-06-30T13:07:38Z
3,149,523
8
2010-06-30T13:09:45Z
[ "python", "list", "blender", "cinema-4d" ]
I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists: ``` props = [lx,ly,lz,sx,sy,sz,rx,ry,rz] ``` I printed out the keyframes for each property/track in an arbitrary animation and they are of different lengths: ``` track Position . X has 24 keys track Position . Y has 24 key...
You can use a generator expression: ``` maxLen = max(len(p) for p in props) ```
How do I get the index of the largest list inside a list of lists using Python?
3,149,502
7
2010-06-30T13:07:38Z
3,149,735
18
2010-06-30T13:34:11Z
[ "python", "list", "blender", "cinema-4d" ]
I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists: ``` props = [lx,ly,lz,sx,sy,sz,rx,ry,rz] ``` I printed out the keyframes for each property/track in an arbitrary animation and they are of different lengths: ``` track Position . X has 24 keys track Position . Y has 24 key...
``` max(enumerate(props), key = lambda tup: len(tup[1])) ``` This gives you a tuple containing `(index, list)` of the longest list in props.
Passing a JSON object through POST using Python
3,150,584
15
2010-06-30T15:09:42Z
3,151,011
25
2010-06-30T15:51:52Z
[ "python", "json", "google-app-engine", "post" ]
I'm trying to post a JSON object through a POST. I'm trying to do it as follows: ``` import json, urllib, urllib2 filename = 'test.json' race_id = 2530 f = open(filename, 'r') fdata = json.loads(f.read()) f.close() prefix = 'localhost:8000' count = 0 for points in fdata['positions'].iteritems(): print '--' + st...
It looks like `self.request.get()` is returning a unicode object rather than a file-like object. You could try using `json.loads()` instead of `json.load()`.
Replace the single quote (') character from a string
3,151,146
18
2010-06-30T16:07:28Z
3,151,171
48
2010-06-30T16:10:03Z
[ "python", "string" ]
I need to strip the character `"'"` from a string in python. How do I do this? I know there is a simple answer. Really what I am looking for is how to write `'` in my code. for example `\n` = newline.
As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes (`"'"`) or you can escape it inside single quotes (`'\''`). To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string: ``` >>> "didn't".replace...
How to decode a Google App Engine entity Key path str in Python?
3,151,379
6
2010-06-30T16:34:46Z
3,152,228
7
2010-06-30T18:27:09Z
[ "python", "google-app-engine" ]
In Google App Engine, an entity has a Key. A key can be made from a path, in which case str(key) is an opaque hex string. Example: ``` from google.appengine.ext import db foo = db.Key.from_path(u'foo', u'bar', _app=u'baz') print foo ``` gives ``` agNiYXpyDAsSA2ZvbyIDYmFyDA ``` if you set up the right paths to run t...
``` from google.appengine.ext import db k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA') _app = k.app() path = [] while k is not None: path.append(k.id_or_name()) path.append(k.kind()) k = k.parent() path.reverse() print 'app=%r, path=%r' % (_app, path) ``` when run in a Development Console, this outputs: ``` app=u'ba...
How to pass a specific argument to a decorator in python
3,152,007
3
2010-06-30T17:57:18Z
3,152,044
11
2010-06-30T18:03:46Z
[ "python", "function", "decorator" ]
I want to write a python function decorator that tests that certain arguments to a function pass some criterion. For eg, Suppose I want to test that some arguments are always even, then I want to be able to do something like this (not valid python code) ``` def ensure_even( n ) : def decorator( function ) : @fu...
You can do this: ``` def ensure_even(argnum): def fdec(func): def f(*args, **kwargs): assert(args[argnum] % 2 == 0) #or assert(not args[argnum] % 2) return func(*args, **kwargs) return f return fdec ``` So then: ``` @ensure_even(1) #2nd argument must be even def test(arg1, arg2): print(ar...
Python Class scope & lists
3,153,017
10
2010-06-30T20:11:48Z
3,153,184
8
2010-06-30T20:35:11Z
[ "python" ]
I'm still fairly new to Python, and my OO experience comes from Java. So I have some code I've written in Python that's acting very unusual to me, given the following code: ``` class MyClass(): mylist = [] mynum = 0 def __init__(self): # populate list with some value. ...
tlayton's answer is part of the story, but it doesn't explain everything. Add a ``` print MyClass.mynum ``` to become even more confused :). It will print '0'. Why? Because the line ``` self.mynum += 1 ``` *creates* an instance variable and subsequently increases it. It doesn't increase the *class* variable. The ...