title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How can I capture the stdout output of a child process?
923,079
7
2009-05-28T20:45:45Z
923,127
20
2009-05-28T20:52:54Z
[ "python", "subprocess", "stdout" ]
I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use `subprocess.popen` or something similar but I'm new to subprocess and have no clue. Anyone have an easy way f...
@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. In case you want to poll output while the process is running you have to do it this way: ``` process = subprocess.Popen(cmd, stdout=subprocess.PIPE) while True: out = process.stdout.readline(1) if o...
Creating lists of lists in a pythonic way
923,111
9
2009-05-28T20:50:30Z
923,147
8
2009-05-28T20:57:09Z
[ "list", "matrix", "python" ]
I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows. ``` mat=[[0]*2]*3 ``` However, when I change the value of one of the items in the matrix, it changes the value of that entry in *every* row, since the id of each row in `mat` is the same. For example, after assi...
Try this: ``` >>> cols = 6 >>> rows = 3 >>> a = [[0]*cols for _ in [0]*rows] >>> a [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] >>> a[0][3] = 2 >>> a [[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] ``` This is also discussed [in this answer](http://stackoverflow.com/questions/691946/short...
Creating lists of lists in a pythonic way
923,111
9
2009-05-28T20:50:30Z
923,171
9
2009-05-28T21:00:21Z
[ "list", "matrix", "python" ]
I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows. ``` mat=[[0]*2]*3 ``` However, when I change the value of one of the items in the matrix, it changes the value of that entry in *every* row, since the id of each row in `mat` is the same. For example, after assi...
Use a [list comprehension](http://docs.python.org/tutorial/datastructures.html?highlight=list%20comprehension#list-comprehensions): ``` >>> mat = [[0]*2 for x in xrange(3)] >>> mat[0][0] = 1 >>> mat [[1, 0], [0, 0], [0, 0]] ``` Or, as a function: ``` def matrix(rows, cols): return [[0]*cols for x in xrange(rows)...
Keeping a session in python while making HTTP requests
923,296
23
2009-05-28T21:28:06Z
923,313
20
2009-05-28T21:32:41Z
[ "python", "http", "authentication" ]
I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. I'm using python 2.3.4
If you want to keep the authentication you need to reuse the cookie. I'm not sure if urllib2 is available in python 2.3.4 but here is an example on how to do it: ``` req1 = urllib2.Request(url1) response = urllib2.urlopen(req1) cookie = response.headers.get('Set-Cookie') # Use the cookie is subsequent requests req2 =...
Keeping a session in python while making HTTP requests
923,296
23
2009-05-28T21:28:06Z
925,043
14
2009-05-29T08:48:54Z
[ "python", "http", "authentication" ]
I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. I'm using python 2.3.4
If this is cookie based authentication use [HTTPCookieProcessor](http://docs.python.org/library/cookielib.html#examples): ``` import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") ``` If this is HTTP authentication us...
Keeping a session in python while making HTTP requests
923,296
23
2009-05-28T21:28:06Z
10,631,831
23
2012-05-17T07:53:27Z
[ "python", "http", "authentication" ]
I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. I'm using python 2.3.4
Use [Requests](https://github.com/kennethreitz/requests) library. From <http://docs.python-requests.org/en/latest/user/advanced/#session-objects> : > The Session object allows you to persist certain parameters across > requests. It also persists cookies across all requests made from the > Session instance. > > ``` > s...
Best way to retrieve variable values from a text file - Python - Json
924,700
20
2009-05-29T06:48:30Z
924,719
13
2009-05-29T06:56:12Z
[ "python", "json", "variables", "text-files" ]
Referring on [this question](http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python), I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: ``` var_a: 'home' var_b: 'car' var_c: 15.5 ``` And I need that python read the file and then create a var...
You can *treat* your text file as a python module and load it dynamically using [`imp.load_source`](https://docs.python.org/2/library/imp.html#imp.load_source): ``` import imp imp.load_source( name, pathname[, file]) ``` Example: ``` // mydata.txt var1 = 'hi' var2 = 'how are you?' var3 = { 1:'elem1', 2:'elem2' } //....
Best way to retrieve variable values from a text file - Python - Json
924,700
20
2009-05-29T06:48:30Z
924,723
18
2009-05-29T06:57:58Z
[ "python", "json", "variables", "text-files" ]
Referring on [this question](http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python), I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: ``` var_a: 'home' var_b: 'car' var_c: 15.5 ``` And I need that python read the file and then create a var...
Use ConfigParser. Your config: ``` [myvars] var_a: 'home' var_b: 'car' var_c: 15.5 ``` Your python code: ``` import ConfigParser config = ConfigParser.ConfigParser() config.read("config.ini") var_a = config.get("myvars", "var_a") var_b = config.get("myvars", "var_b") var_c = config.get("myvars", "var_c") ```
Best way to retrieve variable values from a text file - Python - Json
924,700
20
2009-05-29T06:48:30Z
924,835
11
2009-05-29T07:42:27Z
[ "python", "json", "variables", "text-files" ]
Referring on [this question](http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python), I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: ``` var_a: 'home' var_b: 'car' var_c: 15.5 ``` And I need that python read the file and then create a var...
Load your file with [JSON](http://docs.python.org/library/json.html) or [PyYAML](http://pyyaml.org/wiki/PyYAML) into a dictionary `the_dict` (see doc for JSON or PyYAML for this step, both can store data type) and add the dictionary to your globals dictionary, e.g. using `globals().update(the_dict)`. If you want it in...
Best way to retrieve variable values from a text file - Python - Json
924,700
20
2009-05-29T06:48:30Z
924,866
39
2009-05-29T07:54:55Z
[ "python", "json", "variables", "text-files" ]
Referring on [this question](http://stackoverflow.com/questions/868112/loading-files-into-variables-in-python), I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: ``` var_a: 'home' var_b: 'car' var_c: 15.5 ``` And I need that python read the file and then create a var...
> But what i'll love is to refer to the variable direclty, as i declared it in the python script.. Assuming you're happy to change your syntax slightly, just use python and import the "config" module. ``` # myconfig.py: var_a = 'home' var_b = 'car' var_c = 15.5 ``` Then do ``` from myconfig import * ``` And you c...
How can I remove the top and right axis in matplotlib?
925,024
45
2009-05-29T08:45:12Z
925,141
24
2009-05-29T09:21:20Z
[ "python", "matplotlib" ]
Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.: ``` +------+ | | | | | | ---> | | | | +------+ +------- ``` This should be easy, but I can't find the necessary options in the docs.
[edit] matplotlib in now (2013-10) on version 1.3.0 which includes this That ability was actually just added, and you need the Subversion version for it. You can see the example code [here](http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html). I am just updating to say that there's a better [examp...
How can I remove the top and right axis in matplotlib?
925,024
45
2009-05-29T08:45:12Z
8,011,585
41
2011-11-04T15:20:04Z
[ "python", "matplotlib" ]
Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.: ``` +------+ | | | | | | ---> | | | | +------+ +------- ``` This should be easy, but I can't find the necessary options in the docs.
Alternatively, this ``` def simpleaxis(ax): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() ``` seems to achieve the same effect on an axis without losing rotated label support. (Matplotlib 1.0.1; solution inspired by [...
How can I remove the top and right axis in matplotlib?
925,024
45
2009-05-29T08:45:12Z
27,361,819
16
2014-12-08T15:58:27Z
[ "python", "matplotlib" ]
Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.: ``` +------+ | | | | | | ---> | | | | +------+ +------- ``` This should be easy, but I can't find the necessary options in the docs.
This is the suggested Matplotlib 1.4 solution from the official website [HERE](http://matplotlib.org/examples/ticks_and_spines/spines_demo.html): ``` import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) ax = plt.subplot(111) ax.plot(x, y) # Hide the right and top spines ...
A Python walker that can ignore directories
925,056
8
2009-05-29T08:52:46Z
925,287
7
2009-05-29T10:05:38Z
[ "python", "directory-walk", "ignore-files" ]
I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.
It is possible to modify the second element of [`os.walk`](http://docs.python.org/library/os.html#module-os)'s return values in-place: > [...] the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; t...
A Python walker that can ignore directories
925,056
8
2009-05-29T08:52:46Z
925,291
9
2009-05-29T10:06:40Z
[ "python", "directory-walk", "ignore-files" ]
I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.
Actually, `os.walk` may do exactly what you want. Say I have a list (perhaps a set) of directories to ignore in `ignore`. Then this should work: ``` def my_walk(top_dir, ignore): for dirpath, dirnames, filenames in os.walk(top_dir): dirnames[:] = [ dn for dn in dirnames if os.path...
python queue & multiprocessing queue: how they behave?
925,100
13
2009-05-29T09:08:28Z
925,241
31
2009-05-29T09:53:20Z
[ "python", "queue" ]
This sample code works (I can write something in the file): ``` from multiprocessing import Process, Queue queue = Queue() def _printer(self, queue): queue.put("hello world!!") def _cmdDisp(self, queue): f = file("Cmd.log", "w") print >> f, queue.get() f.close() ``` instead this other sample not: (e...
For your second example, you already gave the explanation yourself---`Queue` is a module, which cannot be called. For the third example: I assume that you use `Queue.Queue` together with `multiprocessing`. A `Queue.Queue` will not be shared between processes. If the `Queue.Queue` is declared before the processes then ...
Uploading multiple images in Django admin
925,305
7
2009-05-29T10:12:53Z
925,339
8
2009-05-29T10:26:07Z
[ "python", "django", "image-uploading" ]
I'm currently building a portfolio site for a client, and I'm having trouble with one small area. I want to be able to upload multiple images (varying number) inline for each portfolio item, and I can't see an obvious way to do it. The most user-friendly way I can see would be a file upload form with a JavaScript cont...
[photologue](http://code.google.com/p/django-photologue/) is a feature-rich photo app for django. it e.g. lets you upload galleries as zip files (which in a sense means uploading multiple files at once), automatically creates thumbnails of different custom sizes and can apply effects to images. I used it once on one pr...
Uploading multiple images in Django admin
925,305
7
2009-05-29T10:12:53Z
925,590
9
2009-05-29T11:36:35Z
[ "python", "django", "image-uploading" ]
I'm currently building a portfolio site for a client, and I'm having trouble with one small area. I want to be able to upload multiple images (varying number) inline for each portfolio item, and I can't see an obvious way to do it. The most user-friendly way I can see would be a file upload form with a JavaScript cont...
You can extend the Admin interface pretty easily using Javascript. There's a [good article](http://www.arnebrodowski.de/blog/507-Add-and-remove-Django-Admin-Inlines-with-JavaScript.html) on doing exactly what you want with a bit of jQuery magic. You would just have to throw all of his code into one Javascript file and...
Giving anonymous users the same functionality as registered ones
925,456
6
2009-05-29T11:00:55Z
925,465
9
2009-05-29T11:04:43Z
[ "python", "django", "session" ]
I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this: ``` class Cart(models.Model): user = models.OneToOneField(User) class CartItem(mode...
I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object. This m...
Jump into a Python Interactive Session mid-program?
925,832
11
2009-05-29T12:58:07Z
3,650,728
8
2010-09-06T10:28:37Z
[ "python", "eclipse", "debugging", "breakpoints", "pydev" ]
Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering: **Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?** I think that would be pretty handy ;) **edit**: I want to emphasi...
So roughly a year on from the OP's question, PyDev has this capability built in. I am not sure when this feature was introduced, but all I know is I've spent the last ~2hrs Googling... configuring iPython and whatever (which was looking like it would have done the job), but only to realise Eclipse/PyDev has what I want...
parsing in python
925,839
3
2009-05-29T13:00:15Z
925,843
18
2009-05-29T13:02:42Z
[ "python" ]
I have following string adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0 I need only the value of adId,siteId and userId. means 4028cb901dd9720a011e1160afbc01a3 8a8ee4f720e6beb70120e6d8e08b0002 5082a05c-015e-4266-9874-5dc6262da3e0 all the 3 ...
You can split them to a dictionary if you don't need any fancy parsing: ``` In [2]: dict(kvpair.split(':') for kvpair in s.split(';')) Out[2]: {'adId': '4028cb901dd9720a011e1160afbc01a3', 'siteId': '8a8ee4f720e6beb70120e6d8e08b0002', 'userId': '5082a05c-015e-4266-9874-5dc6262da3e0'} ```
Are inner-classes unpythonic?
926,327
2
2009-05-29T14:40:35Z
926,388
8
2009-05-29T14:49:32Z
[ "python" ]
My colleague just pointed out that my use of inner-classes seemed to be "unpythonic". I guess it violates the "flat is better than nested" heuristic. What do people here think? Are inner-classes something which are more appropriate to Java etc than Python? NB : I don't think this is a "subjective" question. Surely st...
"Flat is better than nested" is focused on avoiding *excessive* nesting -- i.e., seriously deep hierarchies. One level of nesting, per se, is no big deal: as long as your nesting still respects (a weakish form of) the [Law of Demeter](http://en.wikipedia.org/wiki/Law%5Fof%5FDemeter), as typically confirmed by the fact ...
Are inner-classes unpythonic?
926,327
2
2009-05-29T14:40:35Z
926,443
8
2009-05-29T14:58:56Z
[ "python" ]
My colleague just pointed out that my use of inner-classes seemed to be "unpythonic". I guess it violates the "flat is better than nested" heuristic. What do people here think? Are inner-classes something which are more appropriate to Java etc than Python? NB : I don't think this is a "subjective" question. Surely st...
This may not deserve a [subjective] tag on StackOverflow, but it's subjective on the larger stage: some language communities encourage nesting and others discourage it. So why would the Python community discourage nesting? Because Tim Peters put it in [The Zen of Python](http://www.python.org/dev/peps/pep-0020/)? Does ...
Why does defining __getitem__ on a class make it iterable in python?
926,574
34
2009-05-29T15:22:53Z
926,609
33
2009-05-29T15:29:22Z
[ "python", "iterator", "overloading" ]
Why does defining \_\_getitem\_\_ on a class make it iterable? For instance if I write: ``` class b: def __getitem__(self, k): return k cb = b() for k in cb: print k ``` I get the output: ``` 0 1 2 3 4 5 6 7 8 ... ``` I would really expect to see an error returned from "for k in cb:"
If you take a look at [PEP234](http://www.python.org/dev/peps/pep-0234) defining iterators, it says: ``` 1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). ```
Why does defining __getitem__ on a class make it iterable in python?
926,574
34
2009-05-29T15:22:53Z
926,645
42
2009-05-29T15:37:35Z
[ "python", "iterator", "overloading" ]
Why does defining \_\_getitem\_\_ on a class make it iterable? For instance if I write: ``` class b: def __getitem__(self, k): return k cb = b() for k in cb: print k ``` I get the output: ``` 0 1 2 3 4 5 6 7 8 ... ``` I would really expect to see an error returned from "for k in cb:"
Iteration's support for `__getitem__` can be seen as a "legacy feature" which allowed smoother transition when PEP234 introduced iterability as a primary concept. It only applies to classes without `__iter__` whose `__getitem__` accepts integers 0, 1, &c, and raises `IndexError` once the index gets too high (if ever), ...
Why does defining __getitem__ on a class make it iterable in python?
926,574
34
2009-05-29T15:22:53Z
926,649
16
2009-05-29T15:38:10Z
[ "python", "iterator", "overloading" ]
Why does defining \_\_getitem\_\_ on a class make it iterable? For instance if I write: ``` class b: def __getitem__(self, k): return k cb = b() for k in cb: print k ``` I get the output: ``` 0 1 2 3 4 5 6 7 8 ... ``` I would really expect to see an error returned from "for k in cb:"
`__getitem__` predates the iterator protocol, and was in the past the *only* way to make things iterable. As such, it's still supported as a method of iterating. Essentially, the protocol for iteration is: 1. Check for an `__iter__` method. If it exists, use the new iteration protocol. 2. Otherwise, try calling `__get...
Checking to See if a List Exists Within Another Lists?
926,946
2
2009-05-29T16:35:44Z
926,977
8
2009-05-29T16:42:12Z
[ "python", "list" ]
Okay I'm trying to go for a more pythonic method of doing things. How can i do the following: ``` required_values = ['A','B','C'] some_map = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} for required_value in required_values: if not required_value in some_map: print 'It Doesnt Exists' return False return ...
``` all(value in some_map for value in required_values) ```
how to parse windows inf files for python?
927,279
3
2009-05-29T17:52:31Z
927,306
10
2009-05-29T17:57:35Z
[ "python", "windows", "parsing", "file", "drivers" ]
please help me. example inf file : ``` ;============================================================================= ; ; Copyright (c) Intel Corporation (2002). ; ; INTEL MAKES NO WARRANTY OF ANY KIND REGARDING THE CODE. THIS CODE IS ; LICENSED ON AN "AS IS" BASIS AND INTEL WILL NOT PROVIDE ANY SUPPORT, ; ASSISTANCE...
You may try the built-in ConfigParser <http://docs.python.org/library/configparser.html> As well as ConfigObj <http://code.google.com/p/configobj/> Both claim to be able to handle Windows INI files.
Parsing HTTP User-Agent string
927,552
45
2009-05-29T18:53:46Z
1,151,956
63
2009-07-20T06:24:40Z
[ "python", "http", "http-headers", "user-agent" ]
What is the best method to parse a User-Agent string in Python to reliably detect 1. Browser 2. Browser version 3. OS Or perhaps any helper library that does it
Answering my own question ;) Finally I decided to go by suggestion#1 i.e. write your own. And I am happy with the outcome. Please feel free to use/modify/send me patch etc. It's here -> <http://pypi.python.org/pypi/httpagentparser>
Parsing HTTP User-Agent string
927,552
45
2009-05-29T18:53:46Z
1,339,838
10
2009-08-27T09:10:50Z
[ "python", "http", "http-headers", "user-agent" ]
What is the best method to parse a User-Agent string in Python to reliably detect 1. Browser 2. Browser version 3. OS Or perhaps any helper library that does it
[UASparser for Python](http://user-agent-string.info/download/UASparser-for-Python) by Hicro Kee. Auto updated datafile and cache from remote server with version checking.
Parsing HTTP User-Agent string
927,552
45
2009-05-29T18:53:46Z
11,148,234
8
2012-06-21T23:25:03Z
[ "python", "http", "http-headers", "user-agent" ]
What is the best method to parse a User-Agent string in Python to reliably detect 1. Browser 2. Browser version 3. OS Or perhaps any helper library that does it
Werkzeug has user-agent parsing built-in. <http://werkzeug.pocoo.org/docs/0.10/utils/#module-werkzeug.useragents>
how to override the verbose name of a superclass model field in django
927,729
23
2009-05-29T19:30:57Z
928,774
45
2009-05-30T02:02:46Z
[ "python", "django", "inheritance", "django-models" ]
Let's say that I have a model Foo that inherits from SuperFoo: ``` class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo ``` In class Foo, I'd like to override the v...
A simple hack I have used is: ``` class SuperFoo(models.Model): name = models.CharField('name of SuperFoo instance', max_length=50) ... class Foo(SuperFoo): ... # do something that changes verbose_name of name field of SuperFoo Foo._meta.get_field('name').verbose_name = 'Whatever' ```
How to get the owner and group of a folder with Python on a Linux machine?
927,866
6
2009-05-29T20:04:54Z
927,890
22
2009-05-29T20:10:40Z
[ "python", "linux", "folder", "group", "owner" ]
How can I get the owner and group IDs of a directory using Python under Linux?
Use [`os.stat()`](http://docs.python.org/library/os.html#os.stat) to get the uid and gid of the file. Then, use [`pwd.getpwuid()`](http://docs.python.org/library/pwd.html#pwd.getpwuid) and [`grp.getgrgid()`](http://docs.python.org/library/grp.html#grp.getgrgid) to get the user and group names respectively. ``` import ...
Python Class Inheritance issue
927,985
16
2009-05-29T20:28:23Z
928,004
9
2009-05-29T20:32:36Z
[ "python", "class", "inheritance" ]
I'm playing with Python Class inheritance and ran into a problem where the inherited `__init__` is not being executed if called from the sub-class (code below) the result I get from Active Python is: --- ``` >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin...
You should explicitely call the superclass' init function: ``` class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = "abc123" ```
Python Class Inheritance issue
927,985
16
2009-05-29T20:28:23Z
928,013
25
2009-05-29T20:34:37Z
[ "python", "class", "inheritance" ]
I'm playing with Python Class inheritance and ran into a problem where the inherited `__init__` is not being executed if called from the sub-class (code below) the result I get from Active Python is: --- ``` >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin...
Three things: 1. You need to explicitly call the constructor. It isn't called for you automatically like in C++ 2. Use a new-style class inherited from object 3. With a new-style class, use the super() method available This will look like: ``` class Person(object): AnotherName = 'Sue Ann' def __init__(self):...
Python File Read + Write
928,918
4
2009-05-30T03:21:24Z
928,943
9
2009-05-30T03:38:16Z
[ "python", "file" ]
I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with `\t` delineated columns and one row per line. I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements. A...
Although this is easily doable, it does become easier with the [csv](http://docs.python.org/library/csv.html) module. ``` >>> import csv >>> reader = csv.reader(open('C:/www/stackoverflow.txt'), delimiter='\t') >>> for row in reader: ... print row ... ['1', 'John Smith', 'Developer', 'http://twiiter.com/johns', 'C...
Looping over a Python / IronPython Object Methods
928,990
3
2009-05-30T04:24:46Z
1,447,529
7
2009-09-19T02:17:33Z
[ "python", "reflection", "ironpython", "introspection", "python-datamodel" ]
What is the proper way to loop over a Python object's methods and call them? Given the object: ``` class SomeTest(): def something1(self): print "something 1" def something2(self): print "something 2" ```
You can use the inspect module to get class (or instance) members: ``` >>> class C(object): ... a = 'blah' ... def b(self): ... pass ... ... >>> c = C() >>> inspect.getmembers(c, inspect.ismethod) [('b', <bound method C.b of <__main__.C object at 0x100498250>>)] ``` getmembers() returns a list of...
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
63
2009-05-30T04:52:56Z
929,128
15
2009-05-30T06:02:24Z
[ "python", "django", "many-to-many" ]
In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1\_set or parentclass.childclass2\_set, but what if I don't know the name of the specific child class I want? Is there a way to get the related objects in the parent->...
In Python, given a ("new-style") class X, you can get its (direct) subclasses with `X.__subclasses__()`, which returns a list of class objects. (If you want "further descendants", you'll also have to call `__subclasses__` on each of the direct subclasses, etc etc -- if you need help on how to do that effectively in Pyt...
How do I access the child classes of an object in django without knowing the name of the child class?
929,029
63
2009-05-30T04:52:56Z
929,982
74
2009-05-30T15:47:56Z
[ "python", "django", "many-to-many" ]
In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1\_set or parentclass.childclass2\_set, but what if I don't know the name of the specific child class I want? Is there a way to get the related objects in the parent->...
(**Update**: For Django 1.2 and newer, which can follow select\_related queries across reverse OneToOneField relations (and thus down inheritance hierarchies), there's a better technique available which doesn't require the added `real_type` field on the parent model. It's available as [InheritanceManager](https://djang...
Convert a number range to another range, maintaining ratio
929,103
135
2009-05-30T05:48:22Z
929,104
39
2009-05-30T05:50:45Z
[ "python", "math" ]
I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point. I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value o...
That's a simple linear conversion. ``` new_value = ( (old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min ``` So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields: ``` old_value = 10000 old_min = -16000 old_max = 16000 new_min = 0 new_max = 100 new_value = (...
Convert a number range to another range, maintaining ratio
929,103
135
2009-05-30T05:48:22Z
929,107
244
2009-05-30T05:52:21Z
[ "python", "math" ]
I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point. I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value o...
``` NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin ``` Or a little more readable: ``` OldRange = (OldMax - OldMin) NewRange = (NewMax - NewMin) NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin ``` Or if you want to protect for the case where the old range is ...
Convert a number range to another range, maintaining ratio
929,103
135
2009-05-30T05:48:22Z
11,405,720
8
2012-07-10T02:11:52Z
[ "python", "math" ]
I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point. I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value o...
There is a condition, when all of the values that you are checking are the same, where @jerryjvl's code would return NaN. ``` if (OldMin != OldMax && NewMin != NewMax): return (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin else: return (NewMax + NewMin) / 2 ```
Convert a number range to another range, maintaining ratio
929,103
135
2009-05-30T05:48:22Z
15,537,393
13
2013-03-21T00:32:53Z
[ "python", "math" ]
I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point. I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value o...
Actually there are some cases that above answers would break. Such as wrongly input value, wrongly input range, negative input/output ranges. ``` def remap( x, oMin, oMax, nMin, nMax ): #range check if oMin == oMax: print "Warning: Zero input range" return None if nMin == nMax: pr...
Why does assigning to my global variables not work in Python?
929,777
34
2009-05-30T14:09:18Z
929,783
78
2009-05-30T14:12:14Z
[ "python", "global-variables", "scope" ]
I'm having terrible trouble trying to understand python scoping rules. With the following script: ``` a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA() ``` Gives the une...
Global variables are special. If you try to assign to a variable `a = value` inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a [`global` statement](http://docs.python.org/reference/simple%5Fstmts...
Why does assigning to my global variables not work in Python?
929,777
34
2009-05-30T14:09:18Z
929,793
10
2009-05-30T14:17:00Z
[ "python", "global-variables", "scope" ]
I'm having terrible trouble trying to understand python scoping rules. With the following script: ``` a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA() ``` Gives the une...
The trick to understanding this is that when you assign to a variable, using =, you also declare it as a local variable. So instead of changing the value of the global variable a, setA(value) actually sets a local variable (which happens to be called a) to the value passed in. This becomes more obvious if you try to p...
Two simple questions about python
929,887
2
2009-05-30T15:05:14Z
929,899
8
2009-05-30T15:11:00Z
[ "python", "file" ]
I have 2 simple questions about python: 1.How to get number of lines of a file in python? 2.How to locate the position in a file object to the last line easily?
lines are just data delimited by the newline char `'\n'`. 1) Since lines are variable length, you have to read the entire file to know where the newline chars are, so you can count how many lines: ``` count = 0 for line in open('myfile'): count += 1 print count, line # it will be the last line ``` 2) reading a c...
Two simple questions about python
929,887
2
2009-05-30T15:05:14Z
929,924
7
2009-05-30T15:21:11Z
[ "python", "file" ]
I have 2 simple questions about python: 1.How to get number of lines of a file in python? 2.How to locate the position in a file object to the last line easily?
Let's not forget ``` f = open("myfile.txt") lines = f.readlines() numlines = len(lines) lastline = lines[-1] ``` NOTE: this reads the whole file in memory as a list. Keep that in mind in the case that the file is very large.
Equivalent for Python's lambda functions in Java?
929,988
21
2009-05-30T15:49:17Z
930,012
9
2009-05-30T15:57:01Z
[ "java", "python", "function", "lambda" ]
Can someone please tell me if there is an equivalent for Python's lambda functions in Java?
I don't think there is an exact equivalent, however there are anonymous classes that are about as close as you can get. But still pretty different. Joel Spolsky wrote an article about how the students taught only Java are missing out on these beauties of functional style programming: [Can Your Programming Language Do T...
Equivalent for Python's lambda functions in Java?
929,988
21
2009-05-30T15:49:17Z
930,019
28
2009-05-30T15:58:12Z
[ "java", "python", "function", "lambda" ]
Can someone please tell me if there is an equivalent for Python's lambda functions in Java?
Unfortunately, there are no lambdas in Java. However, you can get *almost* the same effect (in a really ugly way) with anonymous classes: ``` interface MyLambda { void theFunc(); // here we define the interface for the function } public class Something { static void execute(MyLambda l) { l.theFunc(); ...
Python String Cleanup + Manipulation (Accented Characters)
930,303
5
2009-05-30T18:36:16Z
930,316
12
2009-05-30T18:47:38Z
[ "python", "regex", "unicode", "string" ]
I have a database full of names like: ``` John Smith Scott J. Holmes Dr. Kaplan Ray's Dog Levi's Adrian O'Brien Perry Sean Smyre Carie Burchfield-Thompson Björn Árnason ``` There are a few foreign names with accents in them that need to be converted to strings with non-accented characters. I'd like...
Take a look at this link [redacted] Here is the code from the page ``` def latin1_to_ascii (unicrap): """This replaces UNICODE Latin-1 characters with something equivalent in 7-bit ASCII. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 accented lett...
Getting the last element of a list in Python
930,397
826
2009-05-30T19:28:53Z
930,398
1,347
2009-05-30T19:29:55Z
[ "python", "list", "indexing" ]
In Python, how do you get the last element of a list?
`some_list[-1]` is the shortest and most Pythonic. In fact, you can do much more with this syntax. The `some_list[-n]` syntax gets the nth-to-last element. So `some_list[-1]` gets the last element, `some_list[-2]` gets the second to last, etc, all the way down to `some_list[-len(some_list)]`, which gives you the first...
Getting the last element of a list in Python
930,397
826
2009-05-30T19:28:53Z
930,759
49
2009-05-30T22:21:08Z
[ "python", "list", "indexing" ]
In Python, how do you get the last element of a list?
You can also do: ``` alist.pop() ``` It depends on what you want to do with your list because the `pop()` method will delete the last element.
Getting the last element of a list in Python
930,397
826
2009-05-30T19:28:53Z
4,139,773
116
2010-11-09T23:26:38Z
[ "python", "list", "indexing" ]
In Python, how do you get the last element of a list?
If your str() or list() objects might end up being empty as so: `astr = ''` or `alist = []`, then you might want to use `alist[-1:]` instead of `alist[-1]` for object "sameness". The significance of this is: ``` alist = [] alist[-1] # will generate an IndexError exception whereas alist[-1:] # will return an empty...
Getting the last element of a list in Python
930,397
826
2009-05-30T19:28:53Z
12,042,371
32
2012-08-20T17:41:54Z
[ "python", "list", "indexing" ]
In Python, how do you get the last element of a list?
The simplest way to display last element in python is ``` >>> list[-1:] # returns indexed value [3] >>> list[-1] # returns value 3 ``` there are many other method to achieve such a goal but these are short and sweet to use.
How to run one last function before getting killed in Python?
930,519
16
2009-05-30T20:22:53Z
930,537
28
2009-05-30T20:29:50Z
[ "python", "function", "interrupt", "quit" ]
Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc. Thanks for your help!
``` import time try: time.sleep(10) finally: print "clean up" clean up Traceback (most recent call last): File "<stdin>", line 2, in <module> KeyboardInterrupt ``` If you need to catch other OS level interrupts, look at the signal module: <http://docs.python.org/library/signal.html> ### Signal Example `...
How to run one last function before getting killed in Python?
930,519
16
2009-05-30T20:22:53Z
930,542
8
2009-05-30T20:32:14Z
[ "python", "function", "interrupt", "quit" ]
Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc. Thanks for your help!
I think that you could use the `atexit` module. With it, you can register a function which will be called at program termination. An example from here: <http://docs.python.org/library/atexit.html> ``` try: _count = int(open("/tmp/counter").read()) except IOError: _count = 0 def incrcounter(n): global _cou...
Python & parsing IRC messages
930,700
6
2009-05-30T21:51:58Z
930,706
16
2009-05-30T21:58:04Z
[ "python", "parsing", "irc" ]
What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example: ``` :[email protected] PRIVMSG #channel :Hi! ``` becomes this: ``` { "sender" : "[email protected]", "target" : "#channel", "message" : "Hi!" } ``` And so on...
Look at Twisted's implementation <http://twistedmatrix.com/> Unfortunately I'm out of time, maybe someone else can paste it here for you. ### Edit Well I'm back, and strangely no one has pasted it yet so here it is: <http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54> ``` def parsemsg(s)...
how to sort by a computed value in django
930,865
5
2009-05-30T23:34:20Z
930,894
16
2009-05-30T23:54:29Z
[ "python", "django", "web-applications", "sorting", "django-models" ]
Hey I want to sort objects based on a computed value in django... how do I do it? Here is an example User profile model based on stack overflow that explains my predicament: ``` class Profile(models.Model): user = models.ForeignKey(User) def get_reputation(): ... return reputation reputa...
Since your calculation code exists only within Python, you have to perform the sorting in Python as well: ``` sorted (Profile.objects.all (), key = lambda p: p.reputation) ```
assertEquals vs. assertEqual in python
930,995
105
2009-05-31T01:07:03Z
931,011
121
2009-05-31T01:17:47Z
[ "python", "unit-testing" ]
Is there a difference between `assertEquals` and `assertEqual` in the python `unittest.TestCase`? And if there is not, why are there two functions? Only for convenience?
Good question! Actually, in Python 2.6, both `assertEqual` and `assertEquals` are convenience aliases to `failUnlessEqual`. The source declares them thus: ``` # Synonyms for assertion methods assertEqual = assertEquals = failUnlessEqual ``` In [Python 3](http://docs.python.org/3/library/unittest.html#deprecated-al...
assertEquals vs. assertEqual in python
930,995
105
2009-05-31T01:07:03Z
21,993,198
21
2014-02-24T16:21:40Z
[ "python", "unit-testing" ]
Is there a difference between `assertEquals` and `assertEqual` in the python `unittest.TestCase`? And if there is not, why are there two functions? Only for convenience?
A 3.3 update: From [26.3.7.1.1. Deprecated aliases](http://docs.python.org/3.3/library/unittest.html#deprecated-aliases) : > For historical reasons, some of the TestCase methods had one or more aliases that are now deprecated. The following table lists the correct names along with their deprecated aliases: ``` Method...
Reverse a string in Python
931,092
751
2009-05-31T02:10:10Z
931,095
1,576
2009-05-31T02:11:46Z
[ "python", "string" ]
There is no built in `reverse` function in Python's `str` object. What is the best way of implementing this? If supplying a very concise answer, please elaborate on it's efficiency. Is the `str` converted to a different object, etc.
How about: ``` >>> 'hello world'[::-1] 'dlrow olleh' ``` This is [extended slice](http://docs.python.org/2/whatsnew/2.3.html#extended-slices) syntax. It works by doing `[begin:end:step]` - by leaving begin and end off and specifying a step of -1, it reverses a string.
Reverse a string in Python
931,092
751
2009-05-31T02:10:10Z
931,099
155
2009-05-31T02:13:54Z
[ "python", "string" ]
There is no built in `reverse` function in Python's `str` object. What is the best way of implementing this? If supplying a very concise answer, please elaborate on it's efficiency. Is the `str` converted to a different object, etc.
@Paolo's `s[::-1]` is fastest; a slower approach (maybe more readable, but that's debatable) is `''.join(reversed(s))`.
Reverse a string in Python
931,092
751
2009-05-31T02:10:10Z
27,843,760
51
2015-01-08T15:32:55Z
[ "python", "string" ]
There is no built in `reverse` function in Python's `str` object. What is the best way of implementing this? If supplying a very concise answer, please elaborate on it's efficiency. Is the `str` converted to a different object, etc.
> # What is the best way of implementing a reverse function for strings? > > There is no built-in reverse function in Python's str object. In my long illustrious career of being a programmer, I have never seen a practical need to reverse a string. So congratulations, you must be learning Python. There's a couple of t...
Reverse a string in Python
931,092
751
2009-05-31T02:10:10Z
33,457,266
12
2015-10-31T22:24:14Z
[ "python", "string" ]
There is no built in `reverse` function in Python's `str` object. What is the best way of implementing this? If supplying a very concise answer, please elaborate on it's efficiency. Is the `str` converted to a different object, etc.
## Quick Answer (TL;DR) ### Example ``` ### example01 ------------------- mystring = 'coup_ate_grouping' backwards = mystring[::-1] print backwards ### ... or even ... mystring = 'coup_ate_grouping'[::-1] print mystring ### result01 ------------------- ''' gnipuorg_eta_puoc ''' ``` ## Detailed Answer ### ...
Getting friends within a specified degree of separation
931,323
8
2009-05-31T05:00:20Z
931,354
12
2009-05-31T05:13:07Z
[ "python", "recursion" ]
all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and ...
``` friendList = friendList.append(self) ``` This sets `friendList` to `None`, unconditionally, as that's the invariable return value of any list's `append` method -- so, fix *that* weirdness first...!-) Once you've fixed that, you still need to fix the function so that it always ends with `return` of something -- "f...
Is there a Python equivalent to the PHP function htmlspecialchars()?
931,423
13
2009-05-31T05:58:44Z
931,445
12
2009-05-31T06:12:45Z
[ "php", "python", "html-entities", "htmlspecialchars" ]
Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().
Closest thing I know about is [cgi.escape](http://docs.python.org/library/cgi.html#cgi.escape).
Replace __str__ method on list object in Python
931,699
8
2009-05-31T09:06:52Z
931,822
7
2009-05-31T10:37:55Z
[ "python" ]
This seems like it should be simple: I want a `list` like any other `list`, except it has a different `.__str__` method. 1. Trying to set `object.__str__ = foo` results in a read-only error 2. Trying to subclass `list` means you need some way to convert an existing `list` to an instance of the subclass. This requires...
This solution works without a wrapper. And works if you join two lists by add. Any operation that modify the list itself will work as expected. Only functions that return a copy of the list like: sorted, reveresed will return the native python list which is fine. sort and reverse on the other hand operate on the list i...
Inaccurate Logarithm in Python
931,995
7
2009-05-31T12:48:26Z
932,003
43
2009-05-31T12:55:01Z
[ "python", "math", "floating-point" ]
I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2\*\*31, 2) it returned 31.000000000000004, which struck me as a bit odd. I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2\*\*31) / log10(...
This is to be expected with computer arithmetic. It is following particular rules, such as [IEEE 754](http://en.wikipedia.org/wiki/IEEE%5F754), that probably don't match the math you learned in school. If this *actually* matters, use Python's [decimal type](http://docs.python.org/library/decimal.html). Example: ``` ...
Inaccurate Logarithm in Python
931,995
7
2009-05-31T12:48:26Z
932,007
17
2009-05-31T12:58:09Z
[ "python", "math", "floating-point" ]
I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2\*\*31, 2) it returned 31.000000000000004, which struck me as a bit odd. I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2\*\*31) / log10(...
*Always* assume that floating point operations will have some error in them and check for equality taking that error into account (either a percentage value like 0.00001% or a fixed value like 0.00000000001). This inaccuracy is a given since not all decimal numbers can be represented in binary with a fixed number of bi...
Inaccurate Logarithm in Python
931,995
7
2009-05-31T12:48:26Z
932,095
19
2009-05-31T14:08:16Z
[ "python", "math", "floating-point" ]
I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2\*\*31, 2) it returned 31.000000000000004, which struck me as a bit odd. I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2\*\*31) / log10(...
You should read "What Every Computer Scientist Should Know About Floating-Point Arithmetic". <http://docs.sun.com/source/806-3568/ncg_goldberg.html>
Building a minimal plugin architecture in Python
932,069
129
2009-05-31T13:46:41Z
932,072
114
2009-05-31T13:51:05Z
[ "python", "architecture", "plugins" ]
I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something **extremely lightweight**. Most scripts, or plugins, are not going to be dev...
Mine is, basically, a directory called "plugins" which the main app can poll and then use [imp.load\_module](https://docs.python.org/library/imp.html#imp.load_module) to pick up files, look for a well-known entry point possibly with module-level config params, and go from there. I use file-monitoring stuff for a certai...
Building a minimal plugin architecture in Python
932,069
129
2009-05-31T13:46:41Z
932,078
29
2009-05-31T13:54:12Z
[ "python", "architecture", "plugins" ]
I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something **extremely lightweight**. Most scripts, or plugins, are not going to be dev...
Have a look at [at this overview over existing plugin frameworks / libraries](http://wehart.blogspot.com/2009/01/python-plugin-frameworks.html), it is a good starting point. I quite like [yapsy](http://yapsy.sourceforge.net/), but it depends on your use-case.
Building a minimal plugin architecture in Python
932,069
129
2009-05-31T13:46:41Z
932,306
21
2009-05-31T15:54:28Z
[ "python", "architecture", "plugins" ]
I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something **extremely lightweight**. Most scripts, or plugins, are not going to be dev...
While that question is really interesting, I think it's fairly hard to answer, without more details. What sort of application is this? Does it have a GUI? Is it a command-line tool? A set of scripts? A program with an unique entry point, etc... Given the little information I have, I will answer in a very generic manne...
Building a minimal plugin architecture in Python
932,069
129
2009-05-31T13:46:41Z
932,564
10
2009-05-31T18:05:31Z
[ "python", "architecture", "plugins" ]
I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something **extremely lightweight**. Most scripts, or plugins, are not going to be dev...
I am a retired biologist who dealt with digital micrograqphs and found himself having to write an image processing and analysis package (not technically a library) to run on an SGi machine. I wrote the code in C and used Tcl for the scripting language. The GUI, such as it was, was done using Tk. The commands that appea...
Building a minimal plugin architecture in Python
932,069
129
2009-05-31T13:46:41Z
933,245
38
2009-06-01T01:11:18Z
[ "python", "architecture", "plugins" ]
I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something **extremely lightweight**. Most scripts, or plugins, are not going to be dev...
`module_example.py`: ``` def plugin_main(*args, **kwargs): print args, kwargs ``` `loader.py`: ``` def load_plugin(name): mod = __import__("module_%s" % name) return mod def call_plugin(name, *args, **kwargs): plugin = load_plugin(name) plugin.plugin_main(*args, **kwargs) call_plugin("example",...
Building a minimal plugin architecture in Python
932,069
129
2009-05-31T13:46:41Z
2,442,096
10
2010-03-14T12:14:17Z
[ "python", "architecture", "plugins" ]
I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something **extremely lightweight**. Most scripts, or plugins, are not going to be dev...
[Marty Allchin's simple plugin framework](http://martyalchin.com/2008/jan/10/simple-plugin-framework/) is the base I use for my own needs. I really recommand to take a look at it, I think it is really a good start if you want something simple and easily hackable. You can find it also [as a Django Snippets](http://www.d...
Python: defining my own operators?
932,328
33
2009-05-31T16:01:39Z
932,333
27
2009-05-31T16:03:03Z
[ "python", "operators" ]
I would like to define my own operator. Does python support such a thing?
no, python comes with a predefined, yet overridable, [set of operators](http://docs.python.org/library/operator.html#mapping-operators-to-functions).
Python: defining my own operators?
932,328
33
2009-05-31T16:01:39Z
932,347
22
2009-05-31T16:06:16Z
[ "python", "operators" ]
I would like to define my own operator. Does python support such a thing?
No, you can't create new operators. However, if you are just evaluating expressions, you could process the string yourself and calculate the results of the new operators.
Python: defining my own operators?
932,328
33
2009-05-31T16:01:39Z
932,385
7
2009-05-31T16:27:43Z
[ "python", "operators" ]
I would like to define my own operator. Does python support such a thing?
If you intend to apply the operation on a particular class of objects, you could just override the operator that matches your function the closest... for instance, overriding `__eq__()` will override the `==` operator to return whatever you want. This works for almost all the operators.
Python: defining my own operators?
932,328
33
2009-05-31T16:01:39Z
932,580
107
2009-05-31T18:18:32Z
[ "python", "operators" ]
I would like to define my own operator. Does python support such a thing?
While technically you cannot define new operators in Python, this [clever hack](http://code.activestate.com/recipes/384122/) works around this limitation. It allows you to define infix operators like this: ``` # simple multiplication x=Infix(lambda x,y: x*y) print 2 |x| 4 # => 8 # class checking isa=Infix(lambda x,y:...
How can I get the next string, in alphanumeric ordering, in Python?
932,506
5
2009-05-31T17:33:15Z
932,536
12
2009-05-31T17:46:17Z
[ "python", "string" ]
I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering). ``` f("aaa")="aab" f("aaZ")="aba" ``` And so on. Is there a function for this in one of the modules already?
I don't think there's a built-in function to do this. The following should work: ``` def next_string(s): strip_zs = s.rstrip('z') if strip_zs: return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs)) else: return 'a' * (len(s) + 1) ``` Explanation: you find the la...
How to parse angular values using regular expressions
932,796
3
2009-05-31T20:33:01Z
932,812
8
2009-05-31T20:41:01Z
[ "python", "regex", "angle" ]
I have very little experience using regular expressions and I need to parse an angle value expressed as bearings, using regular expressions, example: "N45°20'15.3"E" Which represents: 45 degrees, 20 minutes with 15.3 seconds, located at the NE quadrant. The restrictions are: * The first character can be "N" or "S"...
Try this regular expression: ``` ^([NS])([0-5]?\d)°([0-5]?\d)'(?:([0-5]?\d)(?:\.\d)?")?([EW])$ ``` It matches any string that … * **`^([NS])`**   begins with `N` or `S` * **`([0-5]?\d)°`**   followed by a degree value, either a single digit between `0` and `9` (`\d`) or two digits with the first bewteen `0...
retrieving a variable's name in python at runtime?
932,818
26
2009-05-31T20:44:07Z
932,829
10
2009-05-31T20:48:26Z
[ "python" ]
is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ? e.g. ``` >>> vari = 15 >>> print vari.~~name~~() 'vari' ``` note: i'm talking about plain data-type variables (int, str, list...)
Variable names persist in the compiled code (that's how e.g. the `dir` built-in can work), but the mapping that's there goes from name to value, not vice versa. So if there are several variables all worth, for example, `23`, there's no way to tell them from each other base only on the value `23` .
retrieving a variable's name in python at runtime?
932,818
26
2009-05-31T20:44:07Z
932,835
28
2009-05-31T20:52:27Z
[ "python" ]
is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ? e.g. ``` >>> vari = 15 >>> print vari.~~name~~() 'vari' ``` note: i'm talking about plain data-type variables (int, str, list...)
Variable names don't get forgotten, you can access variables (and look which variables you have) by introspection, e.g. ``` >>> i = 1 >>> locals()["i"] 1 ``` However, because there are no pointers in Python, there's no way to reference a variable without actually writing its name. So if you wanted to print a variable...
Python module globals versus __init__ globals
933,042
4
2009-05-31T22:44:09Z
933,084
8
2009-05-31T23:12:13Z
[ "python", "global" ]
Apologies, somewhat confused Python newbie question. Let's say I have a module called `animals.py`....... ``` globvar = 1 class dog: def bark(self): print globvar class cat: def miaow(self): print globvar ``` What is the difference between this and ``` class dog: def __init__(self): glo...
`global` doesn't create a new variable, it just states that this name should refer to a global variable instead of a local one. Usually assignments to variables in a function/class/... refer to local variables. For example take a function like this: ``` def increment(n) # this creates a new local m m = n+1 retur...
Generic many-to-many relationships
933,092
34
2009-05-31T23:18:01Z
937,385
45
2009-06-02T00:10:47Z
[ "python", "django", "generics", "django-models", "many-to-many" ]
I'm trying to create a messaging system where a message's sender and recipients can be generic entities. This seems fine for the sender, where there is only object to reference (GenericForeignKey) but I can't figure out how to go about this for the recipients (GenericManyToManyKey ??) Below is a simplified example. Pe...
You can implement this using generic relationships by manually creating the junction table between message and recipient: ``` from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType class Client(models.Model): city = models.CharField(...
Django-like abstract database API for non-Django projects
933,232
5
2009-06-01T00:58:06Z
933,235
16
2009-06-01T01:00:11Z
[ "python", "database", "django", "orm", "django-models" ]
I love the abstract database API that comes with Django, I was wondering if I could use this (or something similar) to model, access, and manage my (postgres) database for my non-Django Python projects.
What you're looking for is an [object-relational mapper](http://en.wikipedia.org/wiki/Object-relational%5Fmapping) (ORM). Django has its own, built-in. To use Django's ORM by itself: * [Using the Django ORM as a standalone component](http://jystewart.net/process/2008/02/using-the-django-orm-as-a-standalone-component/...
Django-like abstract database API for non-Django projects
933,232
5
2009-06-01T00:58:06Z
933,238
7
2009-06-01T01:01:55Z
[ "python", "database", "django", "orm", "django-models" ]
I love the abstract database API that comes with Django, I was wondering if I could use this (or something similar) to model, access, and manage my (postgres) database for my non-Django Python projects.
Popular stand-alone ORMs for Python: * [SQLAlchemy](http://www.sqlalchemy.org/) * [SQLObject](http://www.sqlobject.org/) * [Storm](https://storm.canonical.com/) They all support MySQL and PostgreSQL (among others).
Python Regex Search And Replace
933,824
4
2009-06-01T07:15:04Z
933,826
12
2009-06-01T07:16:50Z
[ "python", "regex", "string", "markdown" ]
I'm not new to Python but a complete newbie with regular expressions (on my to do list) I am trying to use python re to convert a string such as ``` [Hollywood Holt](http://www.hollywoodholt.com) ``` to ``` <a href="http://www.hollywoodholt.com">Hollywood Holt</a> ``` and a string like ``` *Hello world* ``` to ...
Why are you bothering to use a regex? Your content is Markdown, why not simply take the string and run it through the markdown module? First, make sure Markdown is installed. It has a dependancy on ElementTree so easy\_install the two of them as follows. If you're running Windows, you can use the [Windows installer](h...
Python module for editing text in CLI
933,941
2
2009-06-01T08:10:22Z
933,965
7
2009-06-01T08:24:56Z
[ "python", "text-editor", "command-line-interface" ]
Is there some python module or commands that would allow me to make my python program enter a CLI text editor, populate the editor with some text, and when it exits, get out the text into some variable? At the moment I have users enter stuff in using raw\_input(), but I would like something a bit more powerful than th...
Well, you can launch the user's $EDITOR with subprocess, editing a temporary file: ``` import tempfile import subprocess import os t = tempfile.NamedTemporaryFile(delete=False) try: editor = os.environ['EDITOR'] except KeyError: editor = 'nano' subprocess.call([editor, t.name]) ```
Write to UTF-8 file in Python
934,160
113
2009-06-01T09:42:23Z
934,173
168
2009-06-01T09:46:58Z
[ "python", "utf-8", "byte-order-mark" ]
I'm really confused with the `codecs.open function`. When I do: ``` file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() ``` It gives me the error > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position > 0: ordinal not in range(128) If I do: ``` file = open("temp", "w")...
Disclaimer: I'm not a Python programmer. I believe the problem is that [`codecs.BOM_UTF8`](https://docs.python.org/library/codecs.html#codecs.BOM_UTF8) is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded t...
Write to UTF-8 file in Python
934,160
113
2009-06-01T09:42:23Z
934,203
129
2009-06-01T09:58:14Z
[ "python", "utf-8", "byte-order-mark" ]
I'm really confused with the `codecs.open function`. When I do: ``` file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() ``` It gives me the error > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position > 0: ordinal not in range(128) If I do: ``` file = open("temp", "w")...
Read the following: <http://docs.python.org/library/codecs.html#module-encodings.utf_8_sig> Do this ``` with codecs.open("test_output", "w", "utf-8-sig") as temp: temp.write("hi mom\n") temp.write(u"This has ♭") ``` The resulting file is UTF-8 with the expected BOM.
Write to UTF-8 file in Python
934,160
113
2009-06-01T09:42:23Z
934,228
11
2009-06-01T10:12:39Z
[ "python", "utf-8", "byte-order-mark" ]
I'm really confused with the `codecs.open function`. When I do: ``` file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() ``` It gives me the error > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position > 0: ordinal not in range(128) If I do: ``` file = open("temp", "w")...
@S-Lott gives the right procedure, but expanding on the *Unicode* issues, the *Python* interpreter can provide more insights. Jon Skeet is right (unusual) about the [`codecs`](http://docs.python.org/library/codecs.html#codecs.BOM) module - it contains byte strings: ``` >>> import codecs >>> codecs.BOM '\xff\xfe' >>> ...
Java equivalent of function mapping in Python
934,509
7
2009-06-01T11:48:37Z
934,532
14
2009-06-01T11:58:09Z
[ "java", "python", "function" ]
In python, if I have a few functions that I would like to call based on an input, i can do this: ``` lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() ``` That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup. Ho...
Java doesn't have first-class methods, so the [command pattern](http://en.wikipedia.org/wiki/Command%5Fpattern) is your friend... disclamer: code not tested! ``` public interface Command { void invoke(); } Map<String, Command> commands = new HashMap<String, Command>(); commands.put("function1", new Command() {...
How do I find out if a numpy array contains integers?
934,616
24
2009-06-01T12:27:46Z
934,652
27
2009-06-01T12:39:12Z
[ "python", "numpy" ]
I know there is a simple solution to this but can't seem to find it at the moment. Given a numpy array, I need to know if the array contains integers. Checking the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...).
Found it in the [numpy book](http://templatelab.com/numpybook/)! Page 23: > The other types in the hierarchy define particular categories of types. > These categories can be useful for testing whether or not the object > returned by self.dtype.type is of a particular class (using issubclass). ``` issubclass(n.dtype(...
How do I find out if a numpy array contains integers?
934,616
24
2009-06-01T12:27:46Z
7,236,784
9
2011-08-29T22:34:52Z
[ "python", "numpy" ]
I know there is a simple solution to this but can't seem to find it at the moment. Given a numpy array, I need to know if the array contains integers. Checking the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...).
Checking for an integer type does not work for floats that are integers, e.g. `4.` Better solution is `np.equal(np.mod(x, 1), 0)`, as in: ``` >>> import numpy as np >>> def isinteger(x): ... return np.equal(np.mod(x, 1), 0) ... >>> foo = np.array([0., 1.5, 1.]) >>> bar = np.array([-5, 1, 2, 3, -4, -2, 0, 1, ...
Using easy_install inside a python script?
935,111
15
2009-06-01T14:39:05Z
935,219
17
2009-06-01T15:05:46Z
[ "python", "setuptools" ]
easy\_install python extension allows to install python eggs from console like: ``` easy_install py2app ``` But is it possible to access easy\_install functionality inside a python script? I means, without calling os.system( "easy\_install py2app" ) but instead importing easy\_install as a python module and using it'...
When I look at the setup tools source, it looks like you can try the following. ``` from setuptools.command import easy_install easy_install.main( ["-U","py2app"] ) ```
Cast a class instance to a subclass
935,448
3
2009-06-01T15:55:54Z
936,498
7
2009-06-01T20:03:39Z
[ "python", "class", "subclass", "boto" ]
I'm using [boto](http://code.google.com/p/boto/) to manage some [EC2](http://aws.amazon.com/ec2/) instances. It provides an Instance class. I'd like to subclass it to meet my particular needs. Since boto provides a query interface to get your instances, I need something to convert between classes. This solution seems t...
I wouldn't subclass and cast. I don't think casting is ever a good policy. Instead, consider a Wrapper or Façade. ``` class MyThing( object ): def __init__( self, theInstance ): self.ec2_instance = theInstance ``` Now, you can subclass `MyThing` as much as you want and you shouldn't need to be casting y...
How do I pass an exception between threads in python
936,556
7
2009-06-01T20:17:57Z
936,675
11
2009-06-01T20:41:14Z
[ "python", "multithreading", "exception" ]
I need to pass exceptions across a thread boundary. I'm using python embedded in a non thread safe app which has one thread safe call, post\_event(callable), which calls callable from its main thread. I am running a pygtk gui in a seperate thread, so when a button is clicked I post an event with post\_event, and wait...
> #what do I do here? How do I store the exception? Use `sys.exc_info()[:2]`, see [this wiki](http://pyref.infogami.com/sys.exc%5Finfo) Best way to communicate among threads is [Queue](http://docs.python.org/library/queue.html). Have the main thread instantiate a `Queue.Queue` instance and pass it to subthreads; when...
Creating connection between two computers in python
936,625
9
2009-06-01T20:32:24Z
936,656
10
2009-06-01T20:36:38Z
[ "python", "networking" ]
The question: How do I create a python application that can connect and send packets over the internet to another computer running the same application? Is there any existing code/library I could use? The background: I am pretty new to programming (HS senior). I've created a lot of simple things in python but I've rec...
[Twisted](http://twistedmatrix.com/) is a python event-driven networking engine licensed under MIT. Means that a single machine can communicate with one or more other machines, while doing other things between data being received and sent, all asynchronously, and running a in a single thread/process. It supports many ...