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
Windows is not passing command line arguments to Python programs executed from the shell
2,640,971
62
2010-04-14T20:56:11Z
2,641,185
63
2010-04-14T21:28:12Z
[ "python", "windows", "registry", "command-line-arguments", "file-association" ]
I'm having trouble getting command line arguments passed to Python programs if I try to execute them directly as executable commands from a Windows command shell. For example, if I have this program (test.py): ``` import sys print "Args: %r" % sys.argv[1:] ``` And execute: ``` >test foo Args: [] ``` as compared to:...
I think I solved this. For some reason there is a SECOND place in the registry (besides that shown by the file associations stored in HKEY\_CLASSES\_ROOT\Python.File\shell\open\command): ``` [HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command] @="\"C:\\Python25\\python.exe\" \"%1\" %*" ``` This seems to be ...
Windows is not passing command line arguments to Python programs executed from the shell
2,640,971
62
2010-04-14T20:56:11Z
3,936,570
12
2010-10-14T18:57:52Z
[ "python", "windows", "registry", "command-line-arguments", "file-association" ]
I'm having trouble getting command line arguments passed to Python programs if I try to execute them directly as executable commands from a Windows command shell. For example, if I have this program (test.py): ``` import sys print "Args: %r" % sys.argv[1:] ``` And execute: ``` >test foo Args: [] ``` as compared to:...
My setting was under yet another registry key, `HKEY_CLASSES_ROOT\py_auto_file`. The other keys mentioned also existed, but Windows was using this one for some reason.
Windows is not passing command line arguments to Python programs executed from the shell
2,640,971
62
2010-04-14T20:56:11Z
15,993,667
7
2013-04-13T22:32:02Z
[ "python", "windows", "registry", "command-line-arguments", "file-association" ]
I'm having trouble getting command line arguments passed to Python programs if I try to execute them directly as executable commands from a Windows command shell. For example, if I have this program (test.py): ``` import sys print "Args: %r" % sys.argv[1:] ``` And execute: ``` >test foo Args: [] ``` as compared to:...
For Python 3.3 on Windows 7, my setting was under another registry key; the key I changed to make the arguments get passed was `HKEY_USERS\S-1-5-21-3922133726-554333396-2662258059-1000_Classes\py_auto_file\shell\open\command` It was `"C:\Python\Python33\python.exe" "%1"`. I only appended `%*` to it. The key's value i...
Need help running Python app as service in Ubuntu with Upstart
2,641,136
12
2010-04-14T21:21:37Z
2,646,616
11
2010-04-15T15:21:47Z
[ "python", "ubuntu", "upstart" ]
I have written a logging application in Python that is meant to start at boot, but I've been unable to start the app with [Ubuntu's Upstart init daemon](http://upstart.ubuntu.com/). When run from the terminal with **sudo /usr/local/greeenlog/main.pyw**, the application works perfectly. Here is what I've tried for the U...
Thanks to unutbu's help, I have been able to correct my job. Apparently, these are the only environment variables that Upstart sets (retrieved in Python with **os.environ**): ``` {'TERM': 'linux', 'PWD': '/', 'UPSTART_INSTANCE': '', 'UPSTART_JOB': 'greeenlog', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin...
Building up an array in numpy/scipy by iteration in Python?
2,641,691
14
2010-04-14T23:13:33Z
2,641,781
11
2010-04-14T23:37:23Z
[ "python", "numpy", "scipy" ]
Often, I am building an array by iterating through some data, e.g.: ``` my_array = [] for n in range(1000): # do operation, get value my_array.append(value) # cast to array my_array = array(my_array) ``` I find that I have to first build a list and then cast it (using "array") to an array. Is there a way around ...
The recommended way to do this is to preallocate before the loop and use slicing and indexing to insert ``` my_array = numpy.zeros(1,1000) for i in xrange(1000): #for 1D array my_array[i] = functionToGetValue(i) #OR to fill an entire row my_array[i:] = functionToGetValue(i) #or to fill an entire co...
Building up an array in numpy/scipy by iteration in Python?
2,641,691
14
2010-04-14T23:13:33Z
2,648,925
21
2010-04-15T20:57:31Z
[ "python", "numpy", "scipy" ]
Often, I am building an array by iterating through some data, e.g.: ``` my_array = [] for n in range(1000): # do operation, get value my_array.append(value) # cast to array my_array = array(my_array) ``` I find that I have to first build a list and then cast it (using "array") to an array. Is there a way around ...
NumPy provides a 'fromiter' method: ``` def myfunc(n): for i in range(n): yield i**2 np.fromiter(myfunc(5), dtype=int) ``` which yields ``` array([ 0, 1, 4, 9, 16]) ```
get_or_create generic relations in Django & python debugging in general
2,641,780
4
2010-04-14T23:36:43Z
2,641,794
7
2010-04-14T23:40:44Z
[ "python", "django", "debugging", "generic-relationship" ]
I ran the code to create the generically related objects from this demo: <http://www.djangoproject.com/documentation/models/generic_relations/> Everything is good intially: ``` >>> bacon.tags.create(tag="fatty") <TaggedItem: fatty> >>> tag, newtag = bacon.tags.get_or_create(tag="fatty") >>> tag <TaggedItem: fatty> >>...
[`ContentType.objects.get_for_model()`](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#django.contrib.contenttypes.models.ContentTypeManager.get_for_model) will give you the appropriate `ContentType` for a model. Pass the returned object as `content_type`. And don't worry too much about "getting it" wh...
Using python to write text files with DOS line endings on linux
2,642,036
10
2010-04-15T00:55:13Z
2,642,121
43
2010-04-15T01:15:32Z
[ "python", "windows", "newline" ]
I want to write text files with DOS/Windows line endings '\r\n' using python running on Linux. It seems to me that there must be a better way than manually putting a '\r\n' at the end of every line or using a line ending conversion utility. Ideally I would like to be able to do something like assign to os.linesep the s...
For Python 2.6 and later, the [open](http://docs.python.org/library/io.html#io.open) function in the `io` module has an optional newline parameter that lets you specify which newlines you want to use. For example: ``` import io with io.open('tmpfile', 'w', newline='\r\n') as f: f.write(u'foo\nbar\nbaz\n') ``` wi...
Does Python doctest remove the need for unit-tests?
2,642,282
10
2010-04-15T01:57:50Z
2,642,744
16
2010-04-15T04:33:42Z
[ "python", "unit-testing", "doctest" ]
A fellow developer on a project I am on believes that doctests are as good as unit-tests, and that if a piece of code is doctested, it does not need to be unit-tested. I do not believe this to be the case. Can anyone provide some solid, ideally cited, examples either for or against the argument that doctests replace th...
I (ab)used `doctest` in lieu of `unittest`, back when I started my [gmpy](http://code.google.com/p/gmpy/) project many years ago -- you can browse its sources and see that all the functionality is thoroughly tested with doctests (the functionality's supplied by a C-coded Python extension, and last time I instrumented i...
Google App Engine: How to disable cache on 'static' files, or make cache smart
2,642,432
10
2010-04-15T02:46:57Z
2,642,441
10
2010-04-15T02:50:49Z
[ "python", "google-app-engine" ]
I'm using the app engine locally, and sometimes the JS files are being cached between page refreshes, and it drives me crazy because I don't know if there's a bug in the javascript code I'm trying to write, or if the cache is acting up. How do I completely disable cache for \*.js files? Or maybe the question is, how t...
Based on [the docs](http://code.google.com/appengine/docs/python/config/appconfig.html#Static_File_Handlers), you can specify an app-wide cache expiration duration: > Unless told otherwise, web browsers retain files they load from a website for a limited period of time. You can define a global default cache period for...
Google App Engine: How to disable cache on 'static' files, or make cache smart
2,642,432
10
2010-04-15T02:46:57Z
2,642,516
11
2010-04-15T03:18:16Z
[ "python", "google-app-engine" ]
I'm using the app engine locally, and sometimes the JS files are being cached between page refreshes, and it drives me crazy because I don't know if there's a bug in the javascript code I'm trying to write, or if the cache is acting up. How do I completely disable cache for \*.js files? Or maybe the question is, how t...
A common practice used by the major sites is to cache documents forever but include a unique identifier based on the release version or date into the url for the .js or .css call. For example: ``` <script type="text/javascript" src="static/util.js?version=20100310"></script> ``` This way you get optimum caching as we...
What is `related_name` used for in Django?
2,642,613
119
2010-04-15T03:51:43Z
2,642,645
172
2010-04-15T04:02:01Z
[ "python", "django", "many-to-many", "foreign-key-relationship" ]
What is the `related_name` argument useful for on `ManyToManyField` and `ForeignKey` fields? For example, given the following code, what is the effect of `related_name='maps'`? ``` class Map(db.Model): members = models.ManyToManyField(User, related_name='maps', verbose_name=_('...
The `related_name` attribute specifies the name of the reverse relation from the `User` model back to your model. If you don't specify a `related_name`, Django automatically creates one using the name of your model with the suffix `_set`, for instance `User.map_set.all()`. If you *do* specify, e.g. `related_name=maps...
What is `related_name` used for in Django?
2,642,613
119
2010-04-15T03:51:43Z
36,916,782
9
2016-04-28T13:52:42Z
[ "python", "django", "many-to-many", "foreign-key-relationship" ]
What is the `related_name` argument useful for on `ManyToManyField` and `ForeignKey` fields? For example, given the following code, what is the effect of `related_name='maps'`? ``` class Map(db.Model): members = models.ManyToManyField(User, related_name='maps', verbose_name=_('...
To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material ``` @with_author class BOM(models.Model): name = models.CharField(max_length=200,null=True, blank=True) description = models.TextField(null=True, blank=Tru...
google app engine error ,and i can't open it now.(python)
2,643,081
6
2010-04-15T06:03:31Z
3,192,316
10
2010-07-07T06:14:31Z
[ "python", "google-app-engine" ]
the error is : --- ## Errors occurred See the logfile 'D:\Program Files\Google\google\_appengine\launcher\GoogleAppEngineLauncher.exe.log' for details ![alt text](http://omploader.org/vNDVuZA) why ? thanks
Find your home directory (open command prompt, run "set home" to see what it is). Go to that directory and delete the directory called "Google" more here: <http://code.google.com/p/googleappengine/issues/detail?id=2299>
Is there a production ready web application framework in Python?
2,643,321
13
2010-04-15T07:07:04Z
2,643,330
27
2010-04-15T07:11:01Z
[ "python", "web-applications" ]
I heard lots of good opinions about Python language. They say it's mature, expressive etc... I'm looking for production-ready enterprise application frameworks in Python. By "production ready" I mean : * supports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..) * control...
[Django](http://www.djangoproject.com/) seems like the obvious choice. It is by far the most stable and developed framework, used by [several large corporations](http://www.djangosites.org/highest-rated/). Because it is a Python framework, it can generally use any Python module, as well as the many modules that have b...
Is there a production ready web application framework in Python?
2,643,321
13
2010-04-15T07:07:04Z
2,643,669
14
2010-04-15T08:14:22Z
[ "python", "web-applications" ]
I heard lots of good opinions about Python language. They say it's mature, expressive etc... I'm looking for production-ready enterprise application frameworks in Python. By "production ready" I mean : * supports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..) * control...
For the context, I work at a large private bank in Switzerland, writing Enterprise applications on the J2EE stack. There are plenty of "Production Ready" web frameworks in Python. And there are plenty of large Python-based websites out there. That said, I think Python is a poor choice for an Enterprisy application. I...
How to replace by regular expression to lowercase in python
2,643,737
4
2010-04-15T08:26:46Z
2,643,782
10
2010-04-15T08:35:05Z
[ "python", "regex" ]
I want to search key words (keys would be dynamic) and replace them in a certain format. For example: these data ``` keys = ["cat", "dog", "mouse"] text = "Cat dog cat cloud miracle DOG MouSE" ``` had to be converted to ``` converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)" `...
You can use a function to do the replacing: ``` pattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE) def format_term(term): return '[%s](%s)' % (term, term.lower()) converted_text = pattern.sub(lambda m: format_term(m.group(0)), text) ```
"UserWarning: Unbuilt egg for setuptools" - What does this actually mean?
2,643,835
6
2010-04-15T08:46:17Z
2,873,947
14
2010-05-20T13:07:52Z
[ "python", "setuptools", "pip", "distribute" ]
When I install things into a virtualenv using pip I often see the message "UserWarning: Unbuilt egg for setuptools". I always safely ignore it and go about my business and it doesn't seem to cause me any problems. But I've suddenly been smacked in the face with curiosity, and wondered if someone could explain what it ...
The answer and workaround in [this Ubuntu bug report](https://bugs.launchpad.net/ubuntu/+source/distribute/+bug/576434/comments/2) fixed this issue for me, where I was reading the same error while using interactive `trac-admin` command. Marius Gedminas, said: > Workaround: > > sudo rmdir /usr/lib/python2.6/dist-packa...
What is a good way to do countif in Python
2,643,850
19
2010-04-15T08:47:58Z
2,643,910
33
2010-04-15T08:55:06Z
[ "python" ]
I want to count how many members of an iterable meet a given condition. I'd like to do it in a way that is clear and simple and preferably reasonably optimal. My current best ideas are: ``` sum(meets_condition(x) for x in my_list) ``` and ``` len([x for x in my_list if meets_condition(x)]) ``` The first one being ...
The iterator based approach is just fine. There are some slight modifications that can emphasize the fact that you are counting: ``` sum(1 if meets_condition(x) else 0 for x in my_list) # or sum(1 for x in my_list if meets_condition(x)) ``` And as always, if the intent isn't apparent from the code, encapsulate it in...
AttributeError while adding colorbar in matplotlib
2,643,953
18
2010-04-15T09:03:04Z
2,644,255
11
2010-04-15T09:52:39Z
[ "python", "matplotlib" ]
The following code fails to run on Python 2.5.4: ``` from matplotlib import pylab as pl import numpy as np data = np.random.rand(6,6) fig = pl.figure(1) fig.clf() ax = fig.add_subplot(1,1,1) ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99) pl.colorbar() pl.show() ``` The error message is ``` C:\temp>p...
Note: I am using python 2.6.2. The same error was raised with your code and the following modification solved the problem. I read the following colorbar example: <http://matplotlib.sourceforge.net/examples/pylab_examples/colorbar_tick_labelling_demo.html> ``` from matplotlib import pylab as pl import numpy as np dat...
AttributeError while adding colorbar in matplotlib
2,643,953
18
2010-04-15T09:03:04Z
11,558,276
30
2012-07-19T09:55:37Z
[ "python", "matplotlib" ]
The following code fails to run on Python 2.5.4: ``` from matplotlib import pylab as pl import numpy as np data = np.random.rand(6,6) fig = pl.figure(1) fig.clf() ax = fig.add_subplot(1,1,1) ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99) pl.colorbar() pl.show() ``` The error message is ``` C:\temp>p...
(This is a very old question I know) The reason you are seeing this issue is because you have mixed the use of the state machine (matplotlib.pyplot) with the OO approach of adding images to an axes. The `plt.imshow` function differs from the `ax.imshow` method in just one subtly different way. The method `ax.imshow`: ...
ProgrammingError: (1146, "Table 'test_<DB>.<TABLE>' doesn't exist") when running unit test for Django
2,644,749
4
2010-04-15T11:20:30Z
13,761,701
9
2012-12-07T10:57:34Z
[ "python", "django", "unit-testing" ]
I'm running a unit test using the Django framework and get this error. Running the actual code does not have this problem, running the unit tests creates a test database on the fly so I suspect the issue lies there. The code that throws the error looks like this ``` member = Member.objects.get(email=email_address) `...
To rectify this problem generate all your table which were declared in the `settings.py` file in your project folder. You can find the in the `INSTALLED APPS` Block in the settings file. For that run this command: `manage.py syncdb` or `python manage.py syncdb` If this doesn't work then set the Environment variable ...
Is there any lib for python that will get me the synonyms of a word?
2,645,706
9
2010-04-15T13:37:44Z
2,645,764
11
2010-04-15T13:42:55Z
[ "python", "nlp", "synonym" ]
Is there any api/lib for python that will get me the synonyms of a word? For example if i have the word "house" it will return "building, domicile, mansion, etc..."
[NLTK](http://www.nltk.org/) and Wordnet can help: e.g., per [this article](http://www.randomhacks.net/articles/2009/12/28/experimenting-with-nltk), ``` from nltk.corpus import wordnet dog = wordnet.synset('dog.n.01') print(dog.lemma_names()) ``` prints: ``` ['dog', 'domestic_dog', 'Canis_familiaris'] ```
Check if something is a list
2,645,749
9
2010-04-15T13:41:12Z
2,645,814
12
2010-04-15T13:47:47Z
[ "python", "typechecking" ]
What is the easiest way to check if something is a list? A method `doSomething` has the parameters `a` and `b`. In the method, it will loop through the list `a` and do something. I'd like a way to make sure `a` is a `list`, before looping through - thus avoiding an error or the unfortunate circumstance of passing in a...
To enable more usecases, but still treat strings as scalars, don't check for a being a list, check that it isn't a string: ``` if not isinstance(a, basestring): ... ```
What is the fastest (to access) struct-like object in Python?
2,646,157
46
2010-04-15T14:29:29Z
2,648,186
29
2010-04-15T19:04:20Z
[ "python", "performance", "data-structures" ]
I'm optimizing some code whose main bottleneck is running through and accessing a very large list of struct-like objects. Currently I'm using namedtuples, for readability. But some quick benchmarking using 'timeit' shows that this is really the wrong way to go where performance is a factor: Named tuple with a, b, c: ...
One thing to bear in mind is that namedtuples are optimised for access as tuples. If you change your accessor to be `a[2]` instead of `a.c`, you'll see similar performance to the tuples. The reason is that the name accessors are effectively translating into calls to self[idx], so pay both the indexing *and* the name lo...
What is the fastest (to access) struct-like object in Python?
2,646,157
46
2010-04-15T14:29:29Z
26,636,844
18
2014-10-29T17:21:17Z
[ "python", "performance", "data-structures" ]
I'm optimizing some code whose main bottleneck is running through and accessing a very large list of struct-like objects. Currently I'm using namedtuples, for readability. But some quick benchmarking using 'timeit' shows that this is really the wrong way to go where performance is a factor: Named tuple with a, b, c: ...
This question is fairly old (internet-time), so I thought I'd try duplicating your test today, both with regular CPython (2.7.6), and with pypy (2.2.1) and see how the various methods compared. (I also added in an indexed lookup for the named tuple.) This is a bit of a micro-benchmark, so YMMV, but pypy seemed to spee...
Threads or background processes in Google App Engine (GAE)
2,646,961
4
2010-04-15T16:03:59Z
2,646,986
9
2010-04-15T16:08:01Z
[ "python", "google-app-engine", "multithreading" ]
I'm running a post, and need the request to be replied fast. So I wanted to put a worker running some operations in background and reply the request imidiatly. The worker is always finite in operations and executes in [0;1] second How can I do this? Is there any module that suports this in the google app engine api? ...
Yes. You want to use the [Task Queue API](http://code.google.com/appengine/docs/python/taskqueue/). It does exactly what you need.
Unique user ID in a Pylons web application
2,647,080
3
2010-04-15T16:19:43Z
2,647,587
8
2010-04-15T17:29:13Z
[ "python", "pylons", "cassandra", "uuid" ]
What is the best way to create a unique user ID in Python, using [UUID](http://docs.python.org/library/uuid.html)?
I'd go with uuid ``` from uuid import uuid4 def new_user_id(): return uuid4().hex ```
I need to speed up a function. Should I use cython, ctypes, or something else?
2,647,105
5
2010-04-15T16:23:08Z
2,648,095
9
2010-04-15T18:47:53Z
[ "python", "ctypes", "cython" ]
I'm having a lot of fun learning Python by writing a genetic programming type of application. I've had some great advice from Torsten Marek, Paul Hankin and Alex Martelli on this site. The program has 4 main functions: * generate (randomly) an expression tree. * evaluate the fitness of the tree * crossbreed * mutate...
Ignore everyone elses' answer for now. The first thing you should learn to use is the profiler. Python comes with a profile/cProfile; you should learn how to read the results and analyze where the real bottlenecks is. The goal of optimization is three-fold: reduce the time spent on each call, reduce the number of calls...
Using urllib and BeautifulSoup to retrieve info from web with Python
2,647,179
7
2010-04-15T16:34:29Z
2,647,188
14
2010-04-15T16:36:10Z
[ "python", "urllib2", "beautifulsoup" ]
I can get the html page using urllib, and use BeautifulSoup to parse the html page, and it looks like that I have to generate file to be read from BeautifulSoup. ``` import urllib sock = urllib.urlopen("http://SOMEWHERE") htmlSource = sock.read() sock...
``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(htmlSource) ``` No file writing needed: Just pass in the HTML string. You can also pass the object returned from `urlopen` directly: ``` f = urllib.urlopen("http://SOMEWHERE") soup = BeautifulSoup(f) ```
urllib2 to string
2,647,723
4
2010-04-15T17:48:01Z
2,647,736
8
2010-04-15T17:49:54Z
[ "python", "string", "urllib2" ]
I'm using urllib2 to open a url. Now I need the html file as a string. How do I do this?
The easiest way would be: ``` f = urllib2.urlopen("http://example.com/foo/bar") s = f.read() # s now holds the contents of the site ``` There is more information in the [urllib2 docs](http://docs.python.org/library/urllib2.html). `urlopen()` returns a file-like object, so Python's [file object methods](http://docs.p...
Python Pre-testing for exceptions when coverage fails
2,647,790
4
2010-04-15T18:00:30Z
2,648,113
7
2010-04-15T18:50:37Z
[ "python", "unit-testing", "exception-handling", "runtime-error", "code-coverage" ]
I recently came across a simple but nasty bug. I had a list and I wanted to find the smallest member in it. I used Python's built-in min(). Everything worked great until in some strange scenario the list was empty (due to strange user input I could not have anticipated). My application crashed with a ValueError (BTW - ...
The problem here is that malformed external input crashed your program. The solution is to exhaustively unit test possible input scenarios at the boundaries of your code. You say your unit tests are 'extensive', but you clearly hadn't tested for this possibility. Code coverage is a useful tool, but it's important to re...
How can I tell what directory an imported library comes from in python?
2,647,862
5
2010-04-15T18:11:43Z
2,648,090
7
2010-04-15T18:47:12Z
[ "python", "import" ]
I'm trying to modify a python library that I downloaded and am using. But the changes I'm making aren't doing anything. So I suspect that python is importing a different copy of this library from somewhere else on the filesystem. So... When I run `import foolib` in python, how can I tell where on the filesystem it's g...
the correct answer is to use `sys.modules`... it works on *everything*, even `sys`. `sys.modules` is a dictionary where the keys are the imported names (modules or packages), and the values are their respective locations. here is some usage output from my Mac: ``` $ python Python 2.5.1 (r251:54863, Feb 9 2009, 18:49:...
Python frequency detection
2,648,151
26
2010-04-15T18:57:56Z
2,649,540
33
2010-04-15T22:52:01Z
[ "python", "audio", "fft", "frequency" ]
Ok what im trying to do is a kind of audio processing software that can detect a prevalent frequency an if the frequency is played for long enough (few ms) i know i got a positive match. i know i would need to use FFT or something simiral but in this field of math i suck, i did search the internet but didn not find a c...
The [aubio](http://aubio.org/) libraries have been wrapped with SWIG and can thus be used by Python. Among their many features include several methods for pitch detection/estimation including the [YIN](http://www.ircam.fr/pcm/cheveign/pss/2002_JASA_YIN.pdf) algorithm and some harmonic comb algorithms. However, if you ...
Python unit test. How to add some sleeping time between test cases?
2,648,329
4
2010-04-15T19:24:45Z
2,648,359
9
2010-04-15T19:28:43Z
[ "python", "unit-testing" ]
I am using python unit test module. I am wondering is there anyway to add some delay between every 2 test cases? Because my unit test is just making http request and I guess the server may block the frequent request from the same ip.
Put a sleep inside the `tearDown` method of your `TestCase` ``` class ExampleTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): time.sleep(1) # sleep time in seconds ``` This will execute after every test within that `TestCase` **EDIT**: added `setUp` because the [docume...
Help me finish this Python 3.x self-challenge
2,649,513
8
2010-04-15T22:45:28Z
2,649,570
24
2010-04-15T23:01:58Z
[ "python", "python-3.x", "puzzle", "combinatorics" ]
This is not homework. I saw [this article praising Linq library and how great it is](http://msdn.microsoft.com/en-us/vcsharp/ee957404.aspx) for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion. After half hour of dabbing with Python I failed. Please finish where I left o...
Here's a short solution, using [itertools.permutations](http://docs.python.org/library/itertools.html#itertools.permutations): ``` from itertools import permutations def is_solution(seq): return all(int(seq[:i]) % i == 0 for i in range(2, 9)) for p in permutations('123456789'): seq = ''.join(p) if is_sol...
Unicode identifiers in Python?
2,649,544
27
2010-04-15T22:52:31Z
2,649,560
31
2010-04-15T22:58:56Z
[ "python", "unicode", "identifier" ]
I want to build a Python function that calculates, ![alt text](http://1.bp.blogspot.com/_mGF7Mo1o9b4/SlT2s9H7g_I/AAAAAAAAABE/RYgqR4C3XSM/s400/entropy) and would like to name my summation function Σ. In a similar fashion, would like to use Π for product, and so on. I was wondering if there was a way to name a python...
(I think it’s pretty cool too, that might mean we’re geeks.) You’re fine to do this with the code you have above in Python 3. (It works in my Python 3.1 interpreter at least.) See: * <http://docs.python.org/py3k/reference/lexical_analysis.html#identifiers> * <http://www.python.org/dev/peps/pep-3131/> But in Py...
Unicode identifiers in Python?
2,649,544
27
2010-04-15T22:52:31Z
7,158,999
10
2011-08-23T09:40:06Z
[ "python", "unicode", "identifier" ]
I want to build a Python function that calculates, ![alt text](http://1.bp.blogspot.com/_mGF7Mo1o9b4/SlT2s9H7g_I/AAAAAAAAABE/RYgqR4C3XSM/s400/entropy) and would like to name my summation function Σ. In a similar fashion, would like to use Π for product, and so on. I was wondering if there was a way to name a python...
According to [is it bad](http://programmers.stackexchange.com/questions/16010/is-it-bad-to-use-unicode-characters-in-variable-names), you can use some unicode characters, but not all: You are restricted to characters identified as letters. ``` >>> α = 3 >>> Σ = sum >>> import math >>> √ = math.sqrt   Fi...
Unicode identifiers in Python?
2,649,544
27
2010-04-15T22:52:31Z
21,867,836
9
2014-02-18T23:31:46Z
[ "python", "unicode", "identifier" ]
I want to build a Python function that calculates, ![alt text](http://1.bp.blogspot.com/_mGF7Mo1o9b4/SlT2s9H7g_I/AAAAAAAAABE/RYgqR4C3XSM/s400/entropy) and would like to name my summation function Σ. In a similar fashion, would like to use Π for product, and so on. I was wondering if there was a way to name a python...
It's worth pointing out that Python 3 *does* support Unicode identifiers, but only allows letter or number like symbols (see <http://docs.python.org/3.3/reference/lexical_analysis.html#identifiers> for full details). That's why Σ works (remember that it's a Greek letter, not just a math symbol), but √ doesn't.
python remove everything between <div class="comment> .. any... </div>
2,649,751
7
2010-04-15T23:50:41Z
2,649,860
16
2010-04-16T00:26:05Z
[ "python", "class", "html" ]
how do you use python 2.6 to remove everything including the `<div class="comment"> ....remove all ....</div>` i tried various way using re.sub without any success Thank you
This can be done easily and reliably using an HTML parser like [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/): ``` >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup('<body><div>1</div><div class="comment"><strong>2</strong></div></body>') >>> for div in soup.findAll('div', 'comment')...
Can a native-looking GUI be made with Python
2,649,882
14
2010-04-16T00:34:07Z
2,649,905
9
2010-04-16T00:42:59Z
[ "python", "user-interface" ]
I haven't gotten far enough into Python to make GUIs yet, so I thought I'd ask here. Can a python app be made with the windows default style GUI, or will it have its own style? The only screenshots I've seen of a python app running with a GUI had this ugly win95 look to it.
The "ugly" Windows 95 look is determined by the version of the Common Dialog library. Supplying a manifest file with the executable (probably your Python implementation) makes Windows use of visual styles, instead of the "ugly" look. Read more here: <http://msdn.microsoft.com/en-us/library/ms997646.aspx>
Can a native-looking GUI be made with Python
2,649,882
14
2010-04-16T00:34:07Z
2,650,115
7
2010-04-16T01:56:49Z
[ "python", "user-interface" ]
I haven't gotten far enough into Python to make GUIs yet, so I thought I'd ask here. Can a python app be made with the windows default style GUI, or will it have its own style? The only screenshots I've seen of a python app running with a GUI had this ugly win95 look to it.
You (and the rest of the world, really ;)) should take a look at [PyGUI](http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/), by Greg Ewing. In his own words, it's "a project to develop a cross-platform pythonic GUI API." Not only that, it attempts to generate native-looking GUIs on each of the three major platfor...
Is there an equivalent in Scala to Python's more general map function?
2,650,156
9
2010-04-16T02:17:27Z
2,651,223
11
2010-04-16T07:07:49Z
[ "python", "scala", "iterable", "applicative" ]
I know that Scala's Lists have a [map](http://www.scala-lang.org/docu/files/api/scala/List.html#map%28%28A%29%3D%3EB%29) implementation with signature `(f: (A) => B):List[B]` and a [foreach](http://www.scala-lang.org/docu/files/api/scala/List.html#foreach%28%28A%29%3D%3EUnit%29) implementation with signature `(f: (A) =...
In scala 2.8, there is a method called zipped in Tuple2 & Tuple3 which avoid to create temporary collection. Here is some sample use case: ``` Welcome to Scala version 2.8.0.r21561-b20100414020114 (Java HotSpot(TM) Client VM, Java 1.6.0_18). Type in expressions to have them evaluated. Type :help for more information. ...
Is there an equivalent in Scala to Python's more general map function?
2,650,156
9
2010-04-16T02:17:27Z
2,653,227
11
2010-04-16T13:29:47Z
[ "python", "scala", "iterable", "applicative" ]
I know that Scala's Lists have a [map](http://www.scala-lang.org/docu/files/api/scala/List.html#map%28%28A%29%3D%3EB%29) implementation with signature `(f: (A) => B):List[B]` and a [foreach](http://www.scala-lang.org/docu/files/api/scala/List.html#foreach%28%28A%29%3D%3EUnit%29) implementation with signature `(f: (A) =...
The function you're looking for is usually called `zipWith`. It's unfortunately not provided in the standard libraries, but it's pretty easy to write: ``` def zipWith[A,B,C](f: (A,B) => C, a: Iterable[A], b: Iterable[B]) = new Iterable[C] { def elements = (a.elements zip b.elements) map f.tupled } ``` This wi...
How to get REALLY fast Python over a simple loop
2,650,544
21
2010-04-16T04:10:13Z
2,650,594
14
2010-04-16T04:22:24Z
[ "python", "performance", "optimization" ]
I'm working on a [SPOJ](http://en.wikipedia.org/wiki/SPOJ) problem, [INTEST](http://www.spoj.pl/problems/INTEST/). The goal is to specify the number of test cases (n) and a divisor (k), then feed your program n numbers. The program will accept each number on a newline of stdin and after receiving the nth number, will t...
[Edited to reflect new findings and passing code on spoj] Generally, when using Python for spoj: * Don't use "raw\_input", use sys.stdin.readlines(). That can make a difference for large input. Also, if possible (and it is, for this problem), read everything at once (sys.stdin. readlines()), instead of reading line b...
How to get REALLY fast Python over a simple loop
2,650,544
21
2010-04-16T04:10:13Z
2,650,902
7
2010-04-16T05:50:32Z
[ "python", "performance", "optimization" ]
I'm working on a [SPOJ](http://en.wikipedia.org/wiki/SPOJ) problem, [INTEST](http://www.spoj.pl/problems/INTEST/). The goal is to specify the number of test cases (n) and a divisor (k), then feed your program n numbers. The program will accept each number on a newline of stdin and after receiving the nth number, will t...
Hey, I got it to be within the time limit. I used the following: * Psyco with Python 2.5. * a simple loop with a variable to keep count in * my code was all in a main() function (except the psyco import) which I called. The last one is what made the difference. I believe that it has to do with variable visibility, bu...
Embed bash in python
2,651,874
8
2010-04-16T09:29:47Z
2,651,975
7
2010-04-16T09:49:17Z
[ "python", "bash", "interop", "language-interoperability" ]
I am writting a Python script and I am running out of time. I need to do some things that I know pretty well in bash, so I just wonder how can I embed some bash lines into a Python script. Thanks
If you want to call system commands, use the [subprocess](http://docs.python.org/library/subprocess.html) module.
Embed bash in python
2,651,874
8
2010-04-16T09:29:47Z
2,654,398
20
2010-04-16T15:59:19Z
[ "python", "bash", "interop", "language-interoperability" ]
I am writting a Python script and I am running out of time. I need to do some things that I know pretty well in bash, so I just wonder how can I embed some bash lines into a Python script. Thanks
The ideal way to do it: ``` def run_script(script, stdin=None): """Returns (stdout, stderr), raises error on non-zero return code""" import subprocess # Note: by using a list here (['bash', ...]) you avoid quoting issues, as the # arguments are passed in exactly this order (spaces, quotes, and newline...
How to detect a sign change for elements in a numpy array
2,652,368
10
2010-04-16T11:04:40Z
2,652,425
13
2010-04-16T11:16:11Z
[ "python", "numpy" ]
I have a numpy array with positive and negative values in. ``` a = array([1,1,-1,-2,-3,4,5]) ``` I want to create another array which contains a value at each index where a sign change occurs (For example, if the current element is positive and the previous element is negative and vice versa). For the array above, I...
Something like ``` a = array([1,1,-1,-2,-3,4,5]) asign = np.sign(a) signchange = ((np.roll(asign, 1) - asign) != 0).astype(int) print signchange array([0, 0, 1, 0, 0, 1, 0]) ``` Now, numpy.roll does a circular shift, so if the last element has different sign than the first, the first element in the signchange array w...
How to detect a sign change for elements in a numpy array
2,652,368
10
2010-04-16T11:04:40Z
4,843,931
7
2011-01-30T16:18:47Z
[ "python", "numpy" ]
I have a numpy array with positive and negative values in. ``` a = array([1,1,-1,-2,-3,4,5]) ``` I want to create another array which contains a value at each index where a sign change occurs (For example, if the current element is positive and the previous element is negative and vice versa). For the array above, I...
``` (numpy.diff(numpy.sign(a)) != 0)*1 ```
Update an sqlite database schema with sqlalchemy and elixir
2,652,378
10
2010-04-16T11:06:05Z
2,653,822
7
2010-04-16T14:47:13Z
[ "python", "database", "sqlalchemy", "python-elixir", "sqlalchemy-migrate" ]
I've created a python application which uses elixir/sqlalchemy to store data. The second release of the software requires any files created in the previous version to be updated in order to add/delete tables and columns. My question is: how can I achieve this? I'm aware of [sqlalchemy-migrate](http://code.google.com/p...
What you're talking about is a well known and quite complex problem. It is known as database migration. Every good project have some policy that describes how database schema and data mutations should be applied to advance from one product version to the other. Many frameworks such as Django or Ruby on Rails have a mi...
fft and array-to-image / image-to-array-conversion
2,652,415
3
2010-04-16T11:13:39Z
2,652,550
12
2010-04-16T11:37:38Z
[ "python", "image-processing", "fft" ]
I want to make a fourier-transformation of an image. But how can I change the picture to an array? And after this I think I should use numpy.fft.rfft2 for the transformation. And how to change back from the array to the image? Thanks in advance.
You can use the [PIL](http://www.pythonware.com/products/pil/) library to load/save images and convert to/from numpy arrays. ``` import Image, numpy i = Image.open('img.png') i = i.convert('L') #convert to grayscale a = numpy.asarray(i) # a is readonly b = abs(numpy.fft.rfft2(a)) j = Image.fromarray(b) j.save('im...
Can't iterate over a list class in Python
2,652,761
5
2010-04-16T12:10:11Z
2,652,814
12
2010-04-16T12:19:10Z
[ "python" ]
I'm trying to write a simple GUI front end for Plurk using pyplurk. I have successfully got it to create the API connection, log in, and retrieve and display a list of friends. Now I'm trying to retrieve and display a list of Plurks. pyplurk provides a GetNewPlurks function as follows: ``` def GetNewPlurks(self, s...
When you define your own `__iter__` method, you should realize that that `__iter__` method should return an *iterator*, not an *iterable*. You are returning a list, not an iterator to a list, so it fails. You can fix it by doing `return iter(self._plurks)`, for example. If you wanted to do something a little more comp...
Error on windows using session from appengine-utilities
2,652,820
4
2010-04-16T12:20:09Z
2,653,503
11
2010-04-16T14:07:08Z
[ "python", "google-app-engine", "session" ]
I ran across an odd problem while trying to transfer a project to a windows machine. In my project I use a session handler (http://gaeutilities.appspot.com/session) it works fine on my mac but on windows I get: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google\_appengine\google\appengine\e...
The bug is pretty clear by glancing at the sources, although perfectly OS-independent. In [sessions.py](http://code.google.com/p/gaeutilities/source/browse/trunk/appengine_utilities/sessions.py) lines 544-547: ``` string_cookie = os.environ.get(u"HTTP_COOKIE", u"") self.cookie = Cookie.SimpleCookie() self....
Python: How to get the caller's method name in the called method?
2,654,113
91
2010-04-16T15:18:59Z
2,654,130
124
2010-04-16T15:20:55Z
[ "python", "introspection" ]
Python: How to get the caller's method name in the called method? Assume I have 2 methods: ``` def method1(self): ... a = A.method2() def method2(self): ... ``` If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?
[inspect.getframeinfo](http://docs.python.org/library/inspect.html?highlight=inspect#inspect.getframeinfo) and other related functions in `inspect` can help: ``` >>> import inspect >>> def f1(): f2() ... >>> def f2(): ... curframe = inspect.currentframe() ... calframe = inspect.getouterframes(curframe, 2) ... p...
Python: How to get the caller's method name in the called method?
2,654,113
91
2010-04-16T15:18:59Z
8,663,885
60
2011-12-29T04:04:54Z
[ "python", "introspection" ]
Python: How to get the caller's method name in the called method? Assume I have 2 methods: ``` def method1(self): ... a = A.method2() def method2(self): ... ``` If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?
Shorter version: ``` import inspect def f1(): f2() def f2(): print 'caller name:', inspect.stack()[1][3] f1() ``` (with thanks to @Alex, and [Stefaan Lippen](http://stefaanlippens.net/python_inspect))
Python: How to get the caller's method name in the called method?
2,654,113
91
2010-04-16T15:18:59Z
9,812,105
17
2012-03-21T20:12:08Z
[ "python", "introspection" ]
Python: How to get the caller's method name in the called method? Assume I have 2 methods: ``` def method1(self): ... a = A.method2() def method2(self): ... ``` If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?
I've come up with a slightly longer version that tries to build a full method name including module and class. <https://gist.github.com/2151727> (rev 9cccbf) ``` # Public Domain, i.e. feel free to copy/paste # Considered a hack in Python 2 import inspect def caller_name(skip=2): """Get a name of a caller in the...
Python: How to get the caller's method name in the called method?
2,654,113
91
2010-04-16T15:18:59Z
24,940,992
18
2014-07-24T18:08:16Z
[ "python", "introspection" ]
Python: How to get the caller's method name in the called method? Assume I have 2 methods: ``` def method1(self): ... a = A.method2() def method2(self): ... ``` If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?
This seems to work just fine: ``` import sys print sys._getframe().f_back.f_code.co_name ```
Count bits of a integer in Python
2,654,149
17
2010-04-16T15:23:27Z
2,654,199
18
2010-04-16T15:30:38Z
[ "python", "bits", "bitcount" ]
``` 1 = 0b1 -> 1 5 = 0b101 -> 3 10 = 0b1010 -> 4 100 = 0b1100100 -> 7 1000 = 0b1111101000 -> 10 … ``` How can I get the bit size of an integer, i.e. count the number of bits that are necessary to represent an integer in Python?
``` >>> len(bin(1000))-2 10 >>> len(bin(100))-2 7 >>> len(bin(10))-2 4 ``` **Note**: will not work for negative numbers, may be need to substract 3 instead of 2
Count bits of a integer in Python
2,654,149
17
2010-04-16T15:23:27Z
2,654,211
100
2010-04-16T15:32:07Z
[ "python", "bits", "bitcount" ]
``` 1 = 0b1 -> 1 5 = 0b101 -> 3 10 = 0b1010 -> 4 100 = 0b1100100 -> 7 1000 = 0b1111101000 -> 10 … ``` How can I get the bit size of an integer, i.e. count the number of bits that are necessary to represent an integer in Python?
In python 2.7+ there is a [`int.bit_length()`](http://docs.python.org/py3k/library/stdtypes.html#int.bit_length) method: ``` >>> a = 100 >>> a.bit_length() 7 ```
Restrictons of Python compared to Ruby: lambda's
2,654,425
5
2010-04-16T16:02:49Z
2,654,458
9
2010-04-16T16:06:52Z
[ "python", "ruby", "lambda", "restriction" ]
I was going over some pages from WikiVS, that I quote from: > because lambdas in Python are restricted to expressions and cannot > contain statements I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language. Thank you for your answers, comm...
The most commonly encountered situation regarding statements is probably Python 2.X's `print` statement. For example, ``` say_hi = lambda name: "Hello " + name ``` works as expected. But this will not compile: ``` say_hi = lambda name: print "Hello " + name ``` because `print` is not a proper function in Python 2...
Restrictons of Python compared to Ruby: lambda's
2,654,425
5
2010-04-16T16:02:49Z
2,654,937
11
2010-04-16T17:20:53Z
[ "python", "ruby", "lambda", "restriction" ]
I was going over some pages from WikiVS, that I quote from: > because lambdas in Python are restricted to expressions and cannot > contain statements I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language. Thank you for your answers, comm...
I don't think you're really asking about lambdas, but *inline functions*. This is genuinely one of Python's seriously annoying limitations: you can't define a function (a real function, not just an expression) inline; you have to give it a name. This is very frustrating, since every other modern scripting language doe...
Identifying that a variable is a new-style class in Python?
2,654,622
12
2010-04-16T16:33:33Z
2,654,806
8
2010-04-16T17:01:09Z
[ "python", "class", "python-2.x" ]
I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. ``` import types class oldclass: pass def test(): o = oldclass() if type(o) is types.InstanceType: print 'Is old-style' else:...
I think what you are asking is: "Can I test if a class was defined in Python code as a new-style class?". Technically simple types such as `int` *are* new-style classes, but it is still possible to distinguish classes written in Python from the built-in types. Here's something that works, although it's a bit of a hack...
Django - how to write users and profiles handling in best way?
2,654,689
3
2010-04-16T16:43:19Z
2,654,818
12
2010-04-16T17:02:38Z
[ "python", "django", "user", "profiles" ]
I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangoboo...
> users should be able to register and authenticate `django.contrib.auth` is the module you want. Be sure to check the docs for [custom login forms.](http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login) > every user should have profile (or model with all required fields) You need to set...
Capturing stdout within the same process in Python
2,654,834
6
2010-04-16T17:04:49Z
3,113,913
13
2010-06-24T21:13:27Z
[ "python", "stream" ]
I've got a python script that calls a bunch of functions, each of which writes output to stdout. Sometimes when I run it, I'd like to send the output in an e-mail (along with a generated file). I'd like to know how I can capture the output in memory so I can use the `email` module to build the e-mail. My ideas so far ...
I modified None's answer to make it a context manager: ``` import sys, StringIO, contextlib class Data(object): pass @contextlib.contextmanager def capture_stdout(): old = sys.stdout capturer = StringIO.StringIO() sys.stdout = capturer data = Data() yield data sys.stdout = old data.re...
filtering elements from list of lists in Python?
2,655,956
3
2010-04-16T20:37:40Z
2,656,070
18
2010-04-16T20:56:36Z
[ "python", "list", "list-comprehension" ]
I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: ``` a = [[1,2,3],[4,5,6]] ``` suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing: ``` filter(lambda x, y, z: x + y + z >= N, a...
Using `lambda` with `filter` is sort of silly when we have other techniques available. In this case I would probably solve the specific problem this way (or using the equivalent generator expression) ``` >>> a = [[1, 2, 3], [4, 5, 6]] >>> [item for item in a if sum(item) > 10] [[4, 5, 6]] ``` or, if I needed to unpa...
ListCtrl - wxPython / Python
2,656,017
3
2010-04-16T20:46:25Z
2,656,249
7
2010-04-16T21:40:54Z
[ "python", "wxpython", "listctrl" ]
My question is if we can assign/bind some value to a certain item and hide that value(or if we can do the same thing in another way). Example: Lets say the columns on ListCtrl are "Name" and "Description": ``` self.lc = wx.ListCtrl(self, -1, style=wx.LC_REPORT) self.lc.InsertColumn(0, 'Name') self.lc.InsertColumn(1, ...
Instead of using the ListCtrl as your data structure, you could keep a separate list/dict of objects that contain all the information you want and refresh the ListCtrl from your other data structure. For example: ``` class MyObject(object): def __init__(self, name, description, hidden_description): self.n...
Adding a font for use in ReportLab
2,656,145
10
2010-04-16T21:14:35Z
2,656,269
7
2010-04-16T21:45:32Z
[ "python", "fonts", "reportlab" ]
I'm trying to add a font to the python ReportLab so that I can use it for a function. The function is using canvas.Canvas to draw a bunch of text in a PDF, nothing complicated, but I need to add a fixed width font for layout issues. When I tried to register a font using what little info I could find, that seemed to wo...
``` c.setFont('TestFont') c.drawString(1,1,'test data here') ``` `setFont` to set the font name you're going to use, and `drawString`. ReportLab will automatically embed the font if you use it in the document, you don't have to manually add it after you've registered the font globally under a name.
shutil.rmtree fails on Windows with 'Access is denied'
2,656,322
40
2010-04-16T21:57:55Z
2,656,405
51
2010-04-16T22:21:29Z
[ "python", "windows", "file-permissions", "shutil" ]
In Python, when running `shutil.rmtree` over a folder that contains a read-only file, the following exception is printed: ``` File "C:\Python26\lib\shutil.py", line 216, in rmtree rmtree(fullname, ignore_errors, onerror) File "C:\Python26\lib\shutil.py", line 216, in rmtree rmtree(fullname, ignore_errors, oner...
Check this question out: <http://stackoverflow.com/questions/1213706/what-user-do-python-scripts-run-as-in-windows> Apparently the answer is to change the file/folder to not be read-only and then remove it. Here's `onerror()` handler from [`pathutils.py`](http://www.voidspace.org.uk/downloads/pathutils.py) mentioned...
shutil.rmtree fails on Windows with 'Access is denied'
2,656,322
40
2010-04-16T21:57:55Z
2,656,408
11
2010-04-16T22:22:35Z
[ "python", "windows", "file-permissions", "shutil" ]
In Python, when running `shutil.rmtree` over a folder that contains a read-only file, the following exception is printed: ``` File "C:\Python26\lib\shutil.py", line 216, in rmtree rmtree(fullname, ignore_errors, onerror) File "C:\Python26\lib\shutil.py", line 216, in rmtree rmtree(fullname, ignore_errors, oner...
I'd say implement your own rmtree with [os.walk](http://docs.python.org/library/os.html#os.walk) that ensures access by using [os.chmod](http://docs.python.org/library/os.html#os.chmod) on each file before trying to delete it. Something like this (untested): ``` import os import stat def rmtree(top): for root, d...
Why does python use 'magic methods'?
2,657,627
65
2010-04-17T07:26:24Z
2,657,639
40
2010-04-17T07:32:12Z
[ "python", "magic-methods" ]
I've been playing around with Python recently, and one thing I'm finding a bit odd is the extensive use of 'magic methods', e.g. to make its length available an object implements a method `def __len__(self)` and then it is called when you write `len(obj)`. I was just wondering why objects don't simply define a `len(se...
AFAIK, `len` is special in this respect and has historical roots. Here's a quote [from the FAQ](http://docs.python.org/faq/design.html): > **Why does Python use methods for some > functionality (e.g. list.index()) but > functions for other (e.g. len(list))?** > > The major reason is history. Functions > were used for...
Why does python use 'magic methods'?
2,657,627
65
2010-04-17T07:26:24Z
2,657,649
15
2010-04-17T07:37:26Z
[ "python", "magic-methods" ]
I've been playing around with Python recently, and one thing I'm finding a bit odd is the extensive use of 'magic methods', e.g. to make its length available an object implements a method `def __len__(self)` and then it is called when you write `len(obj)`. I was just wondering why objects don't simply define a `len(se...
From the Zen of Python: > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. This is one of the reasons - with custom methods, developers would be free to choose a different method name, like `getLength()`, `length()`, `getlength()` or w...
Why does python use 'magic methods'?
2,657,627
65
2010-04-17T07:26:24Z
2,659,640
7
2010-04-17T19:12:07Z
[ "python", "magic-methods" ]
I've been playing around with Python recently, and one thing I'm finding a bit odd is the extensive use of 'magic methods', e.g. to make its length available an object implements a method `def __len__(self)` and then it is called when you write `len(obj)`. I was just wondering why objects don't simply define a `len(se...
Some of these functions do more than a single method would be able to implement (without abstract methods on a superclass). For instance `bool()` acts kind of like this: ``` def bool(obj): if hasattr(obj, '__nonzero__'): return bool(obj.__nonzero__()) elif hasattr(obj, '__len__'): if obj.__len_...
Insert a newline character every 64 characters using Python
2,657,693
16
2010-04-17T07:54:39Z
2,657,703
24
2010-04-17T07:58:26Z
[ "regex", "python" ]
Using Python I need to insert a newline character into a string every 64 characters. In Perl it's easy: ``` s/(.{64})/$1\n/ ``` How could this be done using regular expressions in Python? Is there a more pythonic way to do it?
Same as in Perl, but with a backslash instead of the dollar for accessing groups: ``` s = "0123456789"*100 # test string import re print re.sub("(.{64})", "\\1\n", s, 0, re.DOTALL) ``` [`re.DOTALL`](http://docs.python.org/library/re.html#re.DOTALL) is the equivalent to Perl's `s/` option.
Insert a newline character every 64 characters using Python
2,657,693
16
2010-04-17T07:54:39Z
2,657,733
16
2010-04-17T08:13:17Z
[ "regex", "python" ]
Using Python I need to insert a newline character into a string every 64 characters. In Perl it's easy: ``` s/(.{64})/$1\n/ ``` How could this be done using regular expressions in Python? Is there a more pythonic way to do it?
without regexp: ``` def insert_newlines(string, every=64): lines = [] for i in xrange(0, len(string), every): lines.append(string[i:i+every]) return '\n'.join(lines) ``` shorter but less readable (imo): ``` def insert_newlines(string, every=64): return '\n'.join(string[i:i+every] for i in xra...
Insert a newline character every 64 characters using Python
2,657,693
16
2010-04-17T07:54:39Z
2,657,758
10
2010-04-17T08:24:19Z
[ "regex", "python" ]
Using Python I need to insert a newline character into a string every 64 characters. In Perl it's easy: ``` s/(.{64})/$1\n/ ``` How could this be done using regular expressions in Python? Is there a more pythonic way to do it?
I'd go with: ``` import textwrap s = "0123456789"*100 print '\n'.join(textwrap.wrap(s, 64)) ```
Get localized language name from locale code
2,657,787
5
2010-04-17T08:35:35Z
2,659,333
10
2010-04-17T17:33:51Z
[ "python", "locale" ]
How can I get localized language name by specified locale code in python? For example: ``` >> get_language_name('ja') >> ('Japanese', u'日本語') ```
The [Babel](http://babel.edgewall.org/) package can help: ``` >>> from babel import Locale >>> locale = Locale('ja', 'JP') >>> print locale.display_name 日本語 (日本) ``` There is also [PyICU](http://pyicu.osafoundation.org/), a Python wrapper for the [ICU](http://site.icu-project.org/) library.
How to change the date/time in Python for all modules?
2,658,026
16
2010-04-17T10:22:31Z
2,659,472
8
2010-04-17T18:19:49Z
[ "python", "unit-testing", "datetime", "testing", "time" ]
When I write with business logic, my code often depends on the current time. For example the algorithm which looks at each unfinished order and checks if an invoice should be sent (which depends on the no of days since the job was ended). In these cases creating an invoice is not triggered by an explicit user action bu...
Monkey-patching `time.time` is probably sufficient, actually, as it provides the basis for almost all the other time-based routines in Python. This appears to handle your use case pretty well, without resorting to more complex tricks, and it doesn't matter when you do it (aside from the few stdlib packages like Queue.p...
Python-mode import problem
2,658,475
19
2010-04-17T13:20:00Z
3,390,395
16
2010-08-02T17:53:26Z
[ "python", "emacs" ]
I'm trying to use Emacs as a python editor and it works fine when I evaluate(C-c C-c) only single files but when I evaluate a file that imports another file in the same directory, I get an error saying that the file could not be imported. Does anyone know of a workaround? Thanks in advance edit: Btw, i'm using Emacs...
I think the problem is in the way Emacs' python-mode runs Python. If I type `M-x run-python`, then I see this: ``` >>> import sys >>> '' in sys.path False >>> ``` whereas if I run the python interpreter from the shell, I see: ``` >>> import sys >>> '' in sys.path True >>> ``` This seems to be due to the following c...
Python-mode import problem
2,658,475
19
2010-04-17T13:20:00Z
9,561,305
11
2012-03-05T03:34:10Z
[ "python", "emacs" ]
I'm trying to use Emacs as a python editor and it works fine when I evaluate(C-c C-c) only single files but when I evaluate a file that imports another file in the same directory, I get an error saying that the file could not be imported. Does anyone know of a workaround? Thanks in advance edit: Btw, i'm using Emacs...
Since the answers previous to this one were posted an option was made available to change the default behaviour (removing the current directory from the path) to include the cwd in the path. So a simple ``` (setq python-remove-cwd-from-path nil) ``` in your .emacs should fix this.
How do I make PyScripter work? Says it cant find python26.dll
2,658,779
5
2010-04-17T14:58:42Z
2,658,890
7
2010-04-17T15:27:51Z
[ "python", "pythonpath", "pyscripter" ]
I installed PyScript to try it out but it just wont start. It only gives me the error: "Error126: Could not open Dll "python26.dll" followed by: "Python could not be properly initialized. We must quit." I think this may have something to do with the PYTHONPATH but since I'm a newbie and dont know what it is or exactly...
**Edit**: PyScripter don't need wxPython to run that. and Looks like you have 64bit python, according to your comment. but pyscripter site says, you need 32 bit version of python > If you are using a 64bit version of > Windows note that PyScripter will only > work if a 32bit version of Python is > installed. So, on...
In my virtualenv, I need to use sudo for all commands
2,658,902
7
2010-04-17T15:31:22Z
2,659,051
11
2010-04-17T16:12:23Z
[ "python", "sudo", "virtualenv" ]
I set up a `virtualenv`, which is working, but for some reason I need to use `sudo` for commands as simple as `mkdir`. Obviously I did something incorrectly. Any idea what it might be? Thanks
Check the directory permissions and owner and give: ``` $ sudo chown -R me:me virtualenvdir $ sudo chmod -R a+rX virtualenvdir ``` change `me` with your username, typically $USER, and `virtualenvdir` with your virtualenv's work directory.
How do I convert a numpy array to (and display) an image?
2,659,312
51
2010-04-17T17:28:30Z
2,659,369
18
2010-04-17T17:42:53Z
[ "python", "image", "arrays", "numpy" ]
I have created an array thusly: ``` import numpy as np data = np.zeros( (512,512,3), dtype=np.uint8) data[256,256] = [255,0,0] ``` What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)
Shortest path is to use `scipy`, like this: ``` from scipy.misc import toimage toimage(data).show() ``` This requires PIL or Pillow to be installed as well. A similar approach also requiring PIL or Pillow but which *may invoke a different viewer* is: ``` from scipy.misc import imshow imshow(data) ```
How do I convert a numpy array to (and display) an image?
2,659,312
51
2010-04-17T17:28:30Z
2,659,371
58
2010-04-17T17:43:33Z
[ "python", "image", "arrays", "numpy" ]
I have created an array thusly: ``` import numpy as np data = np.zeros( (512,512,3), dtype=np.uint8) data[256,256] = [255,0,0] ``` What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)
Do you just mean this? ``` from matplotlib import pyplot as plt plt.imshow(data, interpolation='nearest') plt.show() ```
How do I convert a numpy array to (and display) an image?
2,659,312
51
2010-04-17T17:28:30Z
2,659,378
44
2010-04-17T17:46:54Z
[ "python", "image", "arrays", "numpy" ]
I have created an array thusly: ``` import numpy as np data = np.zeros( (512,512,3), dtype=np.uint8) data[256,256] = [255,0,0] ``` What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)
You could use PIL to create (and display) an image: ``` from PIL import Image import numpy as np w, h = 512, 512 data = np.zeros((h, w, 3), dtype=np.uint8) data[256, 256] = [255, 0, 0] img = Image.fromarray(data, 'RGB') img.save('my.png') img.show() ```
Python: Slicing a list into n nearly-equal-length partitions
2,659,900
31
2010-04-17T20:20:10Z
2,660,034
10
2010-04-17T20:55:06Z
[ "python", "list", "slice" ]
I'm looking for a fast, clean, pythonic way to divide a list into exactly n nearly-equal partitions. ``` partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]] partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]]) partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too) ``` There are...
``` def partition(lst, n): division = len(lst) / float(n) return [ lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n) ] >>> partition([1,2,3,4,5],5) [[1], [2], [3], [4], [5]] >>> partition([1,2,3,4,5],2) [[1, 2, 3], [4, 5]] >>> partition([1,2,3,4,5],3) [[1, 2], [3, 4], [5]] >>> pa...
Python: Slicing a list into n nearly-equal-length partitions
2,659,900
31
2010-04-17T20:20:10Z
2,660,138
23
2010-04-17T21:26:16Z
[ "python", "list", "slice" ]
I'm looking for a fast, clean, pythonic way to divide a list into exactly n nearly-equal partitions. ``` partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]] partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]]) partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too) ``` There are...
Here's a version that's similar to Daniel's: it divides as evenly as possible, but puts all the larger partitions at the start: ``` def partition(lst, n): q, r = divmod(len(lst), n) indices = [q*i + min(i, r) for i in xrange(n+1)] return [lst[indices[i]:indices[i+1]] for i in xrange(n)] ``` It also avoids...
Python: Slicing a list into n nearly-equal-length partitions
2,659,900
31
2010-04-17T20:20:10Z
14,861,842
19
2013-02-13T19:51:39Z
[ "python", "list", "slice" ]
I'm looking for a fast, clean, pythonic way to divide a list into exactly n nearly-equal partitions. ``` partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]] partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]]) partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too) ``` There are...
Just a different take, that only works if `[[1,3,5],[2,4]]` is an acceptable partition, in your example. ``` def partition ( lst, n ): return [ lst[i::n] for i in xrange(n) ] ``` This satisfies the example mentioned in @Daniel Stutzbach's example: ``` partition(range(105),10) # [[0, 10, 20, 30, 40, 50, 60, 70, 8...
Python datetime not including DST when using pytz timezone
2,659,908
12
2010-04-17T20:24:02Z
2,660,005
10
2010-04-17T20:46:47Z
[ "python", "datetime", "timezone", "utc", "pytz" ]
If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this? ``` >>> # Modified for readability >>> import pytz >>> import datetime >>> sweden = pytz.timezone('Europe/Stockholm') >>> >>> datetime....
The `sweden` object specifies the CET time zone by default but contains enough information to know when CEST starts and stop. In the first example, you create a `datetime` object and convert it to local time. The `sweden` object knows that the UTC time you passed occurs during daylight savings time and can convert it ...
Putting newline in matplotlib label with TeX in Python?
2,660,319
26
2010-04-17T22:32:17Z
2,660,334
10
2010-04-17T22:37:40Z
[ "python", "plot", "graphing", "matplotlib" ]
How can I add a newline to a plot's label (e.g. xlabel or ylabel) in matplotlib? For example, ``` plt.bar([1, 2], [4, 5]) plt.xlabel("My x label") plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here") ``` Ideally I'd like the y-labeled to be centered too. Is there a way to do this? It's important that...
Your example is exactly how it's done, you use `\n`. You need to take off the r prefix though so python doesn't treat it as a raw string
Putting newline in matplotlib label with TeX in Python?
2,660,319
26
2010-04-17T22:32:17Z
2,666,270
35
2010-04-19T09:01:09Z
[ "python", "plot", "graphing", "matplotlib" ]
How can I add a newline to a plot's label (e.g. xlabel or ylabel) in matplotlib? For example, ``` plt.bar([1, 2], [4, 5]) plt.xlabel("My x label") plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here") ``` Ideally I'd like the y-labeled to be centered too. Is there a way to do this? It's important that...
You can have the best of both worlds: automatic "escaping" of LaTeX commands *and* newlines: ``` plt.ylabel(r"My long label with unescaped {\LaTeX} $\Sigma_{C}$ math" "\n" r"continues here with $\pi$") ``` (spaces only added for legibility: single spaces would suffice). In fact, Python automati...
tag generation from a text content
2,661,778
33
2010-04-18T09:39:23Z
2,663,346
7
2010-04-18T18:19:09Z
[ "python", "tags", "machine-learning", "nlp", "nltk" ]
I am curious if there is an algorithm/method exists to generate keywords/tags from a given text, by using some weight calculations, occurrence ratio or other tools. Additionally, I will be grateful if you point any Python based solution / library for this. Thanks
First, the key python library for computational linguistics is [NLTK](http://nltk.sourceforge.net/index.php/Main_Page) ("**Natural Language Toolkit**"). This is a stable, mature library created and maintained by professional computational linguists. It also has an extensive [collection](http://www.nltk.org/) of tutoria...
tag generation from a text content
2,661,778
33
2010-04-18T09:39:23Z
2,664,351
46
2010-04-18T22:57:28Z
[ "python", "tags", "machine-learning", "nlp", "nltk" ]
I am curious if there is an algorithm/method exists to generate keywords/tags from a given text, by using some weight calculations, occurrence ratio or other tools. Additionally, I will be grateful if you point any Python based solution / library for this. Thanks
One way to do this would be to extract words that occur more frequently in a document than you would expect them to by chance. For example, say in a larger collection of documents the term 'Markov' is almost never seen. However, in a particular document from the same collection Markov shows up very frequently. This wou...
Getting monitor size in python
2,662,857
5
2010-04-18T15:58:35Z
2,662,892
8
2010-04-18T16:06:31Z
[ "python", "monitor", "fullscreen", "pygame" ]
I am using python and want to create a fullscreen window. I know about the pygame.FULLSCREEN flag but when I use that there's areas of black around the screen. Is there any way to get the monitor size using python so I can make the window the correct size?
Per [the docs](http://www.pygame.org/docs/ref/display.html), `pygame.display.Info` gives you a `VideoInfo` object that has, among other attributes: > `current_w`, `current_h`: Width and > height of the current video mode, or > of the > desktop mode if called before the display.set\_mode is called. `pygame.display.lis...
What are some best practices for structuring cherrypy apps?
2,663,218
5
2010-04-18T17:38:38Z
2,669,586
10
2010-04-19T17:41:50Z
[ "python", "cherrypy", "program-structure" ]
I'm writing a cherrypy app and I was wondering what the best way is for structuring my handlers and code for larger applications? I realize assignment is simple trough cherrypy.root, but what are some practices for writing the handlers and assigning them? (Allow me to prove my confusion!) My initial thought is to wri...
CherryPy deliberately doesn't require you to subclass from a framework-provided base class so that you are free to design your own inheritance mechanism, or, more importantly, use none at all. You are certainly free to define your own base class and inherit from it; in this way, you can standardize handler construction...
Using a Loop to add objects to a list(python)
2,663,391
8
2010-04-18T18:30:33Z
2,663,410
19
2010-04-18T18:34:45Z
[ "python", "list", "object", "loops", "while-loop" ]
Hey guys so im trying to use a while loop to add objects to a list. Heres bascially what i want to do: (ill paste actually go after) ``` class x: blah blah choice = raw_input(pick what you want to do) while(choice!=0): if(choice==1): Enter in info for the class: append object to list (A)...
The problem appears to be that you are reinitializing the list to an empty list in each iteration: ``` while choice != 0: ... a = [] a.append(s) ``` Try moving the initialization above the loop so that it is executed only once. ``` a = [] while choice != 0: ... a.append(s) ```
Elegant way to take basename of directory in Python?
2,663,512
7
2010-04-18T18:56:48Z
2,663,541
7
2010-04-18T19:05:36Z
[ "python", "file-io", "filesystems", "directory-structure" ]
I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the program and use it to make various files in the directory. For example, ``` # directory name given by user via command-line output_dir = "..."...
Use [`os.path.join()`](http://docs.python.org/library/os.path.html#os.path.join) to build up paths. For example: ``` >>> import os.path >>> path = 'foo/bar' >>> os.path.join(path, 'filename') 'foo/bar/filename' >>> path = 'foo/bar/' >>> os.path.join(path, 'filename') 'foo/bar/filename' ```
Elegant way to take basename of directory in Python?
2,663,512
7
2010-04-18T18:56:48Z
2,663,562
12
2010-04-18T19:15:13Z
[ "python", "file-io", "filesystems", "directory-structure" ]
I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the program and use it to make various files in the directory. For example, ``` # directory name given by user via command-line output_dir = "..."...
To deal with your "trailing slash" issue (and other issues!), sanitise user input with `os.path.normpath()`. To build paths, use `os.path.join()`
Nicely representing a floating-point number in python
2,663,612
11
2010-04-18T19:29:00Z
2,663,623
7
2010-04-18T19:31:50Z
[ "python", "floating-point", "representation", "significant-digits" ]
I want to represent a floating-point number as a string rounded to some number of significant digits, and never using the exponential format. Essentially, I want to display any floating-point number and make sure it “looks nice”. There are several parts to this problem: * I need to be able to specify the number of ...
It appears there is no built-in string formatting trick which allows you to (1) print floats whose first significant digit appears after the 15th decimal place and (2) not in scientific notation. So that leaves manual string manipulation. Below I use the `decimal` module to extract the decimal digits from the float. T...
python tracing a segmentation fault
2,663,841
30
2010-04-18T20:35:04Z
2,663,863
25
2010-04-18T20:41:37Z
[ "python", "c", "debugging" ]
I'm developing C extensions from python ad I obtain some segfaults (inevitable during the development...). I'm searching a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how I can do that?
Here's a way to output the filename and line number of every line of Python your code runs: ``` import sys def trace(frame, event, arg): print "%s, %s:%d" % (event, frame.f_code.co_filename, frame.f_lineno) return trace def test(): print "Line 8" print "Line 9" sys.settrace(trace) test() ``` Output...