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
Why does "python setup.py sdist" create unwanted "PROJECT-egg.info" in project root directory?
3,779,915
24
2010-09-23T15:26:01Z
3,780,822
26
2010-09-23T17:08:46Z
[ "python", "setuptools", "distutils", "distribute", "setup.py" ]
When I run ``` python setup.py sdist ``` it creates an sdist in my ./dist directory. This includes a "PROJECT-egg.info" file in the zip inside my "dist" folder, which I don't use, but it doesn't hurt me, so I just ignore it. My question is why does it *also* create a "PROJECT-egg.info" folder in my project root di...
This directory is created intentionally as part of the build process for a source distribution. A little gander at the [developer guide for setuptools](http://peak.telecommunity.com/DevCenter/setuptools#generating-source-distributions) gives you a hint as to why: > But, be sure to ignore any part of the > distutils do...
Integrating a script language into a C++ application
3,780,398
5
2010-09-23T16:17:24Z
3,780,476
7
2010-09-23T16:25:44Z
[ "c++", "python", "scripting", "embedding" ]
I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations. I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python. I'm not looking for something like Boost.Python / swig, something that is able to wrap my ...
The Python documentation has a page on [embedding Python](http://docs.python.org/extending/embedding.html) in a C or C++ application.
Integrating a script language into a C++ application
3,780,398
5
2010-09-23T16:17:24Z
3,780,571
7
2010-09-23T16:37:24Z
[ "c++", "python", "scripting", "embedding" ]
I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations. I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python. I'm not looking for something like Boost.Python / swig, something that is able to wrap my ...
Why not use Boost.Python? You can expose your data classes to Python and execute a script/function as described [here](http://www.boost.org/doc/libs/1_44_0/libs/python/doc/tutorial/doc/html/python/embedding.html).
Python: Sum string lengths
3,780,403
8
2010-09-23T16:17:57Z
3,780,412
27
2010-09-23T16:19:03Z
[ "python", "list", "sum" ]
Is there a more idiomatic way to sum string lengths in Python than by using a loop? ``` length = 0 for string in strings: length += len(string) ``` I tried `sum()`, but it only works for integers: ``` >>> sum('abc', 'de') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sum() c...
``` length = sum(len(s) for s in strings) ```
Python: Sum string lengths
3,780,403
8
2010-09-23T16:17:57Z
3,780,444
13
2010-09-23T16:22:08Z
[ "python", "list", "sum" ]
Is there a more idiomatic way to sum string lengths in Python than by using a loop? ``` length = 0 for string in strings: length += len(string) ``` I tried `sum()`, but it only works for integers: ``` >>> sum('abc', 'de') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sum() c...
My first way to do it would be `sum(map(len, strings))`. Another way is to use a list comprehension or generator expression as the other answers have posted.
Passing dictionaries to a Python script through the command line
3,780,468
4
2010-09-23T16:24:58Z
3,780,569
7
2010-09-23T16:37:22Z
[ "python", "command-line" ]
How can I pass a dictionary to a python script from another python script over the command line? I use subprocess to call the second script. The options I've come to are: I) Build a module to parse a dictionary from a string (more in-depth than I had hoped to go). II) Use a temporary file to write a pickle, and pa...
Have you looked at the [pickle](http://docs.python.org/library/pickle.html#module-pickle) module to pass the data over stdout/stdin? Example: knights.py: ``` import pickle import sys desires = {'say': 'ni', 'obtain': 'shrubbery'} pickle.dump(desires, sys.stdout) ``` roundtable.py: ``` import pickle import sys kn...
Add a custom button to a Django application's admin page
3,780,737
11
2010-09-23T16:58:07Z
3,788,051
10
2010-09-24T14:29:59Z
[ "python", "django", "django-admin" ]
I have an application in Django with a routine which would be available only to the admin. I'm quite new to the python/django world, so maybe my question is trivial. What I want to do is add a button to perform the routine in this application's section of the admin app. I'm quite confused from there, am I suppose to m...
Messing with the admin forms can be complicated but i've commonly found that adding links, buttons, or extra info is easy and helpful. (Like a list of links to related objects witout making an inline, esp for things that are more viewed than edited). From [Django docs](http://docs.djangoproject.com/en/dev/ref/contrib/...
shell script remote execution using python
3,781,087
5
2010-09-23T17:41:13Z
3,781,128
11
2010-09-23T17:46:11Z
[ "python", "unix", "shell" ]
Is there a way that I can use Python on Windows to execute shell scripts which are located on a remote Unix machine? P.S: Sorry about the late edit. I do know of Paramiko, but I wanted to know if there is way of doing it without it. For starters, could it be done with subprocess()?
You will need to ssh into the remote machine and if you have appropriate credentials, you can invoke the shell scripts. For using ssh, you can easily use paramiko module that provides ssh automation * <http://www.lag.net/paramiko/> A typical example: ``` import paramiko import sys import os import os.path passwd = ...
why python doesn't need type declaration for python, other way what are the adv. of not declaring type?
3,781,454
2
2010-09-23T18:35:46Z
3,781,496
7
2010-09-23T18:41:49Z
[ "python", "programming-languages" ]
If we know the type of variable or parameter very well, why not to declare them? I'd like to know why it's bad or not necessary. Sorry, I'm new on Python (from about 1 year) and before I was on C, VB, VB.NET and C# programming languages. With Python, I hope to have bad parameter types to be catched at compilation t...
I'm sure you know the `+` function. So, what is it's type? Numbers? Well, it works for lists and strings too. It even works for every object that defines `__add__`. Or in some cases when one object defines `__radd__`. So it's hard to tell the type of this function already. But Python makes it even possible to define t...
Why do Python modules sometimes not import their sub-modules?
3,781,522
40
2010-09-23T18:45:11Z
3,781,554
53
2010-09-23T18:49:54Z
[ "python", "python-import" ]
I noticed something weird today I would like explained. I wasn't 100% sure how to even phrase this as a question, so google is out of the question. The logging module does not have access to the module logging.handlers for some odd reason. Try it yourself if you don't believe me: ``` >>> import logging >>> logging.han...
In Python, modules need to be imported before they're accessible. `import logging` imports just the logging module. It so happens that `logging` is a package with submodules, but those submodules are still not automatically loaded. So, you need to explicitly import `logging.handlers` before you can access it. If you'r...
How to highlight text in a tkinter Text widget
3,781,670
11
2010-09-23T19:03:08Z
3,781,773
26
2010-09-23T19:17:51Z
[ "python", "text", "tkinter" ]
I want to know how to change the style of certain words and expressions based on certain patterns. I am using the `Tkinter.Text` widget and I am not sure how to do such a thing (the same idea of syntax highlighting in text editors). I am not sure even if this is the right widget to use for this purpose.
It's the right widget to use for these purposes. The basic concept is, you assign properties to tags, and you apply tags to ranges of text in the widget. You can use the text widget's `search` command to find strings that match your pattern, which will return you enough information apply a tag to the range that matched...
Selecting a Python Web Framework
3,781,802
6
2010-09-23T19:23:19Z
3,782,005
7
2010-09-23T19:49:13Z
[ "python", "mysql", "django", "pylons", "cherrypy" ]
This may seem like a subjective question. But it is not (that's not the idea, at least). I'm developing an Advertising software (like AdWords, AdBrite, etc) and i've decide to use Python. And would like to use one of those well known web frameworks (Django, Cherrypy, pylons, etc). The question is: Given that it will...
check out Flask. Its easy, its fast, works on top of Werkzeug, uses Jinja2 templating and SQLAlchemy for the model domain. <http://flask.pocoo.org/>
Properties in Python
3,781,834
6
2010-09-23T19:29:46Z
3,781,915
9
2010-09-23T19:37:48Z
[ "python" ]
whats the reason to use the variable the self.\_age? A similar name that doesn't link to the already used self.age? ``` class newprops(object): def getage(self): return 40 def setage(self, value): self._age = value age = property(getage, setage, None, None) ```
`self.age` is already occupied by the property, you need to give another name to the actual variable, which is `_age` here. BTW, since Python 2.6, you could write this with decorators: ``` def newprops(object): @property def age(self): return 40 @age.setter def age(self, value): self...
Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes
3,782,040
12
2010-09-23T19:53:14Z
3,782,084
12
2010-09-23T19:58:41Z
[ "python", "inheritance", "ironpython", "decorator" ]
Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class (the decorator will access class members hence it will require the self parameter). ``` class SubSystem(object): def UpdateGUI(self, fun): #fu...
You need to make `UpdateGUI` a `@classmethod`, and make your `wrapper` aware of `self`. A working example: ``` class X(object): @classmethod def foo(cls, fun): def wrapper(self, *args, **kwargs): self.write(*args, **kwargs) return fun(self, *args, **kwargs) return wrappe...
Py2Exe: DLL load failed
3,782,117
16
2010-09-23T20:02:44Z
4,047,121
31
2010-10-28T20:57:46Z
[ "python", "py2exe" ]
When trying to use py2exe to convert a simple Python game I made into exe format, it gave me the following error: ``` Traceback (most recent call last): File "C:\Users\Tali\Desktop\2exe.py", line 4, in <module> setup(console=['test.py']) File "C:\Python\lib\distutils\core.py", line 152, in setup dist.run_c...
I had exact the same problem. Since I have windows 7 64bit, I downloaded py2exe-0.6.9.win64-py2.6.amd64.exe, which I suppose to be the 64bit version of py2exe. but it did not work, and I had the same error. I changed to py2exe-0.6.9.win32-py2.6.exe, and it worked fine. I guess you have to match the 32bit or 64bit wi...
Why aren't Python's superclass __init__ methods automatically invoked?
3,782,827
88
2010-09-23T21:56:12Z
3,782,838
9
2010-09-23T21:59:08Z
[ "python", "inheritance", "subclass", "delegation", "superclass" ]
Why did the Python designers decide that subclasses' `__init__()` methods don't automatically call the `__init__()` methods of their superclasses, as in some other languages? Is the Pythonic and recommended idiom really like the following? ``` class Superclass(object): def __init__(self): print 'Do somethi...
"Explicit is better than implicit." It's the same reasoning that indicates we should explicitly write 'self'. I think in in the end it is a benefit-- can you recite all of the rules Java has regarding calling superclasses' constructors?
Why aren't Python's superclass __init__ methods automatically invoked?
3,782,827
88
2010-09-23T21:56:12Z
3,782,877
112
2010-09-23T22:07:53Z
[ "python", "inheritance", "subclass", "delegation", "superclass" ]
Why did the Python designers decide that subclasses' `__init__()` methods don't automatically call the `__init__()` methods of their superclasses, as in some other languages? Is the Pythonic and recommended idiom really like the following? ``` class Superclass(object): def __init__(self): print 'Do somethi...
The crucial distinction between Python's `__init__` and those other languages **constructors** is that `__init__` is **not** a constructor: it's an **initializer** (the actual **constructor** (if any, but, see later;-) is `__new__` and works completely differently again). While **constructing** all superclasses (and, n...
Why aren't Python's superclass __init__ methods automatically invoked?
3,782,827
88
2010-09-23T21:56:12Z
3,782,881
25
2010-09-23T22:08:51Z
[ "python", "inheritance", "subclass", "delegation", "superclass" ]
Why did the Python designers decide that subclasses' `__init__()` methods don't automatically call the `__init__()` methods of their superclasses, as in some other languages? Is the Pythonic and recommended idiom really like the following? ``` class Superclass(object): def __init__(self): print 'Do somethi...
I'm somewhat embarrassed when people parrot the "Zen of Python", as if it's a justification for anything. It's a design philosophy; particular design decisions can *always* be explained in more specific terms--and they must be, or else the "Zen of Python" becomes an excuse for doing anything. The reason is simple: you...
Why aren't Python's superclass __init__ methods automatically invoked?
3,782,827
88
2010-09-23T21:56:12Z
7,871,558
11
2011-10-24T05:20:01Z
[ "python", "inheritance", "subclass", "delegation", "superclass" ]
Why did the Python designers decide that subclasses' `__init__()` methods don't automatically call the `__init__()` methods of their superclasses, as in some other languages? Is the Pythonic and recommended idiom really like the following? ``` class Superclass(object): def __init__(self): print 'Do somethi...
Java and C++ **require** that a base class constructor is called because of memory layout. If you have a class `BaseClass` with a member `field1`, and you create a new class `SubClass` that adds a member `field2`, then an instance of `SubClass` contains space for `field1` and `field2`. You need a constructor of `BaseC...
Why does python gstreamer crash without "gobject.threads_init()" at the top of my script?
3,782,962
10
2010-09-23T22:27:29Z
3,783,135
12
2010-09-23T23:03:23Z
[ "python", "thread-safety", "gstreamer", "gobject" ]
I have written a python script to use gstreamer (pygst and gst modules) to calculate replaygain tags, and it was crashing inconsistently with various gobject errors. I found somewhere that you could fix this by putting the following boilerplate at the top of your script: ``` import gobject gobject.threads_init() ``` ...
Because, you can use gobject in a non threading environment. This is not unusual. When you use gobject in a threading environment, you need to explicitly initialize by calling gobject.threads\_init(). This will also ensure that the when "C" functions are called, the GIL is freed. * <http://stackoverflow.com/questions/...
Get the list of figures in matplotlib
3,783,217
25
2010-09-23T23:30:00Z
3,783,303
11
2010-09-23T23:54:38Z
[ "python", "matplotlib" ]
I would like to: ``` pylab.figure() pylab.plot(x) pylab.figure() pylab.plot(y) # ... for i, figure in enumerate(pylab.MagicFunctionReturnsListOfAllFigures()): figure.savefig('figure%d.png' % i) ``` What is the magic function that returns a list of current figures in pylab? Websearch didn't help...
## Edit: As [Matti Pastell's solution shows](http://stackoverflow.com/a/15900439/190597), there is a much better way: use `plt.get_fignums()`. --- ``` import numpy as np import pylab import matplotlib._pylab_helpers x=np.random.random((10,10)) y=np.random.random((10,10)) pylab.figure() pylab.plot(x) pylab.figure() p...
Get the list of figures in matplotlib
3,783,217
25
2010-09-23T23:30:00Z
15,900,439
58
2013-04-09T11:18:38Z
[ "python", "matplotlib" ]
I would like to: ``` pylab.figure() pylab.plot(x) pylab.figure() pylab.plot(y) # ... for i, figure in enumerate(pylab.MagicFunctionReturnsListOfAllFigures()): figure.savefig('figure%d.png' % i) ``` What is the magic function that returns a list of current figures in pylab? Websearch didn't help...
Pyplot has [get\_fignums](http://matplotlib.org/api/pyplot_api.html?highlight=gcf#matplotlib.pyplot.get_fignums) method that returns a list of figure numbers. This should do what you want: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(100) y = -x plt.figure() plt.plot(x) plt.figure() plt.plot(...
Python Database connection Close
3,783,238
13
2010-09-23T23:35:49Z
3,783,252
15
2010-09-23T23:39:56Z
[ "python", "database-connection" ]
Using the code below leaves me with an open connection, how do I close? ``` import pyodbc conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') csr = conn.cursor() csr.close() del csr ```
Connections have a [`close`](https://www.python.org/dev/peps/pep-0249/#connection-close) method as specified in PEP-249 (Python Database API Specification v2.0): ``` import pyodbc conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') csr = conn.cursor() csr.close()...
Python Database connection Close
3,783,238
13
2010-09-23T23:35:49Z
3,783,305
26
2010-09-23T23:55:18Z
[ "python", "database-connection" ]
Using the code below leaves me with an open connection, how do I close? ``` import pyodbc conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') csr = conn.cursor() csr.close() del csr ```
You can wrap the whole connection in a context manager, like the following: ``` from contextlib import contextmanager import pyodbc import sys @contextmanager def open_db_connection(connection_string, commit=False): connection = pyodbc.connect(connection_string) cursor = connection.cursor() try: y...
python tuple to dict
3,783,530
70
2010-09-24T01:04:04Z
3,783,546
135
2010-09-24T01:07:56Z
[ "python", "dictionary", "tuples" ]
For the tuple, `t = ((1, 'a'),(2, 'b'))` `dict(t)` returns `{1: 'a', 2: 'b'}` Is there a good way to get `{'a': 1, 'b': 2}` (keys and vals swapped)? I'm wanting to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the best way.
Try: ``` >>> t = ((1, 'a'),(2, 'b')) >>> dict((y, x) for x, y in t) {'a': 1, 'b': 2} ```
python tuple to dict
3,783,530
70
2010-09-24T01:04:04Z
7,667,508
36
2011-10-05T20:46:19Z
[ "python", "dictionary", "tuples" ]
For the tuple, `t = ((1, 'a'),(2, 'b'))` `dict(t)` returns `{1: 'a', 2: 'b'}` Is there a good way to get `{'a': 1, 'b': 2}` (keys and vals swapped)? I'm wanting to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the best way.
A slightly simpler method: ``` >>> t = ((1, 'a'),(2, 'b')) >>> dict(map(reversed, t)) {'a': 1, 'b': 2} ```
python tuple to dict
3,783,530
70
2010-09-24T01:04:04Z
15,179,569
27
2013-03-02T21:20:09Z
[ "python", "dictionary", "tuples" ]
For the tuple, `t = ((1, 'a'),(2, 'b'))` `dict(t)` returns `{1: 'a', 2: 'b'}` Is there a good way to get `{'a': 1, 'b': 2}` (keys and vals swapped)? I'm wanting to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the best way.
Even more concise if you are on python 2.7: ``` >>> t = ((1,'a'),(2,'b')) >>> {y:x for x,y in t} {'a':1, 'b':2} ```
How to read integers from a file that are 24bit and little endian using Python?
3,783,677
11
2010-09-24T01:45:24Z
3,783,679
9
2010-09-24T01:46:47Z
[ "python", "file-io", "endianness" ]
Is there an easy way to read these integers in? I'd prefer a built in method, but I assume it is possible to do with some bit operations. Cheers **edit** I thought of another way to do it that is different to the ways below and in my opinion is clearer. It pads with zeros at the other end, then shifts the result. ...
Python's `struct` module lets you interpret bytes as different kinds of data structure, with control over endianness. If you read a single three-byte number from the file, you can convert it thus: ``` struct.unpack('<I', bytes + '\0') ``` The module doesn't appear to support 24-bit words, hence the `'\0'`-padding. ...
pythonic implementation of Bayesian networks for a specific application
3,783,708
32
2010-09-24T01:53:24Z
5,435,278
20
2011-03-25T16:30:22Z
[ "python", "bayesian", "bayesian-networks" ]
**This is why I'm asking this question:** Last year I made some C++ code to compute posterior probabilities for a particular type of model (described by a Bayesian network). The model worked pretty well and some other people started to use my software. Now I want to improve my model. Since I'm already coding slightly d...
I've been working on this kind of thing in my spare time for quite a while. I think I'm on my third or fourth version of this same problem right now. I'm actually getting ready to release another version of Fathom (https://github.com/davidrichards/fathom/wiki) with dynamic bayesian models included and a different persi...
Is there a Pythonic way to make this logic more elegant?
3,783,728
2
2010-09-24T01:59:58Z
3,783,745
9
2010-09-24T02:04:34Z
[ "python" ]
I'm new to Python, and I've been playing around with it for simple tasks. I have a bunch of CSVs which I need to manipulate in complex ways, but I'm breaking this up into smaller tasks for the sake of learning Python. For now, given a list of strings, I want to remove user-defined title prefixes of any names in the st...
``` [re.sub(r'^(Mr|Ms|Mrs)\.\s+', '', s) for s in test_csv_line] ```
Calling PHP from Python
3,784,138
5
2010-09-24T04:08:48Z
3,784,156
13
2010-09-24T04:13:35Z
[ "php", "python" ]
Is it possible to run a PHP script using python?
You can look into the `subprocess` class, more specifically, [`subprocess.call()`](http://docs.python.org/library/subprocess.html#module-subprocess) ``` subprocess.call(*popenargs, **kwargs) subprocess.call(["php", "path/to/script.php"]); ```
Views in Python3.1?
3,784,169
14
2010-09-24T04:18:04Z
3,784,203
9
2010-09-24T04:32:02Z
[ "python", "view", "python-3.x" ]
What exactly are views in Python3.1? They seem to behave in a similar manner as that of iterators and they can be materialized into lists too. How are iterators and views different?
From what I can tell, a view is still attached to the object it was created from. Modifications to the original object affect the view. from the [docs](http://docs.python.org/release/3.0.1/library/stdtypes.html#dictionary-view-objects) (for dictionary views): ``` >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'sp...
Best way to iterate through all rows in a DB-table
3,785,294
11
2010-09-24T08:14:56Z
3,785,364
29
2010-09-24T08:23:31Z
[ "python", "mysql", "database" ]
I often write little Python scripts to iterate through all rows of a DB-table. For example sending all to all subscribers a email. I do it like this ``` conn = MySQLdb.connect(host = hst, user = usr, passwd = pw, db = db) cursor = conn.cursor() subscribers = cursor.execute("SELECT * FROM tbl_subscriber;") for subscr...
unless you have BLOBs in there, thousands of rows shouldn't be a problem. Do you know that it is? Also, why bring shame on yourself and your entire family by doing something like ``` "SELECT * FROM tbl_subscriber LIMIT %d,%d;" % (actualLimit,steps) ``` when the cursor will make the substitution for you in a manner t...
Best way to iterate through all rows in a DB-table
3,785,294
11
2010-09-24T08:14:56Z
3,789,108
15
2010-09-24T16:33:15Z
[ "python", "mysql", "database" ]
I often write little Python scripts to iterate through all rows of a DB-table. For example sending all to all subscribers a email. I do it like this ``` conn = MySQLdb.connect(host = hst, user = usr, passwd = pw, db = db) cursor = conn.cursor() subscribers = cursor.execute("SELECT * FROM tbl_subscriber;") for subscr...
You don't have to modify the query, you can use the **fetchmany** method of cursors. Here is how I do it : ``` def fetchsome(cursor, some=1000): fetch = cursor.fetchmany while True: rows = fetch(some) if not rows: break for row in rows: yield row ``` This way you can "SELEC...
Good python XML parser to work with namespace heavy documents
3,785,629
7
2010-09-24T09:08:13Z
3,786,391
12
2010-09-24T11:03:53Z
[ "python", "xml", "namespaces", "xml-namespaces" ]
Python elementTree seems unusable with namespaces. What are my alternatives? BeautifulSoup is pretty rubbish with namespaces too. I don't want to strip them out. Examples of how a particular python library gets namespaced elements and their collections are all +1. **Edit:** Could you provide code to deal with this re...
[lxml](http://lxml.de/) is namespace-aware. ``` >>> from lxml import etree >>> et = etree.XML("""<root xmlns="foo" xmlns:stuff="bar"><bar><stuff:baz /></bar></root>""") >>> etree.tostring(et, encoding=str) # encoding=str only needed in Python 3, to avoid getting bytes '<root xmlns="foo" xmlns:stuff="bar"><bar><stuff:b...
Change working directory in shell with a python script
3,786,678
10
2010-09-24T11:40:08Z
3,786,928
13
2010-09-24T12:11:55Z
[ "python", "linux", "bash", "shell" ]
I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell to be in that directory. So I want to implement `cd` command, but with external program. Can it be done in a python script or I have to write bash ...
Others have pointed out that you can't change the working directory of a parent from a child. But there is a way you can achieve your goal -- if you cd from a shell function, it *can* change the working dir. Add this to your ~/.bashrc: ``` function go() { cd $(python /path/to/cd.py "$1") } ``` Your script should...
Dynamic base class and factories
3,786,762
2
2010-09-24T11:53:15Z
3,787,025
9
2010-09-24T12:25:35Z
[ "python", "factory", "factory-pattern" ]
I have following code: ``` class EntityBase (object) : __entity__ = None def __init__ (self) : pass def entity (name) : class Entity (EntityBase) : __entity__ = name def __init__ (self) : pass return Entity class Smth (entity ("SMTH")) : def __init__ (self, ...
I would do this with a decorator. Also, storing the entity -> subclass map in a dictionary lets you replace a linear scan with a dict lookup. ``` class EntityBase(object): _entity_ = None _entities_ = {} @classmethod def factory(cls, entity): try: return cls._entities_[entity] ...
What is a "method" in Python?
3,786,881
37
2010-09-24T12:07:07Z
3,786,900
46
2010-09-24T12:08:56Z
[ "python", "methods" ]
Can anyone, please, explain to me in very simple terms what a "method" is in Python? The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have n...
It's a function which is a member of a class: ``` class C: def my_method(self): print "I am a C" c = C() c.my_method() # Prints "I am a C" ``` Simple as that! (There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing ...
What is a "method" in Python?
3,786,881
37
2010-09-24T12:07:07Z
3,787,670
23
2010-09-24T13:40:56Z
[ "python", "methods" ]
Can anyone, please, explain to me in very simple terms what a "method" is in Python? The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have n...
A method is a function that takes a class instance as its first parameter. Methods are members of classes. ``` class C: def method(self, possibly, other, arguments): pass # do something here ``` As you wanted to know what it specifically means in Python, one can distinguish between bound and unbound metho...
Python GUI for portable app
3,787,065
6
2010-09-24T12:30:46Z
3,787,488
8
2010-09-24T13:21:44Z
[ "python", "user-interface", "portable-applications" ]
I am developing a python app, using python and sqlite and GUI to re-create a Access 2007 report generating app. Since the app is portable, I'm looking for GUI solution for python that user doesn't need to install addition things before using the app. Is there any GUI solution suits my need? Thanks!
The only fully portable GUI for Python is the standard **TkInter**, if you don't want any additional install beside Python. The [Themed Tk](http://docs.python.org/py3k/library/tkinter.ttk.html) version is quite nice looking, compared to the older Tk version (the themed version is available through the `ttk` module). A...
Django Models (1054, "Unknown column in 'field list'")
3,787,237
24
2010-09-24T12:55:43Z
3,819,051
10
2010-09-29T05:48:11Z
[ "python", "django", "django-models" ]
No idea why this error is popping up. Here are the models I created - ``` from django.db import models from django.contrib.auth.models import User class Shows(models.Model): showid= models.CharField(max_length=10, unique=True, db_index=True) name = models.CharField(max_length=256, db_index=True) aka = ...
As @inception said my tables schema has been changed & running `syncdb` did not update already created tables. Apparently any changes to the models when updated through `syncdb` does not change (as in update/modify) the actual tables. So I dropped the relevant DB & ran `syncdb` on empty DB. Now it works fine. :) For ...
Django Models (1054, "Unknown column in 'field list'")
3,787,237
24
2010-09-24T12:55:43Z
4,121,698
22
2010-11-08T06:24:17Z
[ "python", "django", "django-models" ]
No idea why this error is popping up. Here are the models I created - ``` from django.db import models from django.contrib.auth.models import User class Shows(models.Model): showid= models.CharField(max_length=10, unique=True, db_index=True) name = models.CharField(max_length=256, db_index=True) aka = ...
maybe your tables schema has been changed? Also, running `syncdb` does not update already created tables. You might need to drop all the tables & then run `syncdb` again. Also remember to take backup of your data!!
Python: Is there any reason *not* to cache an object's hash?
3,787,405
8
2010-09-24T13:13:38Z
3,787,481
7
2010-09-24T13:21:16Z
[ "python", "caching", "hash" ]
I've written a class whose `.__hash__()` implementation takes a long time to execute. I've been thinking to cache its hash, and store it in a variable like `._hash` so the `.__hash__()` method would simply return `._hash`. (Which will be computed either at the end of the `.__init__()` or the first time `.__hash__()` is...
Sure, it's fine to cache the hash value. In fact, Python does so for strings itself. The trade-off is between the speed of the hash calculation and the space it takes to save the hash value. That trade-off is for example why tuples don't cache their hash value, but strings do (see [request for enhancement #1462796](htt...
Python comparison functions
3,787,633
4
2010-09-24T13:35:45Z
3,787,649
11
2010-09-24T13:37:50Z
[ "python", "functional-programming", "comparison" ]
I have some data that lends itself to representation as a value and a comparison function, `(val, f)`, so another value can be checked against it by seeing if `f(val, another)` is `True`. That's easy. Some of them just need `>`, `<`, or `==` as `f`, however, and I can't find a clean way of using them; I end up writing...
The `operator` module is your friend: ``` import operator ScorePoint(60, operator.le) ``` See <http://docs.python.org/library/operator.html>
Python threading ignores KeyboardInterrupt exception
3,788,208
33
2010-09-24T14:48:23Z
3,788,243
44
2010-09-24T14:51:04Z
[ "python", "multithreading", "events", "exception", "keyboardinterrupt" ]
I'm running this my simple code: ``` import threading, time class reqthread ( threading.Thread ): def __init__ (self): threading.Thread.__init__(self) def run ( self ): for i in range(0,10): time.sleep(1) print '.' try: thread=reqthread() thread.start() except (KeyboardInterrupt, SystemE...
Try ``` try: thread=reqthread() thread.daemon=True thread.start() while True: time.sleep(100) except (KeyboardInterrupt, SystemExit): print '\n! Received keyboard interrupt, quitting threads.\n' ``` Without the call to `time.sleep`, the main process is jumping out of the `try...except` block too early, so t...
How to check if a word is an English word with Python?
3,788,870
62
2010-09-24T16:01:15Z
3,788,947
18
2010-09-24T16:12:00Z
[ "python", "nltk", "wordnet" ]
I want to check in a Python program if a word is in the English dictionary. I believe nltk wordnet interface might be the way to go but I have no clue how to use it for such a simple task. ``` def is_english_word(word): pass # how to I implement is_english_word? is_english_word(token.lower()) ``` In the future,...
Using a set to store the word list because looking them up will be faster: ``` with open("english_words.txt") as word_file: english_words = set(word.strip().lower() for word in word_file) def is_english_word(word): return word.lower() in english_words print is_english_word("ham") # should be true if you hav...
How to check if a word is an English word with Python?
3,788,870
62
2010-09-24T16:01:15Z
3,789,057
101
2010-09-24T16:26:11Z
[ "python", "nltk", "wordnet" ]
I want to check in a Python program if a word is in the English dictionary. I believe nltk wordnet interface might be the way to go but I have no clue how to use it for such a simple task. ``` def is_english_word(word): pass # how to I implement is_english_word? is_english_word(token.lower()) ``` In the future,...
For (much) more power and flexibility, use a dedicated spellchecking library like [`PyEnchant`](http://pythonhosted.org/pyenchant/). There's a [tutorial](http://pythonhosted.org/pyenchant/tutorial.html), or you could just dive straight in: ``` >>> import enchant >>> d = enchant.Dict("en_US") >>> d.check("Hello") True ...
How to check if a word is an English word with Python?
3,788,870
62
2010-09-24T16:01:15Z
5,351,315
16
2011-03-18T11:29:06Z
[ "python", "nltk", "wordnet" ]
I want to check in a Python program if a word is in the English dictionary. I believe nltk wordnet interface might be the way to go but I have no clue how to use it for such a simple task. ``` def is_english_word(word): pass # how to I implement is_english_word? is_english_word(token.lower()) ``` In the future,...
**Using NLTK**: ``` from nltk.corpus import wordnet if not wordnet.synsets(word_to_test): #Not an English Word else: #English Word ``` You should refer to [this article](http://www.velvetcache.org/2010/03/01/looking-up-words-in-a-dictionary-using-python) if you have trouble installing wordnet or want to try othe...
How to check if a word is an English word with Python?
3,788,870
62
2010-09-24T16:01:15Z
21,400,566
15
2014-01-28T08:38:26Z
[ "python", "nltk", "wordnet" ]
I want to check in a Python program if a word is in the English dictionary. I believe nltk wordnet interface might be the way to go but I have no clue how to use it for such a simple task. ``` def is_english_word(word): pass # how to I implement is_english_word? is_english_word(token.lower()) ``` In the future,...
It won't work well with WordNet, because WordNet does not contain all english words. Another possibility based on NLTK without enchant is NLTK's words corpus ``` >>> from nltk.corpus import words >>> "would" in words.words() True >>> "could" in words.words() True >>> "should" in words.words() True >>> "I" in words.wor...
How to parse BaseHTTPRequestHandler.path
3,788,897
12
2010-09-24T16:05:08Z
3,788,973
13
2010-09-24T16:15:39Z
[ "python" ]
I'm using Python's `BaseHTTPRequestHandler`. When I implement the do\_GET method I find myself parsing by hand `self.path` `self.path` looks something like: ``` /?parameter=value&other=some ``` How should I parse it in order to get a dict like ``` {'parameter': 'value', 'other':'some'} ``` Thanks,
Use [`parse_qs`](http://docs.python.org/library/urlparse.html#urlparse.parse_qs) from the `urlparse` module, but make sure you remove the "/?": ``` from urlparse import parse_qs s = "/?parameter=value&other=some" print parse_qs(s[2:]) # prints {'other': ['some'], 'parameter': ['value']} ``` Note that each parameter c...
How to parse BaseHTTPRequestHandler.path
3,788,897
12
2010-09-24T16:05:08Z
7,743,415
17
2011-10-12T16:34:58Z
[ "python" ]
I'm using Python's `BaseHTTPRequestHandler`. When I implement the do\_GET method I find myself parsing by hand `self.path` `self.path` looks something like: ``` /?parameter=value&other=some ``` How should I parse it in order to get a dict like ``` {'parameter': 'value', 'other':'some'} ``` Thanks,
Considering self.path could potentially be hierarchical, you should probably do something like the following : ``` import urlparse o = urlparse.urlparse(self.path) urlparse.parse_qs(o.query) ```
Python: Can we convert a ctypes structure to a dictionary?
3,789,372
9
2010-09-24T17:07:23Z
3,789,491
9
2010-09-24T17:23:42Z
[ "python", "ctypes" ]
I have a ctypes structure. ``` class S1 (ctypes.Structure): _fields_ = [ ('A', ctypes.c_uint16 * 10), ('B', ctypes.c_uint32), ('C', ctypes.c_uint32) ] ``` if I have X=S1(), I would like to return a dictionary out of this object: Example, if I do something like: Y = X.getdict() or Y = getdi...
Probably something like this: ``` def getdict(struct): return dict((field, getattr(struct, field)) for field, _ in struct._fields_) >>> x = S1() >>> getdict(x) {'A': <__main__.c_ushort_Array_10 object at 0x100490680>, 'C': 0L, 'B': 0L} ``` As you can see, it works with numbers but it doesn't work as nicely with ...
Redirecting an old URL to a new one with Flask micro-framework
3,789,462
4
2010-09-24T17:17:51Z
3,789,654
14
2010-09-24T17:49:28Z
[ "python", "url-routing", "flask", "werkzeug" ]
I'm making a new website to replace a current one, using Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case). The core functionality and many pages are the same. However by using Flask many of the previous URLs are different to the old ones. I need a way to somehow store the each of the old U...
Something like this should get you started: ``` from flask import Flask, redirect, request app = Flask(__name__) redirect_urls = { 'http://example.com/old/': 'http://example.com/new/', ... } def redirect_url(): return redirect(redirect_urls[request.url], 301) for url in redirect_urls: app.add_url_r...
Java: Equivalent of Python's range(int, int)?
3,790,142
52
2010-09-24T19:04:50Z
3,790,192
10
2010-09-24T19:12:29Z
[ "java", "python" ]
Does Java have an equivalent to Python's `range(int, int)` method?
``` public int[] range(int start, int stop) { int[] result = new int[stop-start]; for(int i=0;i<stop-start;i++) result[i] = start+i; return result; } ``` Forgive any syntax or style errors; I normally program in C#.
Java: Equivalent of Python's range(int, int)?
3,790,142
52
2010-09-24T19:04:50Z
7,602,118
13
2011-09-29T19:01:47Z
[ "java", "python" ]
Does Java have an equivalent to Python's `range(int, int)` method?
I'm working on a little Java utils library called [Jools](https://github.com/Nurdok/Jools), and it contains a class `Range` which provides the functionality you need (there's a downloadable JAR). Constructors are either `Range(int stop)`, `Range(int start, int stop)`, or `Range(int start, int stop, int step)` (simili...
Java: Equivalent of Python's range(int, int)?
3,790,142
52
2010-09-24T19:04:50Z
13,589,954
15
2012-11-27T17:40:44Z
[ "java", "python" ]
Does Java have an equivalent to Python's `range(int, int)` method?
[Guava](http://code.google.com/p/guava-libraries/) also provides something similar to Python's `range`: ``` Range.closed(1, 5).asSet(DiscreteDomains.integers()); ``` You can also implement a fairly simple iterator to do the same sort of thing using Guava's AbstractIterator: ``` return new AbstractIterator<Integer>()...
Java: Equivalent of Python's range(int, int)?
3,790,142
52
2010-09-24T19:04:50Z
17,779,666
13
2013-07-22T03:51:57Z
[ "java", "python" ]
Does Java have an equivalent to Python's `range(int, int)` method?
Since Guava 15.0, [Range.asSet()](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#asSet%28com.google.common.collect.DiscreteDomain%29) has been deprecated and is scheduled to be removed in version 16. Use the following instead: ``` ContiguousSet.create(Range.closed(1, 5), Di...
Java: Equivalent of Python's range(int, int)?
3,790,142
52
2010-09-24T19:04:50Z
22,903,362
100
2014-04-07T04:00:38Z
[ "java", "python" ]
Does Java have an equivalent to Python's `range(int, int)` method?
Old question, new answer (for Java 8) ``` IntStream.range(0, 10).forEach( n -> { System.out.println(n); } ); ``` or with method references: ``` IntStream.range(0, 10).forEach(System.out::println); ```
python list to newline separated value
3,790,805
2
2010-09-24T20:38:25Z
3,790,834
8
2010-09-24T20:43:00Z
[ "jquery", "python", "pylons" ]
Im trying to get data in pylon to use in jquery autocomplete, the librarary i'm using for autocomplete it requires this format ``` abc pqr xyz ``` and in python i have data in this format ``` [["abc"], ["pqr"],["xyz"] ``` How do i convert this list to the above one. Edit: I trying to use these for a autocompete ...
``` "\n".join(item[0] for item in my_list) ``` However, what's this got to do with JSON...?
Fastest way to convert an iterator to a list
3,790,848
79
2010-09-24T20:45:26Z
3,790,862
146
2010-09-24T20:48:10Z
[ "python", "code-review", "list-comprehension" ]
Having an `iterator` object, is there something faster, better or more correct than a list comprehension to get a list of the objects returned by the iterator? ``` user_list = [user for user in user_iterator] ```
``` list(your_iterator) ```
Python number wrapping?
3,791,312
6
2010-09-24T21:57:24Z
3,791,356
9
2010-09-24T22:05:12Z
[ "python" ]
Consider this Python code: ``` assert(a > 0) assert(b > 0) assert(a + b > 0) ``` Can the third assert ever fail? In C/C++, it can if the sum overflows the maximum integer value. How is this handled in Python?
Depends on which version of Python you're using. Prior to 2.2 or so, you could get an `OverflowError`. Version 2.2-2.7 promote the sum to a `long` (arbitrary precision) if it's too large to fit in an `int`. 3.0+ has only one integer type, which is arbitrary precision.
How to stop python from propagating signals to subprocesses?
3,791,398
18
2010-09-24T22:12:10Z
5,446,983
16
2011-03-27T03:17:13Z
[ "python", "subprocess", "signals" ]
I'm using python to manage some simulations. I build the parameters and run the program using: ``` pipe = open('/dev/null', 'w') pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe) ``` My code handles different signal. Ctrl+C will stop the simulation, ask if I want to save, and exit gracefully. I h...
Combining some of other answers that will do the trick - no signal sent to main app will be forwarded to the subprocess. ``` import os from subprocess import Popen def preexec(): # Don't forward signals. os.setpgrp() Popen('whatever', preexec_fn = preexec) ```
How can you select a random element from a list, and have it be removed?
3,791,400
3
2010-09-24T22:13:08Z
3,791,435
7
2010-09-24T22:20:40Z
[ "python", "random" ]
Let's say I have a list of colours, `colours = ['red', 'blue', 'green', 'purple']`. I then wish to call this python function that I hope exists, `random_object = random_choice(colours)`. Now, if random\_object holds 'blue', I hope `colours = ['red', 'green', 'purple']`. Does such a function exist in python?
Firstly, if you want it removed because you want to do this again and again, you might want to use `random.shuffle()` in the random module. `random.choice()` picks one, but does not remove it. Otherwise, try: ``` import random # this will choose one and remove it def choose_and_remove( items ): # pick an item i...
Python, os.system for command-line call (linux) not returning what it should?
3,791,465
41
2010-09-24T22:26:26Z
3,791,476
74
2010-09-24T22:28:43Z
[ "python", "linux", "python-2.7", "command-line", "os.system" ]
I need to make some command line calls to linux and get the return from this, however doing it as below is just returning `0` when it should return a time value, like `00:08:19`, I am testing the exact same call in regular command line and it returns the time value `00:08:19` so I am confused as to what I am doing wron...
What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution. Use popen etc for capturing the output . Some thing along this line: ``` import subprocess as sub p = sub.Po...
Python, os.system for command-line call (linux) not returning what it should?
3,791,465
41
2010-09-24T22:26:26Z
3,791,993
17
2010-09-25T01:04:02Z
[ "python", "linux", "python-2.7", "command-line", "os.system" ]
I need to make some command line calls to linux and get the return from this, however doing it as below is just returning `0` when it should return a time value, like `00:08:19`, I am testing the exact same call in regular command line and it returns the time value `00:08:19` so I am confused as to what I am doing wron...
If you're only interested in the output from the process, it's easiest to use subprocess' [check\_output](http://docs.python.org/library/subprocess.html#subprocess.check_output) function: ``` output = subprocess.check_output(["command", "arg1", "arg2"]); ``` Then output holds the program output to stdout. Check the l...
Which python version needs from __future__ import with_statement?
3,791,903
18
2010-09-25T00:26:56Z
3,791,936
14
2010-09-25T00:38:51Z
[ "python", "python-import" ]
Using python 2.6.5, I can use the `with` statement without calling `from __future__ import with_statement`. How can I tell which version of Python supports `with` without specifically importing it from `__future__`?
You only need it in Python 2.5. Older versions (<= 2.4) don't support it and newer versions (>= 2.6) have it enabled by default. So if you want to support Python >= 2.5, you can simply put the `from __future__ import with_statement` at the beginning. For newer versions, it will simply be ignored.
Which python version needs from __future__ import with_statement?
3,791,903
18
2010-09-25T00:26:56Z
3,792,223
38
2010-09-25T02:29:30Z
[ "python", "python-import" ]
Using python 2.6.5, I can use the `with` statement without calling `from __future__ import with_statement`. How can I tell which version of Python supports `with` without specifically importing it from `__future__`?
`__future__` features are self-documenting. Try this: ``` >>> from __future__ import with_statement >>> with_statement.getOptionalRelease() (2, 5, 0, 'alpha', 1) >>> with_statement.getMandatoryRelease() (2, 6, 0, 'alpha', 0) ``` These respectively indicate the first release supporting `from __future__ import with_sta...
Will reloading supervisord cause the process under its to stop?
3,792,081
13
2010-09-25T01:34:47Z
3,792,150
37
2010-09-25T02:04:25Z
[ "python", "reload", "supervisord" ]
I try to figure out when I used reload command to supervisord. Will it stop the processing currently executing under it? I used below steps: ``` mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) mlzboy@mlzboy-mac:~/my/ide/test$ supervisorctl daemon STARTING ...
It doesn't kill the supervisord process, it just stops all processes, reload the configuration file, and restart processes again. If you just want to apply the new configurations use `reread` command. It'd just reload the configuration without stopping, and respawning processes. And running `update` will restart the ...
Mapping Languages to Paradigms
3,793,030
3
2010-09-25T08:25:50Z
3,793,170
11
2010-09-25T09:08:20Z
[ "java", "c++", "python", "perl", "lisp" ]
I recently read Eric Steven Raymond's article "How To Become A Hacker" and I like his suggestion of learning 5 key languages (he suggests Python, C/C++, Lisp, Java, and Perl) as a way of covering the main programming paradigms in use today. His advice is that it's not so important which specific languages a programmer...
I think you're approaching it wrong. As esr himself says, it's not the *language* that matters, it's the *paradigm*. So when you say that > 1. Perl is a functional language > 2. It's great for quick text substitutions in multiple files from the command line you are missing one of the main points of a functional langu...
How to install a Python Recipe File (.py)?
3,793,123
3
2010-09-25T08:53:17Z
3,793,208
7
2010-09-25T09:22:40Z
[ "python", "install", "python-3.x", "recipe" ]
I'm new to Python. I'm currently on Py3k (Win). I'm having trouble installing a `.py` file. Basically, i want to use the recipes provided at the bottom of [this](http://docs.python.org/py3k/library/itertools.html) page. So i want to put them inside a `.py` and `import` them in *any* of my source codes. So i copied al...
There are two closely-related issues. First, *within* recipes.py, you need access to all of itertools. At the very least, this means you need ``` import itertools ``` at the top. But in this case you would need to qualify all of the itertools functions as `itertools.<funcname>`, as you say. (You could also use `imp...
How to set up a staging environment on Google App Engine
3,793,860
42
2010-09-25T12:48:09Z
3,805,305
11
2010-09-27T15:26:38Z
[ "python", "google-app-engine", "deployment", "staging" ]
Having properly configured a *Development* server and a *Production* server, I would like to set up a *Staging* environment on Google App Engine useful to test new developed versions live before deploying them to production. I know two different approaches: **A.** The first option is by modifying the [app.yaml](http:...
I chose the second option in my set-up, because it was the quickest solution, and I didn't make any script to change the application-parameter on deployment yet. But the way I see it now, option A is a cleaner solution. You can with a couple of code lines switch the datastore namespace based on the version, which you ...
How to set up a staging environment on Google App Engine
3,793,860
42
2010-09-25T12:48:09Z
10,279,945
13
2012-04-23T11:47:55Z
[ "python", "google-app-engine", "deployment", "staging" ]
Having properly configured a *Development* server and a *Production* server, I would like to set up a *Staging* environment on Google App Engine useful to test new developed versions live before deploying them to production. I know two different approaches: **A.** The first option is by modifying the [app.yaml](http:...
If separate datastore is required, **option B looks cleaner solution for me** because: 1. You can keep versions feature for real versioning of production applications. 2. You can keep versions feature for traffic splitting. 3. You can keep namespaces feature for multi-tenancy. 4. You can easily copy entities to one ap...
Command for clicking on the items of a Tkinter Treeview widget?
3,794,268
8
2010-09-25T14:53:04Z
3,794,505
14
2010-09-25T16:10:16Z
[ "python", "user-interface", "treeview", "tkinter" ]
I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the `Treeview` objects to *change* when an item (i.e. a directory) is *clicked twice*. If Treeview items were buttons, I'd just be able to set `command` to the appropriate function. But I'm having trouble findi...
If you want something to happen when the user double-clicks, add a binding to `"<Double-1>"`. Since a single click sets the selection, in your callback you can query the widget to find out what is selected. For example: ``` import tkinter as tk from tkinter import ttk class App: def __init__(self): self.r...
Command for clicking on the items of a Tkinter Treeview widget?
3,794,268
8
2010-09-25T14:53:04Z
14,118,529
8
2013-01-02T07:46:43Z
[ "python", "user-interface", "treeview", "tkinter" ]
I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the `Treeview` objects to *change* when an item (i.e. a directory) is *clicked twice*. If Treeview items were buttons, I'd just be able to set `command` to the appropriate function. But I'm having trouble findi...
The previous solution fails when multiple elements are selected and the user uses `SHIFT+CLICK` (at least on a Mac). Here is a better solution: ``` import tkinter as tk import tkinter.ttk as ttk class App: def __init__(self): self.root = tk.Tk() self.tree = ttk.Treeview() self.tree.pack()...
Python ctypes: Python file object <-> C FILE *
3,794,309
8
2010-09-25T15:07:26Z
3,794,401
22
2010-09-25T15:33:43Z
[ "python", "ctypes" ]
I am using ctypes to wrap a C-library (which I have control over) with Python. I want to wrap a C-function with declaration: ``` int fread_int( FILE * stream ); ``` Now; I would like to open file in python, and then use the Python file-object (in some way??) to get access to the underlying FILE \* object and pass tha...
A Python file object does not necessarily *have* an underlying C-level `FILE *` -- at least, not unless you're willing to tie your code to extremely specific Python versions and platforms. What I would recommend instead is using the Python file object's `fileno` to get a file descriptor, then use `ctypes` to call the ...
why i can't reverse a list of list in python
3,794,486
11
2010-09-25T16:05:23Z
3,794,553
8
2010-09-25T16:29:15Z
[ "python", "list", "reverse", "map-function" ]
i wanted to do something like this but this code return list of None (i think it's because list.reverse() is reversing the list in place): ``` map(lambda row: row.reverse(), figure) ``` i tried this one, but the reversed return an iterator : ``` map(reversed, figure) ``` finally i did something like this , which wo...
You can also use a slice to get the reversal of a single list (*not* in place): ``` >>> a = [1,2,3,4] >>> a[::-1] [4, 3, 2, 1] ``` So something like: ``` all_reversed = [lst[::-1] for lst in figure] ``` ...or... ``` all_reversed = map(lambda x: x[::-1], figure) ``` ...will do what you want.
why i can't reverse a list of list in python
3,794,486
11
2010-09-25T16:05:23Z
3,794,626
27
2010-09-25T16:54:56Z
[ "python", "list", "reverse", "map-function" ]
i wanted to do something like this but this code return list of None (i think it's because list.reverse() is reversing the list in place): ``` map(lambda row: row.reverse(), figure) ``` i tried this one, but the reversed return an iterator : ``` map(reversed, figure) ``` finally i did something like this , which wo...
The *mutator* methods of Python's mutable containers (such as the `.reverse` method of lists) almost invariably return `None` -- a few return one useful value, e.g. the `.pop` method returns the popped element, but the key concept to retain is that none of those mutators returns the mutated container: rather, the conta...
Extract the time from a UUID v1 in python
3,795,554
8
2010-09-25T21:05:19Z
3,795,750
14
2010-09-25T21:57:40Z
[ "python", "timestamp", "uuid" ]
I have some UUIDs that are being generated in my program at random, but I want to be able to extract the timestamp of the generated UUID for testing purposes. I noticed that using the `fields` accessor I can get the various parts of the timestamp but I have no idea on how to combine them.
Looking inside /usr/lib/python2.6/uuid.py I see ``` def uuid1(node=None, clock_seq=None): ... nanoseconds = int(time.time() * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds/...
Python tool for incorporating imported items
3,795,629
3
2010-09-25T21:27:35Z
3,795,738
7
2010-09-25T21:53:59Z
[ "python", "parsing", "import" ]
Is there a tool in python to rewrite some code which imports things such that it no longer has to import anything? Take a library that draws a box called box.py ``` def box(text='Hello, World!') draw the box magic return ``` Now in another program (we'll call it warning.py) it says: ``` from box import box ...
It sounds like you're wanting to effectively copy-paste everything into one file to be able to distribute a single file instead of several? In that case, look into using a zipped module instead of copy-pasting everything into one file... This is far more maintainable in the long run. Python will execute a zip file if...
counting non-zero elements within each row and within each column of a 2D numpy array
3,797,158
11
2010-09-26T09:07:06Z
3,797,190
19
2010-09-26T09:22:38Z
[ "python", "arrays", "count", "numpy" ]
I have a numpy matrix that contains mostly nonzero values, but that occasionally will contain a zero value. I need to be able to: 1.) count the non-zero values in each row, and put that count into a variable that I can use in subsequent operations, perhaps by iterating through row indices and performing the calculati...
``` import numpy as np a = np.array([[1, 0, 1], [2, 3, 4], [0, 0, 7]]) columns = (a != 0).sum(0) rows = (a != 0).sum(1) ``` The variable `(a != 0)` is an array of the same shape as original `a` and it contains `True` for all non-zero elements. The `.sum(x)` function sums the elements ...
object oriented programming basics (python)
3,797,219
2
2010-09-26T09:33:07Z
3,797,224
7
2010-09-26T09:36:40Z
[ "python", "oop" ]
Level: Beginner In the following code my 'samePoint' function returns False where i am expecting True. Any hints? ``` import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self....
Looking at your code ``` def samePoint(p, q): return (p.cartesian == q.cartesian) ``` p.cartesian, q.cartesian are functions and you are comparing function rather than function result. Since the comparing two distinct functions, the result is False What you should have been coding is ``` def samePoint(p, q): ...
find largest power of two less than X number?
3,797,575
8
2010-09-26T11:29:51Z
3,797,589
20
2010-09-26T11:32:48Z
[ "find", "python" ]
I m doing this ``` def power_two(n, base = -1): result = 2 ** base if result < n: base += 1 power_two(n, base) else: if result == n: print base else: print base - 1 ``` what is the pythonic way to find largest power of two less than X number? EDIT e...
Find the logarithm and truncate it: ``` def power_two(n): return int(math.log(n, 2)) ```
find largest power of two less than X number?
3,797,575
8
2010-09-26T11:29:51Z
3,797,818
12
2010-09-26T12:43:28Z
[ "find", "python" ]
I m doing this ``` def power_two(n, base = -1): result = 2 ** base if result < n: base += 1 power_two(n, base) else: if result == n: print base else: print base - 1 ``` what is the pythonic way to find largest power of two less than X number? EDIT e...
You could use [bit\_length()](http://docs.python.org/library/stdtypes.html#additional-methods-on-integer-types): ``` def power_two(n): return n.bit_length() - 1 ``` By definition for `n != 0`: `2**(n.bit_length()-1) <= abs(n) < 2**n.bit_length()`
How to do a Python split() on languages (like Chinese) that don't use whitespace as word separator?
3,797,746
11
2010-09-26T12:21:58Z
3,797,753
13
2010-09-26T12:24:31Z
[ "python", "string", "unicode", "nlp", "cjk" ]
I want to split a sentence into a list of words. For English and European languages this is easy, just use split() ``` >>> "This is a sentence.".split() ['This', 'is', 'a', 'sentence.'] ``` But I also need to deal with sentences in languages such as Chinese that don't use whitespace as word separator. ``` >>> u"这...
You can do this but not with standard library functions. And regular expressions won't help you either. The task you are describing is part of the field called [Natural Language Processing](http://en.wikipedia.org/wiki/Natural_language_processing) (NLP). There has been quite a lot of work done already on splitting Chi...
How to do a Python split() on languages (like Chinese) that don't use whitespace as word separator?
3,797,746
11
2010-09-26T12:21:58Z
3,798,790
9
2010-09-26T16:43:43Z
[ "python", "string", "unicode", "nlp", "cjk" ]
I want to split a sentence into a list of words. For English and European languages this is easy, just use split() ``` >>> "This is a sentence.".split() ['This', 'is', 'a', 'sentence.'] ``` But I also need to deal with sentences in languages such as Chinese that don't use whitespace as word separator. ``` >>> u"这...
just a word of caution: using `list( '...' )` (in Py3; that's `u'...'` for Py2) will *not*, in the general sense, give you the *characters* of a unicode string; rather, it will most likely result in a series of 16bit codepoints. this is true for all 'narrow' CPython builds, which accounts for the vast majority of pytho...
Python: Easily access deeply nested dict (get and set)
3,797,957
19
2010-09-26T13:23:28Z
3,798,595
31
2010-09-26T16:00:58Z
[ "python" ]
I'm building some Python code to read and manipulate deeply nested dicts (ultimately for interacting with JSON services, however it would be great to have for other purposes) I'm looking for a way to easily read/set/update values deep within the dict, without needing a lot of code. @see also <http://stackoverflow.com/...
# Attribute Tree The problem with your first specification is that Python can't tell in `__getitem__` if, at `my_obj.a.b.c.d`, you will next proceed farther down a nonexistent tree, in which case it needs to return an object with a `__getitem__` method so you won't get an `AttributeError` thrown at you, or if you want...
How to write script output to file and command-line?
3,797,958
7
2010-09-26T13:23:40Z
3,798,199
14
2010-09-26T14:24:23Z
[ "python", "unix", "command-line" ]
I have a long-running Python script that I run from the command-line. The script writes progress messages and results to the standard output. I want to capture everything the script write to the standard output in a file, but also see it on the command line. Alternatively, I want the output to go to the file immediatel...
You are on the right path but the problem is python buffering the output. Fortunately there is a way to tell it not to buffer output: ``` python -u MyLongRunngingScript.py | tee log.txt ```
How to select a Radio Button?
3,798,138
8
2010-09-26T14:05:27Z
3,798,182
9
2010-09-26T14:18:36Z
[ "python", "radio-button", "mechanize" ]
I am using `mechanize` and I am trying to select a button from a radio button list. This list has 5 items. How can I select the first item? Docs didn't help me. ``` >>> br.form <ClientForm.HTMLForm instance at 0x9ac0d4c> >>> print(br.form) <form1 POST http://www.example.com application/x-www-form-urlencoded <HiddenCon...
[It should be as simple as](http://wwwsearch.sourceforge.net/mechanize/forms.html) ``` br.form['prodclass'] = ['1'] ``` I prefer the more verbose: ``` br.form.set_value(['1'],name='prodclass') ```
Combining a url with urlunparse
3,798,269
6
2010-09-26T14:42:54Z
3,798,311
8
2010-09-26T14:55:10Z
[ "python", "urlparse" ]
I'm writing something to 'clean' a URL. In this case all I'm trying to do is return a faked scheme as `urlopen` won't work without one. However, if I test this with `www.python.org` It'll return `http:///www.python.org`. Does anyone know why the extra /, and is there a way to return this without it? ``` def FixScheme(...
Problem is that in parsing the *very* incomplete URL `www.python.org`, the string you give is actually taken as the `path` component of the URL, with the `netloc` (network location) one being empty as well as the scheme. For defaulting the scheme you can actually pass a second parameter `scheme` to `urlparse` (simplify...
image information along a polar coordinate system
3,798,333
13
2010-09-26T15:01:49Z
3,806,851
29
2010-09-27T18:53:39Z
[ "python", "image-processing", "numpy", "scipy" ]
I have a set of png images that I would like to process with Python and associated tools. Each image represents a physical object with known dimensions. In each image there is a specific feature of the object at a certain pixel/physical location. The location is different for each image. I would like to impose a pola...
What you're describing isn't exactly image processing in the traditional sense, but it's fairly easy to do with numpy, etc. Here's a rather large example doing some of the things you mentioned to get you pointed in the right direction... Note that the example images all show results for the origin at the center of the...
Why urllib2.urlopen can not open pages like "http://localhost/new-post#comment-29"?
3,798,422
2
2010-09-26T15:21:09Z
3,798,468
7
2010-09-26T15:31:04Z
[ "python", "urllib2", "fragment-identifier", "urlopen" ]
I'm curious, how come I get 404 error running this line: ``` urllib2.urlopen("http://localhost/new-post#comment-29") ``` While everything works fine surfing <http://localhost/new-post#comment-29> in any browser... urlopen method does not parse urls with "#" in it? Anybody knows?
In the HTTP protocol, the fragment (from `#` onwards) is not sent to the server across the network: it's locally retained by the browser and used, once the server's response is fully received, to somehow "visually locate" the exact spot in the page to be shown as "current" (for example, if the returned page is in HTML,...
How to compare dates in Django
3,798,812
25
2010-09-26T16:49:21Z
3,798,865
58
2010-09-26T17:06:00Z
[ "python", "django", "django-templates" ]
I would like to compare a date to the current date in Django, preferably in the template, but it is also possible to do before rendering the template. If the date has already passed, I want to say "In the past" while if it is in the future, I want to give the date. I was hoping one could do something like this: ``` {...
Compare date in the view, and pass something like `in_the_past` (boolean) to the extra\_context. **Or better add it to the model as a property.** ``` from datetime import date @property def is_past_due(self): if date.today() > self.date: return True return False ``` Then in the view: ``` {% if list...
How to compare dates in Django
3,798,812
25
2010-09-26T16:49:21Z
4,831,464
9
2011-01-28T17:55:55Z
[ "python", "django", "django-templates" ]
I would like to compare a date to the current date in Django, preferably in the template, but it is also possible to do before rendering the template. If the date has already passed, I want to say "In the past" while if it is in the future, I want to give the date. I was hoping one could do something like this: ``` {...
I added date\_now to my list of context processors. So in the template there's a variable called "date\_now" which is just datetime.datetime.now() Make a context processor called date\_now in the file context\_processors.py ``` import datetime def date_now(request): return {'date_now':datetime.datetime.now()} `...
Understanding __get__ and __set__ and Python descriptors
3,798,835
193
2010-09-26T16:55:42Z
3,798,882
86
2010-09-26T17:08:18Z
[ "python", "descriptor" ]
I am *trying* to understand what Python's descriptors are and what they can useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code: ``` class Celsius(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, ins...
The descriptor is how Python's `property` type is implemented. A descriptor simply implements `__get__`, `__set__`, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example: ``` temp=Temperature() temp.celsius #calls celsius.__get__ ``` Accessing the propert...
Understanding __get__ and __set__ and Python descriptors
3,798,835
193
2010-09-26T16:55:42Z
18,038,707
48
2013-08-04T00:41:58Z
[ "python", "descriptor" ]
I am *trying* to understand what Python's descriptors are and what they can useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code: ``` class Celsius(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, ins...
> Why do I need the descriptor class? Please explain using this example or the one you think is better. it gives you extra control over how attributes work. if you're used to getters and setters in java, for example, then it's python's way of doing that. one advantage is that it looks to users just like an attribute (...
Understanding __get__ and __set__ and Python descriptors
3,798,835
193
2010-09-26T16:55:42Z
34,554,353
12
2016-01-01T07:22:20Z
[ "python", "descriptor" ]
I am *trying* to understand what Python's descriptors are and what they can useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code: ``` class Celsius(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, ins...
> **I am trying to understand what Python's descriptors are and what they > can useful for.** # Short Answer Descriptors are objects with any of `__get__`, `__set__`, or `__delete__`. These descriptor objects can be used as attributes on other object class definitions. Descriptor objects can be used to programmatica...
Appengine - Reportlab (Get Photo from Model)
3,798,885
3
2010-09-26T17:08:40Z
3,810,736
10
2010-09-28T07:56:20Z
[ "python", "google-app-engine", "django-models", "reportlab" ]
I´m using Reportlab to generate a PDF. Can´t retrieve a photo from a model. ``` #Personal Info p.drawImage('myPhoto.jpg', 40, 730) p.drawString(50, 670, 'Your name:' + '%s' % user.name) p.drawImage (50, 640, 'Photo: %s' % (user.photo)) ``` When i create on generate PDF, i got this error: ``` Tra...
According to the [ReportLab API reference](http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html#module-reportlab.pdfgen.canvas), drawImage() has arguments 'image, x, y', whereas it looks as though you are passing 'x, y, string'. The image argument to drawImage() requires a filename or ImageReader. According to [th...
Speeding up Django Testing
3,799,061
14
2010-09-26T17:51:01Z
3,799,122
7
2010-09-26T18:04:24Z
[ "python", "django", "unit-testing" ]
Im looking to learn more about your testing flows with Django. Background information <http://docs.djangoproject.com/en/dev/topics/testing/> Im encountering difficulties when using test driven development. The test runner of Django constantly creates all db models in a test db when starting. For our current projects ...
Using an in-memory SQLite database during testing definitely speeds things up.
Speeding up Django Testing
3,799,061
14
2010-09-26T17:51:01Z
3,801,433
7
2010-09-27T06:03:15Z
[ "python", "django", "unit-testing" ]
Im looking to learn more about your testing flows with Django. Background information <http://docs.djangoproject.com/en/dev/topics/testing/> Im encountering difficulties when using test driven development. The test runner of Django constantly creates all db models in a test db when starting. For our current projects ...
> change the testloader to reuse the same test db every time and apply migrations when needed 1. I don't see anything wrong in writing your own test runner that merely truncates the tables instead of dropping and creating the database. This is djangoic in that it solves a specific problem. There is a [ticket](http://c...
Dynamically importing Python module
3,799,545
24
2010-09-26T19:57:18Z
3,799,609
38
2010-09-26T20:13:35Z
[ "python", "dynamic-import" ]
I have a trusted remote server that stores many custom Python modules. I can fetch them via HTTP (e.g. using `urllib2.urlopen`) as text/plain, but I cannot save the fetched module code to the local hard disk. How can I import the code as a fully operable Python module, including its global variables and imports? I su...
It looks like this should do the trick: [importing a dynamically generated module](http://code.activestate.com/recipes/82234-importing-a-dynamically-generated-module/) ``` >>> import imp >>> foo = imp.new_module("foo") >>> foo_code = """ ... class Foo: ... pass ... """ >>> exec foo_code in foo.__dict__ >>> foo.Foo...